clang 22.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"
15#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/Template.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
146 return D;
147
148 return nullptr;
149}
150
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
242 if (isa<FunctionTemplateDecl>(FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
281 } else {
282 if (!D) {
284 assert(D && "unambiguous result is not a template name");
285 }
286
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
300 Template);
301 }
302
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
308 } else {
312 TemplateKind =
314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
318 }
319 }
320
322 S->getTemplateParamParent() == nullptr)
323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(Template);
328 return TemplateKind;
329}
330
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
352 if (!TD || !getAsTypeTemplateDecl(TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
358 *Template = TemplateTy::make(Name);
359 }
360 return true;
361}
362
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(IILoc, diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(IILoc, "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
391 bool AllowTypoCorrection) {
392 if (ATK)
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()
412 ->getOriginalDecl()
413 ->isEntityBeingDefined()) &&
414 "Caller should have completed object type");
415
416 // Template names cannot appear inside an Objective-C class or object type
417 // or a vector type.
418 //
419 // FIXME: This is wrong. For example:
420 //
421 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
422 // Vec<int> vi;
423 // vi.Vec<int>::~Vec<int>();
424 //
425 // ... should be accepted but we will not treat 'Vec' as a template name
426 // here. The right thing to do would be to check if the name is a valid
427 // vector component name, and look up a template name if not. And similarly
428 // for lookups into Objective-C class and object types, where the same
429 // problem can arise.
430 if (ObjectType->isObjCObjectOrInterfaceType() ||
431 ObjectType->isVectorType()) {
432 Found.clear();
433 return false;
434 }
435 } else if (SS.isNotEmpty()) {
436 // This nested-name-specifier occurs after another nested-name-specifier,
437 // so long into the context associated with the prior nested-name-specifier.
438 LookupCtx = computeDeclContext(SS, EnteringContext);
439 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
440
441 // The declaration context must be complete.
442 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
443 return true;
444 }
445
446 bool ObjectTypeSearchedInScope = false;
447 bool AllowFunctionTemplatesInLookup = true;
448 if (LookupCtx) {
449 // Perform "qualified" name lookup into the declaration context we
450 // computed, which is either the type of the base of a member access
451 // expression or the declaration context associated with a prior
452 // nested-name-specifier.
453 LookupQualifiedName(Found, LookupCtx);
454
455 // FIXME: The C++ standard does not clearly specify what happens in the
456 // case where the object type is dependent, and implementations vary. In
457 // Clang, we treat a name after a . or -> as a template-name if lookup
458 // finds a non-dependent member or member of the current instantiation that
459 // is a type template, or finds no such members and lookup in the context
460 // of the postfix-expression finds a type template. In the latter case, the
461 // name is nonetheless dependent, and we may resolve it to a member of an
462 // unknown specialization when we come to instantiate the template.
463 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
464 }
465
466 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
467 // C++ [basic.lookup.classref]p1:
468 // In a class member access expression (5.2.5), if the . or -> token is
469 // immediately followed by an identifier followed by a <, the
470 // identifier must be looked up to determine whether the < is the
471 // beginning of a template argument list (14.2) or a less-than operator.
472 // The identifier is first looked up in the class of the object
473 // expression. If the identifier is not found, it is then looked up in
474 // the context of the entire postfix-expression and shall name a class
475 // template.
476 if (S)
477 LookupName(Found, S);
478
479 if (!ObjectType.isNull()) {
480 // FIXME: We should filter out all non-type templates here, particularly
481 // variable templates and concepts. But the exclusion of alias templates
482 // and template template parameters is a wording defect.
483 AllowFunctionTemplatesInLookup = false;
484 ObjectTypeSearchedInScope = true;
485 }
486
487 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
488 }
489
490 if (Found.isAmbiguous())
491 return false;
492
493 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
494 !RequiredTemplate.hasTemplateKeyword()) {
495 // C++2a [temp.names]p2:
496 // A name is also considered to refer to a template if it is an
497 // unqualified-id followed by a < and name lookup finds either one or more
498 // functions or finds nothing.
499 //
500 // To keep our behavior consistent, we apply the "finds nothing" part in
501 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
502 // successfully form a call to an undeclared template-id.
503 bool AllFunctions =
504 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
506 });
507 if (AllFunctions || (Found.empty() && !IsDependent)) {
508 // If lookup found any functions, or if this is a name that can only be
509 // used for a function, then strongly assume this is a function
510 // template-id.
511 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
514 Found.clear();
515 return false;
516 }
517 }
518
519 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
520 // If we did not find any names, and this is not a disambiguation, attempt
521 // to correct any typos.
522 DeclarationName Name = Found.getLookupName();
523 Found.clear();
524 // Simple filter callback that, for keywords, only accepts the C++ *_cast
525 DefaultFilterCCC FilterCCC{};
526 FilterCCC.WantTypeSpecifiers = false;
527 FilterCCC.WantExpressionKeywords = false;
528 FilterCCC.WantRemainingKeywords = false;
529 FilterCCC.WantCXXNamedCasts = true;
530 if (TypoCorrection Corrected = CorrectTypo(
531 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
532 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
533 if (auto *ND = Corrected.getFoundDecl())
534 Found.addDecl(ND);
536 if (Found.isAmbiguous()) {
537 Found.clear();
538 } else if (!Found.empty()) {
539 // Do not erase the typo-corrected result to avoid duplicated
540 // diagnostics.
541 AllowFunctionTemplatesInLookup = true;
542 Found.setLookupName(Corrected.getCorrection());
543 if (LookupCtx) {
544 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
545 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
546 Name.getAsString() == CorrectedStr;
547 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
548 << Name << LookupCtx << DroppedSpecifier
549 << SS.getRange());
550 } else {
551 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
552 }
553 }
554 }
555 }
556
557 NamedDecl *ExampleLookupResult =
558 Found.empty() ? nullptr : Found.getRepresentativeDecl();
559 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
560 if (Found.empty()) {
561 if (IsDependent) {
562 Found.setNotFoundInCurrentInstantiation();
563 return false;
564 }
565
566 // If a 'template' keyword was used, a lookup that finds only non-template
567 // names is an error.
568 if (ExampleLookupResult && RequiredTemplate) {
569 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
570 << Found.getLookupName() << SS.getRange()
571 << RequiredTemplate.hasTemplateKeyword()
572 << RequiredTemplate.getTemplateKeywordLoc();
573 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
574 diag::note_template_kw_refers_to_non_template)
575 << Found.getLookupName();
576 return true;
577 }
578
579 return false;
580 }
581
582 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
584 // C++03 [basic.lookup.classref]p1:
585 // [...] If the lookup in the class of the object expression finds a
586 // template, the name is also looked up in the context of the entire
587 // postfix-expression and [...]
588 //
589 // Note: C++11 does not perform this second lookup.
590 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
592 FoundOuter.setTemplateNameLookup(true);
593 LookupName(FoundOuter, S);
594 // FIXME: We silently accept an ambiguous lookup here, in violation of
595 // [basic.lookup]/1.
596 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
597
598 NamedDecl *OuterTemplate;
599 if (FoundOuter.empty()) {
600 // - if the name is not found, the name found in the class of the
601 // object expression is used, otherwise
602 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
603 !(OuterTemplate =
604 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
605 // - if the name is found in the context of the entire
606 // postfix-expression and does not name a class template, the name
607 // found in the class of the object expression is used, otherwise
608 FoundOuter.clear();
609 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
610 // - if the name found is a class template, it must refer to the same
611 // entity as the one found in the class of the object expression,
612 // otherwise the program is ill-formed.
613 if (!Found.isSingleResult() ||
614 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
615 OuterTemplate->getCanonicalDecl()) {
616 Diag(Found.getNameLoc(),
617 diag::ext_nested_name_member_ref_lookup_ambiguous)
618 << Found.getLookupName()
619 << ObjectType;
620 Diag(Found.getRepresentativeDecl()->getLocation(),
621 diag::note_ambig_member_ref_object_type)
622 << ObjectType;
623 Diag(FoundOuter.getFoundDecl()->getLocation(),
624 diag::note_ambig_member_ref_scope);
625
626 // Recover by taking the template that we found in the object
627 // expression's type.
628 }
629 }
630 }
631
632 return false;
633}
634
638 if (TemplateName.isInvalid())
639 return;
640
641 DeclarationNameInfo NameInfo;
642 CXXScopeSpec SS;
643 LookupNameKind LookupKind;
644
645 DeclContext *LookupCtx = nullptr;
646 NamedDecl *Found = nullptr;
647 bool MissingTemplateKeyword = false;
648
649 // Figure out what name we looked up.
650 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
651 NameInfo = DRE->getNameInfo();
652 SS.Adopt(DRE->getQualifierLoc());
653 LookupKind = LookupOrdinaryName;
654 Found = DRE->getFoundDecl();
655 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
656 NameInfo = ME->getMemberNameInfo();
657 SS.Adopt(ME->getQualifierLoc());
658 LookupKind = LookupMemberName;
659 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
660 Found = ME->getMemberDecl();
661 } else if (auto *DSDRE =
662 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
663 NameInfo = DSDRE->getNameInfo();
664 SS.Adopt(DSDRE->getQualifierLoc());
665 MissingTemplateKeyword = true;
666 } else if (auto *DSME =
667 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
668 NameInfo = DSME->getMemberNameInfo();
669 SS.Adopt(DSME->getQualifierLoc());
670 MissingTemplateKeyword = true;
671 } else {
672 llvm_unreachable("unexpected kind of potential template name");
673 }
674
675 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
676 // was missing.
677 if (MissingTemplateKeyword) {
678 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
679 << NameInfo.getName() << SourceRange(Less, Greater);
680 return;
681 }
682
683 // Try to correct the name by looking for templates and C++ named casts.
684 struct TemplateCandidateFilter : CorrectionCandidateCallback {
685 Sema &S;
686 TemplateCandidateFilter(Sema &S) : S(S) {
687 WantTypeSpecifiers = false;
688 WantExpressionKeywords = false;
689 WantRemainingKeywords = false;
690 WantCXXNamedCasts = true;
691 };
692 bool ValidateCandidate(const TypoCorrection &Candidate) override {
693 if (auto *ND = Candidate.getCorrectionDecl())
694 return S.getAsTemplateNameDecl(ND);
695 return Candidate.isKeyword();
696 }
697
698 std::unique_ptr<CorrectionCandidateCallback> clone() override {
699 return std::make_unique<TemplateCandidateFilter>(*this);
700 }
701 };
702
703 DeclarationName Name = NameInfo.getName();
704 TemplateCandidateFilter CCC(*this);
705 if (TypoCorrection Corrected =
706 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
707 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
708 auto *ND = Corrected.getFoundDecl();
709 if (ND)
710 ND = getAsTemplateNameDecl(ND);
711 if (ND || Corrected.isKeyword()) {
712 if (LookupCtx) {
713 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
714 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
715 Name.getAsString() == CorrectedStr;
716 diagnoseTypo(Corrected,
717 PDiag(diag::err_non_template_in_member_template_id_suggest)
718 << Name << LookupCtx << DroppedSpecifier
719 << SS.getRange(), false);
720 } else {
721 diagnoseTypo(Corrected,
722 PDiag(diag::err_non_template_in_template_id_suggest)
723 << Name, false);
724 }
725 if (Found)
726 Diag(Found->getLocation(),
727 diag::note_non_template_in_template_id_found);
728 return;
729 }
730 }
731
732 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
733 << Name << SourceRange(Less, Greater);
734 if (Found)
735 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
736}
737
740 SourceLocation TemplateKWLoc,
741 const DeclarationNameInfo &NameInfo,
742 bool isAddressOfOperand,
743 const TemplateArgumentListInfo *TemplateArgs) {
744 if (SS.isEmpty()) {
745 // FIXME: This codepath is only used by dependent unqualified names
746 // (e.g. a dependent conversion-function-id, or operator= once we support
747 // it). It doesn't quite do the right thing, and it will silently fail if
748 // getCurrentThisType() returns null.
749 QualType ThisType = getCurrentThisType();
750 if (ThisType.isNull())
751 return ExprError();
752
754 Context, /*Base=*/nullptr, ThisType,
755 /*IsArrow=*/!Context.getLangOpts().HLSL,
756 /*OperatorLoc=*/SourceLocation(),
757 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
758 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
759 }
760 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
761}
762
765 SourceLocation TemplateKWLoc,
766 const DeclarationNameInfo &NameInfo,
767 const TemplateArgumentListInfo *TemplateArgs) {
768 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
769 if (!SS.isValid())
770 return CreateRecoveryExpr(
771 SS.getBeginLoc(),
772 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
773
775 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
776 TemplateArgs);
777}
778
780 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
782 bool Final) {
783 // The template argument itself might be an expression, in which case we just
784 // return that expression. This happens when substituting into an alias
785 // template.
786 Expr *Replacement;
787 bool refParam = true;
789 Replacement = Arg.getAsExpr();
790 refParam = Replacement->isLValue();
791 if (refParam && Replacement->getType()->isRecordType()) {
792 QualType ParamType =
794 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
795 : NTTP->getType();
796 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))
797 ParamType = PET->getPattern();
798 refParam = ParamType->isReferenceType();
799 }
800 } else {
801 ExprResult result =
802 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
803 if (result.isInvalid())
804 return ExprError();
805 Replacement = result.get();
807 }
808 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
809 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
810 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
811}
812
814 NamedDecl *Instantiation,
815 bool InstantiatedFromMember,
816 const NamedDecl *Pattern,
817 const NamedDecl *PatternDef,
819 bool Complain, bool *Unreachable) {
820 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
821 isa<VarDecl>(Instantiation));
822
823 bool IsEntityBeingDefined = false;
824 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
825 IsEntityBeingDefined = TD->isBeingDefined();
826
827 if (PatternDef && !IsEntityBeingDefined) {
828 NamedDecl *SuggestedDef = nullptr;
829 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
830 &SuggestedDef,
831 /*OnlyNeedComplete*/ false)) {
832 if (Unreachable)
833 *Unreachable = true;
834 // If we're allowed to diagnose this and recover, do so.
835 bool Recover = Complain && !isSFINAEContext();
836 if (Complain)
837 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
839 return !Recover;
840 }
841 return false;
842 }
843
844 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
845 return true;
846
847 CanQualType InstantiationTy;
848 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
849 InstantiationTy = Context.getCanonicalTagType(TD);
850 if (PatternDef) {
851 Diag(PointOfInstantiation,
852 diag::err_template_instantiate_within_definition)
853 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
854 << InstantiationTy;
855 // Not much point in noting the template declaration here, since
856 // we're lexically inside it.
857 Instantiation->setInvalidDecl();
858 } else if (InstantiatedFromMember) {
859 if (isa<FunctionDecl>(Instantiation)) {
860 Diag(PointOfInstantiation,
861 diag::err_explicit_instantiation_undefined_member)
862 << /*member function*/ 1 << Instantiation->getDeclName()
863 << Instantiation->getDeclContext();
864 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
865 } else {
866 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
867 Diag(PointOfInstantiation,
868 diag::err_implicit_instantiate_member_undefined)
869 << InstantiationTy;
870 Diag(Pattern->getLocation(), diag::note_member_declared_at);
871 }
872 } else {
873 if (isa<FunctionDecl>(Instantiation)) {
874 Diag(PointOfInstantiation,
875 diag::err_explicit_instantiation_undefined_func_template)
876 << Pattern;
877 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
878 } else if (isa<TagDecl>(Instantiation)) {
879 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
880 << (TSK != TSK_ImplicitInstantiation)
881 << InstantiationTy;
882 NoteTemplateLocation(*Pattern);
883 } else {
884 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
885 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
886 Diag(PointOfInstantiation,
887 diag::err_explicit_instantiation_undefined_var_template)
888 << Instantiation;
889 Instantiation->setInvalidDecl();
890 } else
891 Diag(PointOfInstantiation,
892 diag::err_explicit_instantiation_undefined_member)
893 << /*static data member*/ 2 << Instantiation->getDeclName()
894 << Instantiation->getDeclContext();
895 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
896 }
897 }
898
899 // In general, Instantiation isn't marked invalid to get more than one
900 // error for multiple undefined instantiations. But the code that does
901 // explicit declaration -> explicit definition conversion can't handle
902 // invalid declarations, so mark as invalid in that case.
904 Instantiation->setInvalidDecl();
905 return true;
906}
907
909 bool SupportedForCompatibility) {
910 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
911
912 // C++23 [temp.local]p6:
913 // The name of a template-parameter shall not be bound to any following.
914 // declaration whose locus is contained by the scope to which the
915 // template-parameter belongs.
916 //
917 // When MSVC compatibility is enabled, the diagnostic is always a warning
918 // by default. Otherwise, it an error unless SupportedForCompatibility is
919 // true, in which case it is a default-to-error warning.
920 unsigned DiagId =
921 getLangOpts().MSVCCompat
922 ? diag::ext_template_param_shadow
923 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
924 : diag::err_template_param_shadow);
925 const auto *ND = cast<NamedDecl>(PrevDecl);
926 Diag(Loc, DiagId) << ND->getDeclName();
928}
929
931 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
932 D = Temp->getTemplatedDecl();
933 return Temp;
934 }
935 return nullptr;
936}
937
939 SourceLocation EllipsisLoc) const {
940 assert(Kind == Template &&
941 "Only template template arguments can be pack expansions here");
942 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
943 "Template template argument pack expansion without packs");
945 Result.EllipsisLoc = EllipsisLoc;
946 return Result;
947}
948
950 const ParsedTemplateArgument &Arg) {
951
952 switch (Arg.getKind()) {
954 TypeSourceInfo *DI;
955 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
956 if (!DI)
957 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
959 }
960
962 Expr *E = Arg.getAsExpr();
963 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
964 }
965
968 TemplateArgument TArg;
969 if (Arg.getEllipsisLoc().isValid())
970 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
971 else
972 TArg = Template;
973 return TemplateArgumentLoc(
974 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
976 Arg.getNameLoc(), Arg.getEllipsisLoc());
977 }
978 }
979
980 llvm_unreachable("Unhandled parsed template argument");
981}
982
984 TemplateArgumentListInfo &TemplateArgs) {
985 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
986 TemplateArgs.addArgument(translateTemplateArgument(*this,
987 TemplateArgsIn[I]));
988}
989
991 SourceLocation Loc,
992 const IdentifierInfo *Name) {
993 NamedDecl *PrevDecl =
994 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
996 if (PrevDecl && PrevDecl->isTemplateParameter())
997 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
998}
999
1001 TypeSourceInfo *TInfo;
1002 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1003 if (T.isNull())
1004 return ParsedTemplateArgument();
1005 assert(TInfo && "template argument with no location");
1006
1007 // If we might have formed a deduced template specialization type, convert
1008 // it to a template template argument.
1009 if (getLangOpts().CPlusPlus17) {
1010 TypeLoc TL = TInfo->getTypeLoc();
1011 SourceLocation EllipsisLoc;
1012 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1013 EllipsisLoc = PET.getEllipsisLoc();
1014 TL = PET.getPatternLoc();
1015 }
1016
1017 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1018 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1019 CXXScopeSpec SS;
1020 SS.Adopt(DTST.getQualifierLoc());
1021 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1022 TemplateTy::make(Name),
1023 DTST.getTemplateNameLoc());
1024 if (EllipsisLoc.isValid())
1025 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1026 return Result;
1027 }
1028 }
1029
1030 // This is a normal type template argument. Note, if the type template
1031 // argument is an injected-class-name for a template, it has a dual nature
1032 // and can be used as either a type or a template. We handle that in
1033 // convertTypeTemplateArgumentToTemplate.
1035 ParsedType.get().getAsOpaquePtr(),
1036 TInfo->getTypeLoc().getBeginLoc());
1037}
1038
1040 SourceLocation EllipsisLoc,
1041 SourceLocation KeyLoc,
1042 IdentifierInfo *ParamName,
1043 SourceLocation ParamNameLoc,
1044 unsigned Depth, unsigned Position,
1045 SourceLocation EqualLoc,
1046 ParsedType DefaultArg,
1047 bool HasTypeConstraint) {
1048 assert(S->isTemplateParamScope() &&
1049 "Template type parameter not in template parameter scope!");
1050
1051 bool IsParameterPack = EllipsisLoc.isValid();
1053 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1054 KeyLoc, ParamNameLoc, Depth, Position,
1055 ParamName, Typename, IsParameterPack,
1056 HasTypeConstraint);
1057 Param->setAccess(AS_public);
1058
1059 if (Param->isParameterPack())
1060 if (auto *CSI = getEnclosingLambdaOrBlock())
1061 CSI->LocalPacks.push_back(Param);
1062
1063 if (ParamName) {
1064 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1065
1066 // Add the template parameter into the current scope.
1067 S->AddDecl(Param);
1068 IdResolver.AddDecl(Param);
1069 }
1070
1071 // C++0x [temp.param]p9:
1072 // A default template-argument may be specified for any kind of
1073 // template-parameter that is not a template parameter pack.
1074 if (DefaultArg && IsParameterPack) {
1075 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1076 DefaultArg = nullptr;
1077 }
1078
1079 // Handle the default argument, if provided.
1080 if (DefaultArg) {
1081 TypeSourceInfo *DefaultTInfo;
1082 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1083
1084 assert(DefaultTInfo && "expected source information for type");
1085
1086 // Check for unexpanded parameter packs.
1087 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1089 return Param;
1090
1091 // Check the template argument itself.
1092 if (CheckTemplateArgument(DefaultTInfo)) {
1093 Param->setInvalidDecl();
1094 return Param;
1095 }
1096
1097 Param->setDefaultArgument(
1098 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1099 }
1100
1101 return Param;
1102}
1103
1104/// Convert the parser's template argument list representation into our form.
1107 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1108 TemplateId.RAngleLoc);
1109 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1110 TemplateId.NumArgs);
1111 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1112 return TemplateArgs;
1113}
1114
1116
1117 TemplateName TN = TypeConstr->Template.get();
1118 NamedDecl *CD = nullptr;
1119 bool IsTypeConcept = false;
1120 bool RequiresArguments = false;
1121 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1122 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1123 RequiresArguments =
1124 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1125 CD = TTP;
1126 } else {
1127 CD = TN.getAsTemplateDecl();
1128 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1129 RequiresArguments = cast<ConceptDecl>(CD)
1130 ->getTemplateParameters()
1131 ->getMinRequiredArguments() > 1;
1132 }
1133
1134 // C++2a [temp.param]p4:
1135 // [...] The concept designated by a type-constraint shall be a type
1136 // concept ([temp.concept]).
1137 if (!IsTypeConcept) {
1138 Diag(TypeConstr->TemplateNameLoc,
1139 diag::err_type_constraint_non_type_concept);
1140 return true;
1141 }
1142
1143 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1144 return true;
1145
1146 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1147
1148 if (!WereArgsSpecified && RequiresArguments) {
1149 Diag(TypeConstr->TemplateNameLoc,
1150 diag::err_type_constraint_missing_arguments)
1151 << CD;
1152 return true;
1153 }
1154 return false;
1155}
1156
1158 TemplateIdAnnotation *TypeConstr,
1159 TemplateTypeParmDecl *ConstrainedParameter,
1160 SourceLocation EllipsisLoc) {
1161 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1162 false);
1163}
1164
1166 TemplateIdAnnotation *TypeConstr,
1167 TemplateTypeParmDecl *ConstrainedParameter,
1168 SourceLocation EllipsisLoc,
1169 bool AllowUnexpandedPack) {
1170
1171 if (CheckTypeConstraint(TypeConstr))
1172 return true;
1173
1174 TemplateName TN = TypeConstr->Template.get();
1177
1178 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1179 TypeConstr->TemplateNameLoc);
1180
1181 TemplateArgumentListInfo TemplateArgs;
1182 if (TypeConstr->LAngleLoc.isValid()) {
1183 TemplateArgs =
1184 makeTemplateArgumentListInfo(*this, *TypeConstr);
1185
1186 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1187 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1189 return true;
1190 }
1191 }
1192 }
1193 return AttachTypeConstraint(
1195 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1196 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1197 ConstrainedParameter, EllipsisLoc);
1198}
1199
1200template <typename ArgumentLocAppender>
1203 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1204 SourceLocation RAngleLoc, QualType ConstrainedType,
1205 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1206 SourceLocation EllipsisLoc) {
1207
1208 TemplateArgumentListInfo ConstraintArgs;
1209 ConstraintArgs.addArgument(
1211 /*NTTPType=*/QualType(), ParamNameLoc));
1212
1213 ConstraintArgs.setRAngleLoc(RAngleLoc);
1214 ConstraintArgs.setLAngleLoc(LAngleLoc);
1215 Appender(ConstraintArgs);
1216
1217 // C++2a [temp.param]p4:
1218 // [...] This constraint-expression E is called the immediately-declared
1219 // constraint of T. [...]
1220 CXXScopeSpec SS;
1221 SS.Adopt(NS);
1222 ExprResult ImmediatelyDeclaredConstraint;
1223 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1224 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1225 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1226 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1227 /*DoCheckConstraintSatisfaction=*/
1229 }
1230 // We have a template template parameter
1231 else {
1232 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1233 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1234 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1235 }
1236 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1237 return ImmediatelyDeclaredConstraint;
1238
1239 // C++2a [temp.param]p4:
1240 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1241 //
1242 // We have the following case:
1243 //
1244 // template<typename T> concept C1 = true;
1245 // template<C1... T> struct s1;
1246 //
1247 // The constraint: (C1<T> && ...)
1248 //
1249 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1250 // any unqualified lookups for 'operator&&' here.
1251 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1252 /*LParenLoc=*/SourceLocation(),
1253 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1254 EllipsisLoc, /*RHS=*/nullptr,
1255 /*RParenLoc=*/SourceLocation(),
1256 /*NumExpansions=*/std::nullopt);
1257}
1258
1260 DeclarationNameInfo NameInfo,
1261 TemplateDecl *NamedConcept,
1262 NamedDecl *FoundDecl,
1263 const TemplateArgumentListInfo *TemplateArgs,
1264 TemplateTypeParmDecl *ConstrainedParameter,
1265 SourceLocation EllipsisLoc) {
1266 // C++2a [temp.param]p4:
1267 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1268 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1269 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1271 *TemplateArgs) : nullptr;
1272
1273 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1274
1275 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1276 *this, NS, NameInfo, NamedConcept, FoundDecl,
1277 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1278 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1279 ParamAsArgument, ConstrainedParameter->getLocation(),
1280 [&](TemplateArgumentListInfo &ConstraintArgs) {
1281 if (TemplateArgs)
1282 for (const auto &ArgLoc : TemplateArgs->arguments())
1283 ConstraintArgs.addArgument(ArgLoc);
1284 },
1285 EllipsisLoc);
1286 if (ImmediatelyDeclaredConstraint.isInvalid())
1287 return true;
1288
1289 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1290 /*TemplateKWLoc=*/SourceLocation{},
1291 /*ConceptNameInfo=*/NameInfo,
1292 /*FoundDecl=*/FoundDecl,
1293 /*NamedConcept=*/NamedConcept,
1294 /*ArgsWritten=*/ArgsAsWritten);
1295 ConstrainedParameter->setTypeConstraint(
1296 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1297 return false;
1298}
1299
1301 NonTypeTemplateParmDecl *NewConstrainedParm,
1302 NonTypeTemplateParmDecl *OrigConstrainedParm,
1303 SourceLocation EllipsisLoc) {
1304 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1306 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1307 diag::err_unsupported_placeholder_constraint)
1308 << NewConstrainedParm->getTypeSourceInfo()
1309 ->getTypeLoc()
1310 .getSourceRange();
1311 return true;
1312 }
1313 // FIXME: Concepts: This should be the type of the placeholder, but this is
1314 // unclear in the wording right now.
1315 DeclRefExpr *Ref =
1316 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1317 VK_PRValue, OrigConstrainedParm->getLocation());
1318 if (!Ref)
1319 return true;
1320 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1322 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1324 OrigConstrainedParm->getLocation(),
1325 [&](TemplateArgumentListInfo &ConstraintArgs) {
1326 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1327 ConstraintArgs.addArgument(TL.getArgLoc(I));
1328 },
1329 EllipsisLoc);
1330 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1331 !ImmediatelyDeclaredConstraint.isUsable())
1332 return true;
1333
1334 NewConstrainedParm->setPlaceholderTypeConstraint(
1335 ImmediatelyDeclaredConstraint.get());
1336 return false;
1337}
1338
1340 SourceLocation Loc) {
1341 if (TSI->getType()->isUndeducedType()) {
1342 // C++17 [temp.dep.expr]p3:
1343 // An id-expression is type-dependent if it contains
1344 // - an identifier associated by name lookup with a non-type
1345 // template-parameter declared with a type that contains a
1346 // placeholder type (7.1.7.4),
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1351}
1352
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(SubLoc, diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 // C++ [temp.param]p4:
1463 //
1464 // A non-type template-parameter shall have one of the following
1465 // (optionally cv-qualified) types:
1466 //
1467 // -- integral or enumeration type,
1468 if (T->isIntegralOrEnumerationType() ||
1469 // -- pointer to object or pointer to function,
1470 T->isPointerType() ||
1471 // -- lvalue reference to object or lvalue reference to function,
1472 T->isLValueReferenceType() ||
1473 // -- pointer to member,
1474 T->isMemberPointerType() ||
1475 // -- std::nullptr_t, or
1476 T->isNullPtrType() ||
1477 // -- a type that contains a placeholder type.
1478 T->isUndeducedType()) {
1479 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1480 // are ignored when determining its type.
1481 return T.getUnqualifiedType();
1482 }
1483
1484 // C++ [temp.param]p8:
1485 //
1486 // A non-type template-parameter of type "array of T" or
1487 // "function returning T" is adjusted to be of type "pointer to
1488 // T" or "pointer to function returning T", respectively.
1489 if (T->isArrayType() || T->isFunctionType())
1490 return Context.getDecayedType(T);
1491
1492 // If T is a dependent type, we can't do the check now, so we
1493 // assume that it is well-formed. Note that stripping off the
1494 // qualifiers here is not really correct if T turns out to be
1495 // an array type, but we'll recompute the type everywhere it's
1496 // used during instantiation, so that should be OK. (Using the
1497 // qualified type is equally wrong.)
1498 if (T->isDependentType())
1499 return T.getUnqualifiedType();
1500
1501 // C++20 [temp.param]p6:
1502 // -- a structural type
1503 if (RequireStructuralType(T, Loc))
1504 return QualType();
1505
1506 if (!getLangOpts().CPlusPlus20) {
1507 // FIXME: Consider allowing structural types as an extension in C++17. (In
1508 // earlier language modes, the template argument evaluation rules are too
1509 // inflexible.)
1510 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1511 return QualType();
1512 }
1513
1514 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1515 return T.getUnqualifiedType();
1516}
1517
1519 unsigned Depth,
1520 unsigned Position,
1521 SourceLocation EqualLoc,
1522 Expr *Default) {
1524
1525 // Check that we have valid decl-specifiers specified.
1526 auto CheckValidDeclSpecifiers = [this, &D] {
1527 // C++ [temp.param]
1528 // p1
1529 // template-parameter:
1530 // ...
1531 // parameter-declaration
1532 // p2
1533 // ... A storage class shall not be specified in a template-parameter
1534 // declaration.
1535 // [dcl.typedef]p1:
1536 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1537 // of a parameter-declaration
1538 const DeclSpec &DS = D.getDeclSpec();
1539 auto EmitDiag = [this](SourceLocation Loc) {
1540 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1542 };
1544 EmitDiag(DS.getStorageClassSpecLoc());
1545
1547 EmitDiag(DS.getThreadStorageClassSpecLoc());
1548
1549 // [dcl.inline]p1:
1550 // The inline specifier can be applied only to the declaration or
1551 // definition of a variable or function.
1552
1553 if (DS.isInlineSpecified())
1554 EmitDiag(DS.getInlineSpecLoc());
1555
1556 // [dcl.constexpr]p1:
1557 // The constexpr specifier shall be applied only to the definition of a
1558 // variable or variable template or the declaration of a function or
1559 // function template.
1560
1561 if (DS.hasConstexprSpecifier())
1562 EmitDiag(DS.getConstexprSpecLoc());
1563
1564 // [dcl.fct.spec]p1:
1565 // Function-specifiers can be used only in function declarations.
1566
1567 if (DS.isVirtualSpecified())
1568 EmitDiag(DS.getVirtualSpecLoc());
1569
1570 if (DS.hasExplicitSpecifier())
1571 EmitDiag(DS.getExplicitSpecLoc());
1572
1573 if (DS.isNoreturnSpecified())
1574 EmitDiag(DS.getNoreturnSpecLoc());
1575 };
1576
1577 CheckValidDeclSpecifiers();
1578
1579 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1580 if (isa<AutoType>(T))
1582 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1583 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1584
1585 assert(S->isTemplateParamScope() &&
1586 "Non-type template parameter not in template parameter scope!");
1587 bool Invalid = false;
1588
1590 if (T.isNull()) {
1591 T = Context.IntTy; // Recover with an 'int' type.
1592 Invalid = true;
1593 }
1594
1596
1597 const IdentifierInfo *ParamName = D.getIdentifier();
1598 bool IsParameterPack = D.hasEllipsis();
1600 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1601 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1602 TInfo);
1603 Param->setAccess(AS_public);
1604
1606 if (TL.isConstrained()) {
1607 if (D.getEllipsisLoc().isInvalid() &&
1608 T->containsUnexpandedParameterPack()) {
1609 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1610 for (auto &Loc :
1611 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1614 }
1615 if (!Invalid &&
1616 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1617 Invalid = true;
1618 }
1619
1620 if (Invalid)
1621 Param->setInvalidDecl();
1622
1623 if (Param->isParameterPack())
1624 if (auto *CSI = getEnclosingLambdaOrBlock())
1625 CSI->LocalPacks.push_back(Param);
1626
1627 if (ParamName) {
1629 ParamName);
1630
1631 // Add the template parameter into the current scope.
1632 S->AddDecl(Param);
1633 IdResolver.AddDecl(Param);
1634 }
1635
1636 // C++0x [temp.param]p9:
1637 // A default template-argument may be specified for any kind of
1638 // template-parameter that is not a template parameter pack.
1639 if (Default && IsParameterPack) {
1640 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1641 Default = nullptr;
1642 }
1643
1644 // Check the well-formedness of the default template argument, if provided.
1645 if (Default) {
1646 // Check for unexpanded parameter packs.
1648 return Param;
1649
1650 Param->setDefaultArgument(
1652 TemplateArgument(Default, /*IsCanonical=*/false),
1653 QualType(), SourceLocation()));
1654 }
1655
1656 return Param;
1657}
1658
1659/// ActOnTemplateTemplateParameter - Called when a C++ template template
1660/// parameter (e.g. T in template <template <typename> class T> class array)
1661/// has been parsed. S is the current scope.
1663 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1664 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1665 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1666 unsigned Position, SourceLocation EqualLoc,
1668 assert(S->isTemplateParamScope() &&
1669 "Template template parameter not in template parameter scope!");
1670
1671 bool IsParameterPack = EllipsisLoc.isValid();
1672
1673 bool Invalid = false;
1675 Params,
1676 /*OldParams=*/nullptr,
1677 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1678 Invalid = true;
1679
1680 // Construct the parameter object.
1682 Context, Context.getTranslationUnitDecl(),
1683 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1684 Name, Kind, Typename, Params);
1685 Param->setAccess(AS_public);
1686
1687 if (Param->isParameterPack())
1688 if (auto *LSI = getEnclosingLambdaOrBlock())
1689 LSI->LocalPacks.push_back(Param);
1690
1691 // If the template template parameter has a name, then link the identifier
1692 // into the scope and lookup mechanisms.
1693 if (Name) {
1694 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1695
1696 S->AddDecl(Param);
1697 IdResolver.AddDecl(Param);
1698 }
1699
1700 if (Params->size() == 0) {
1701 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1702 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1703 Invalid = true;
1704 }
1705
1706 if (Invalid)
1707 Param->setInvalidDecl();
1708
1709 // C++0x [temp.param]p9:
1710 // A default template-argument may be specified for any kind of
1711 // template-parameter that is not a template parameter pack.
1712 if (IsParameterPack && !Default.isInvalid()) {
1713 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1715 }
1716
1717 if (!Default.isInvalid()) {
1718 // Check only that we have a template template argument. We don't want to
1719 // try to check well-formedness now, because our template template parameter
1720 // might have dependent types in its template parameters, which we wouldn't
1721 // be able to match now.
1722 //
1723 // If none of the template template parameter's template arguments mention
1724 // other template parameters, we could actually perform more checking here.
1725 // However, it isn't worth doing.
1727 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1728 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1729 << DefaultArg.getSourceRange();
1730 return Param;
1731 }
1732
1733 TemplateName Name =
1736 if (Template &&
1738 return Param;
1739 }
1740
1741 // Check for unexpanded parameter packs.
1743 DefaultArg.getArgument().getAsTemplate(),
1745 return Param;
1746
1747 Param->setDefaultArgument(Context, DefaultArg);
1748 }
1749
1750 return Param;
1751}
1752
1753namespace {
1754class ConstraintRefersToContainingTemplateChecker
1756 using inherited = ConstDynamicRecursiveASTVisitor;
1757 bool Result = false;
1758 const FunctionDecl *Friend = nullptr;
1759 unsigned TemplateDepth = 0;
1760
1761 // Check a record-decl that we've seen to see if it is a lexical parent of the
1762 // Friend, likely because it was referred to without its template arguments.
1763 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1764 CheckingRD = CheckingRD->getMostRecentDecl();
1765 if (!CheckingRD->isTemplated())
1766 return true;
1767
1768 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1769 DC && !DC->isFileContext(); DC = DC->getParent())
1770 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1771 if (CheckingRD == RD->getMostRecentDecl()) {
1772 Result = true;
1773 return false;
1774 }
1775
1776 return true;
1777 }
1778
1779 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1780 if (D->getDepth() < TemplateDepth)
1781 Result = true;
1782
1783 // Necessary because the type of the NTTP might be what refers to the parent
1784 // constriant.
1785 return TraverseType(D->getType());
1786 }
1787
1788public:
1789 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1790 unsigned TemplateDepth)
1791 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1792
1793 bool getResult() const { return Result; }
1794
1795 // This should be the only template parm type that we have to deal with.
1796 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1797 // FunctionParmPackExpr are all partially substituted, which cannot happen
1798 // with concepts at this point in translation.
1799 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1800 if (Type->getDecl()->getDepth() < TemplateDepth) {
1801 Result = true;
1802 return false;
1803 }
1804 return true;
1805 }
1806
1807 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1808 return TraverseDecl(E->getDecl());
1809 }
1810
1811 bool TraverseTypedefType(const TypedefType *TT,
1812 bool /*TraverseQualifier*/) override {
1813 return TraverseType(TT->desugar());
1814 }
1815
1816 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1817 // We don't care about TypeLocs. So traverse Types instead.
1818 return TraverseType(TL.getType(), TraverseQualifier);
1819 }
1820
1821 bool VisitTagType(const TagType *T) override {
1822 return TraverseDecl(T->getOriginalDecl());
1823 }
1824
1825 bool TraverseDecl(const Decl *D) override {
1826 assert(D);
1827 // FIXME : This is possibly an incomplete list, but it is unclear what other
1828 // Decl kinds could be used to refer to the template parameters. This is a
1829 // best guess so far based on examples currently available, but the
1830 // unreachable should catch future instances/cases.
1831 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1832 return TraverseType(TD->getUnderlyingType());
1833 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1834 return CheckNonTypeTemplateParmDecl(NTTPD);
1835 if (auto *VD = dyn_cast<ValueDecl>(D))
1836 return TraverseType(VD->getType());
1837 if (isa<TemplateDecl>(D))
1838 return true;
1839 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1840 return CheckIfContainingRecord(RD);
1841
1843 // No direct types to visit here I believe.
1844 } else
1845 llvm_unreachable("Don't know how to handle this declaration type yet");
1846 return true;
1847 }
1848};
1849} // namespace
1850
1852 const FunctionDecl *Friend, unsigned TemplateDepth,
1853 const Expr *Constraint) {
1854 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1855 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1856 Checker.TraverseStmt(Constraint);
1857 return Checker.getResult();
1858}
1859
1862 SourceLocation ExportLoc,
1863 SourceLocation TemplateLoc,
1864 SourceLocation LAngleLoc,
1865 ArrayRef<NamedDecl *> Params,
1866 SourceLocation RAngleLoc,
1867 Expr *RequiresClause) {
1868 if (ExportLoc.isValid())
1869 Diag(ExportLoc, diag::warn_template_export_unsupported);
1870
1871 for (NamedDecl *P : Params)
1873
1874 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1875 llvm::ArrayRef(Params), RAngleLoc,
1876 RequiresClause);
1877}
1878
1880 const CXXScopeSpec &SS) {
1881 if (SS.isSet())
1882 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1883}
1884
1885// Returns the template parameter list with all default template argument
1886// information.
1888 // Make sure we get the template parameter list from the most
1889 // recent declaration, since that is the only one that is guaranteed to
1890 // have all the default template argument information.
1891 Decl *D = TD->getMostRecentDecl();
1892 // C++11 N3337 [temp.param]p12:
1893 // A default template argument shall not be specified in a friend class
1894 // template declaration.
1895 //
1896 // Skip past friend *declarations* because they are not supposed to contain
1897 // default template arguments. Moreover, these declarations may introduce
1898 // template parameters living in different template depths than the
1899 // corresponding template parameters in TD, causing unmatched constraint
1900 // substitution.
1901 //
1902 // FIXME: Diagnose such cases within a class template:
1903 // template <class T>
1904 // struct S {
1905 // template <class = void> friend struct C;
1906 // };
1907 // template struct S<int>;
1909 D->getPreviousDecl())
1910 D = D->getPreviousDecl();
1911 return cast<TemplateDecl>(D)->getTemplateParameters();
1912}
1913
1915 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1916 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1917 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1918 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1919 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1920 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1921 assert(TemplateParams && TemplateParams->size() > 0 &&
1922 "No template parameters");
1923 assert(TUK != TagUseKind::Reference &&
1924 "Can only declare or define class templates");
1925 bool Invalid = false;
1926
1927 // Check that we can declare a template here.
1928 if (CheckTemplateDeclScope(S, TemplateParams))
1929 return true;
1930
1932 assert(Kind != TagTypeKind::Enum &&
1933 "can't build template of enumerated type");
1934
1935 // There is no such thing as an unnamed class template.
1936 if (!Name) {
1937 Diag(KWLoc, diag::err_template_unnamed_class);
1938 return true;
1939 }
1940
1941 // Find any previous declaration with this name. For a friend with no
1942 // scope explicitly specified, we only look for tag declarations (per
1943 // C++11 [basic.lookup.elab]p2).
1944 DeclContext *SemanticContext;
1945 LookupResult Previous(*this, Name, NameLoc,
1946 (SS.isEmpty() && TUK == TagUseKind::Friend)
1950 if (SS.isNotEmpty() && !SS.isInvalid()) {
1951 SemanticContext = computeDeclContext(SS, true);
1952 if (!SemanticContext) {
1953 // FIXME: Horrible, horrible hack! We can't currently represent this
1954 // in the AST, and historically we have just ignored such friend
1955 // class templates, so don't complain here.
1956 Diag(NameLoc, TUK == TagUseKind::Friend
1957 ? diag::warn_template_qualified_friend_ignored
1958 : diag::err_template_qualified_declarator_no_match)
1959 << SS.getScopeRep() << SS.getRange();
1960 return TUK != TagUseKind::Friend;
1961 }
1962
1963 if (RequireCompleteDeclContext(SS, SemanticContext))
1964 return true;
1965
1966 // If we're adding a template to a dependent context, we may need to
1967 // rebuilding some of the types used within the template parameter list,
1968 // now that we know what the current instantiation is.
1969 if (SemanticContext->isDependentContext()) {
1970 ContextRAII SavedContext(*this, SemanticContext);
1972 Invalid = true;
1973 }
1974
1975 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1976 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1977 /*TemplateId-*/ nullptr,
1978 /*IsMemberSpecialization*/ false);
1979
1980 LookupQualifiedName(Previous, SemanticContext);
1981 } else {
1982 SemanticContext = CurContext;
1983
1984 // C++14 [class.mem]p14:
1985 // If T is the name of a class, then each of the following shall have a
1986 // name different from T:
1987 // -- every member template of class T
1988 if (TUK != TagUseKind::Friend &&
1989 DiagnoseClassNameShadow(SemanticContext,
1990 DeclarationNameInfo(Name, NameLoc)))
1991 return true;
1992
1993 LookupName(Previous, S);
1994 }
1995
1996 if (Previous.isAmbiguous())
1997 return true;
1998
1999 // Let the template parameter scope enter the lookup chain of the current
2000 // class template. For example, given
2001 //
2002 // namespace ns {
2003 // template <class> bool Param = false;
2004 // template <class T> struct N;
2005 // }
2006 //
2007 // template <class Param> struct ns::N { void foo(Param); };
2008 //
2009 // When we reference Param inside the function parameter list, our name lookup
2010 // chain for it should be like:
2011 // FunctionScope foo
2012 // -> RecordScope N
2013 // -> TemplateParamScope (where we will find Param)
2014 // -> NamespaceScope ns
2015 //
2016 // See also CppLookupName().
2017 if (S->isTemplateParamScope())
2018 EnterTemplatedContext(S, SemanticContext);
2019
2020 NamedDecl *PrevDecl = nullptr;
2021 if (Previous.begin() != Previous.end())
2022 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2023
2024 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2025 // Maybe we will complain about the shadowed template parameter.
2026 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2027 // Just pretend that we didn't see the previous declaration.
2028 PrevDecl = nullptr;
2029 }
2030
2031 // If there is a previous declaration with the same name, check
2032 // whether this is a valid redeclaration.
2033 ClassTemplateDecl *PrevClassTemplate =
2034 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2035
2036 // We may have found the injected-class-name of a class template,
2037 // class template partial specialization, or class template specialization.
2038 // In these cases, grab the template that is being defined or specialized.
2039 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2040 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2041 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2042 PrevClassTemplate
2043 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2044 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2045 PrevClassTemplate
2047 ->getSpecializedTemplate();
2048 }
2049 }
2050
2051 if (TUK == TagUseKind::Friend) {
2052 // C++ [namespace.memdef]p3:
2053 // [...] When looking for a prior declaration of a class or a function
2054 // declared as a friend, and when the name of the friend class or
2055 // function is neither a qualified name nor a template-id, scopes outside
2056 // the innermost enclosing namespace scope are not considered.
2057 if (!SS.isSet()) {
2058 DeclContext *OutermostContext = CurContext;
2059 while (!OutermostContext->isFileContext())
2060 OutermostContext = OutermostContext->getLookupParent();
2061
2062 if (PrevDecl &&
2063 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2064 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2065 SemanticContext = PrevDecl->getDeclContext();
2066 } else {
2067 // Declarations in outer scopes don't matter. However, the outermost
2068 // context we computed is the semantic context for our new
2069 // declaration.
2070 PrevDecl = PrevClassTemplate = nullptr;
2071 SemanticContext = OutermostContext;
2072
2073 // Check that the chosen semantic context doesn't already contain a
2074 // declaration of this name as a non-tag type.
2076 DeclContext *LookupContext = SemanticContext;
2077 while (LookupContext->isTransparentContext())
2078 LookupContext = LookupContext->getLookupParent();
2079 LookupQualifiedName(Previous, LookupContext);
2080
2081 if (Previous.isAmbiguous())
2082 return true;
2083
2084 if (Previous.begin() != Previous.end())
2085 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2086 }
2087 }
2088 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2089 SemanticContext, S, SS.isValid()))
2090 PrevDecl = PrevClassTemplate = nullptr;
2091
2092 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2093 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2094 if (SS.isEmpty() &&
2095 !(PrevClassTemplate &&
2096 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2097 SemanticContext->getRedeclContext()))) {
2098 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2099 Diag(Shadow->getTargetDecl()->getLocation(),
2100 diag::note_using_decl_target);
2101 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2102 // Recover by ignoring the old declaration.
2103 PrevDecl = PrevClassTemplate = nullptr;
2104 }
2105 }
2106
2107 if (PrevClassTemplate) {
2108 // Ensure that the template parameter lists are compatible. Skip this check
2109 // for a friend in a dependent context: the template parameter list itself
2110 // could be dependent.
2111 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2113 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2114 : CurContext,
2115 CurContext, KWLoc),
2116 TemplateParams, PrevClassTemplate,
2117 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2119 return true;
2120
2121 // C++ [temp.class]p4:
2122 // In a redeclaration, partial specialization, explicit
2123 // specialization or explicit instantiation of a class template,
2124 // the class-key shall agree in kind with the original class
2125 // template declaration (7.1.5.3).
2126 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2128 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2129 Diag(KWLoc, diag::err_use_with_wrong_tag)
2130 << Name
2131 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2132 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2133 Kind = PrevRecordDecl->getTagKind();
2134 }
2135
2136 // Check for redefinition of this class template.
2137 if (TUK == TagUseKind::Definition) {
2138 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2139 // If we have a prior definition that is not visible, treat this as
2140 // simply making that previous definition visible.
2141 NamedDecl *Hidden = nullptr;
2142 bool HiddenDefVisible = false;
2143 if (SkipBody &&
2144 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2145 SkipBody->ShouldSkip = true;
2146 SkipBody->Previous = Def;
2147 if (!HiddenDefVisible && Hidden) {
2148 auto *Tmpl =
2149 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2150 assert(Tmpl && "original definition of a class template is not a "
2151 "class template?");
2154 }
2155 } else {
2156 Diag(NameLoc, diag::err_redefinition) << Name;
2157 Diag(Def->getLocation(), diag::note_previous_definition);
2158 // FIXME: Would it make sense to try to "forget" the previous
2159 // definition, as part of error recovery?
2160 return true;
2161 }
2162 }
2163 }
2164 } else if (PrevDecl) {
2165 // C++ [temp]p5:
2166 // A class template shall not have the same name as any other
2167 // template, class, function, object, enumeration, enumerator,
2168 // namespace, or type in the same scope (3.3), except as specified
2169 // in (14.5.4).
2170 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2171 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2172 return true;
2173 }
2174
2175 // Check the template parameter list of this declaration, possibly
2176 // merging in the template parameter list from the previous class
2177 // template declaration. Skip this check for a friend in a dependent
2178 // context, because the template parameter list might be dependent.
2179 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2181 TemplateParams,
2182 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2183 : nullptr,
2184 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2185 SemanticContext->isDependentContext())
2188 : TPC_Other,
2189 SkipBody))
2190 Invalid = true;
2191
2192 if (SS.isSet()) {
2193 // If the name of the template was qualified, we must be defining the
2194 // template out-of-line.
2195 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2196 Diag(NameLoc, TUK == TagUseKind::Friend
2197 ? diag::err_friend_decl_does_not_match
2198 : diag::err_member_decl_does_not_match)
2199 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2200 Invalid = true;
2201 }
2202 }
2203
2204 // If this is a templated friend in a dependent context we should not put it
2205 // on the redecl chain. In some cases, the templated friend can be the most
2206 // recent declaration tricking the template instantiator to make substitutions
2207 // there.
2208 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2209 bool ShouldAddRedecl =
2210 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2211
2213 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2214 PrevClassTemplate && ShouldAddRedecl
2215 ? PrevClassTemplate->getTemplatedDecl()
2216 : nullptr);
2217 SetNestedNameSpecifier(*this, NewClass, SS);
2218 if (NumOuterTemplateParamLists > 0)
2220 Context,
2221 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2222
2223 // Add alignment attributes if necessary; these attributes are checked when
2224 // the ASTContext lays out the structure.
2225 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2226 if (LangOpts.HLSL)
2227 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2230 }
2231
2232 ClassTemplateDecl *NewTemplate
2233 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2234 DeclarationName(Name), TemplateParams,
2235 NewClass);
2236
2237 if (ShouldAddRedecl)
2238 NewTemplate->setPreviousDecl(PrevClassTemplate);
2239
2240 NewClass->setDescribedClassTemplate(NewTemplate);
2241
2242 if (ModulePrivateLoc.isValid())
2243 NewTemplate->setModulePrivate();
2244
2245 // If we are providing an explicit specialization of a member that is a
2246 // class template, make a note of that.
2247 if (PrevClassTemplate &&
2248 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2249 PrevClassTemplate->setMemberSpecialization();
2250
2251 // Set the access specifier.
2252 if (!Invalid && TUK != TagUseKind::Friend &&
2253 NewTemplate->getDeclContext()->isRecord())
2254 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2255
2256 // Set the lexical context of these templates
2258 NewTemplate->setLexicalDeclContext(CurContext);
2259
2260 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2261 NewClass->startDefinition();
2262
2263 ProcessDeclAttributeList(S, NewClass, Attr);
2264
2265 if (PrevClassTemplate)
2266 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2267
2271
2272 if (TUK != TagUseKind::Friend) {
2273 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2274 Scope *Outer = S;
2275 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2276 Outer = Outer->getParent();
2277 PushOnScopeChains(NewTemplate, Outer);
2278 } else {
2279 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2280 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2281 NewClass->setAccess(PrevClassTemplate->getAccess());
2282 }
2283
2284 NewTemplate->setObjectOfFriendDecl();
2285
2286 // Friend templates are visible in fairly strange ways.
2287 if (!CurContext->isDependentContext()) {
2288 DeclContext *DC = SemanticContext->getRedeclContext();
2289 DC->makeDeclVisibleInContext(NewTemplate);
2290 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2291 PushOnScopeChains(NewTemplate, EnclosingScope,
2292 /* AddToContext = */ false);
2293 }
2294
2296 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2297 Friend->setAccess(AS_public);
2298 CurContext->addDecl(Friend);
2299 }
2300
2301 if (PrevClassTemplate)
2302 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2303
2304 if (Invalid) {
2305 NewTemplate->setInvalidDecl();
2306 NewClass->setInvalidDecl();
2307 }
2308
2309 ActOnDocumentableDecl(NewTemplate);
2310
2311 if (SkipBody && SkipBody->ShouldSkip)
2312 return SkipBody->Previous;
2313
2314 return NewTemplate;
2315}
2316
2317/// Diagnose the presence of a default template argument on a
2318/// template parameter, which is ill-formed in certain contexts.
2319///
2320/// \returns true if the default template argument should be dropped.
2323 SourceLocation ParamLoc,
2324 SourceRange DefArgRange) {
2325 switch (TPC) {
2326 case Sema::TPC_Other:
2328 return false;
2329
2332 // C++ [temp.param]p9:
2333 // A default template-argument shall not be specified in a
2334 // function template declaration or a function template
2335 // definition [...]
2336 // If a friend function template declaration specifies a default
2337 // template-argument, that declaration shall be a definition and shall be
2338 // the only declaration of the function template in the translation unit.
2339 // (C++98/03 doesn't have this wording; see DR226).
2340 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2341 << DefArgRange;
2342 return false;
2343
2345 // C++0x [temp.param]p9:
2346 // A default template-argument shall not be specified in the
2347 // template-parameter-lists of the definition of a member of a
2348 // class template that appears outside of the member's class.
2349 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2350 << DefArgRange;
2351 return true;
2352
2355 // C++ [temp.param]p9:
2356 // A default template-argument shall not be specified in a
2357 // friend template declaration.
2358 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2359 << DefArgRange;
2360 return true;
2361
2362 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2363 // for friend function templates if there is only a single
2364 // declaration (and it is a definition). Strange!
2365 }
2366
2367 llvm_unreachable("Invalid TemplateParamListContext!");
2368}
2369
2370/// Check for unexpanded parameter packs within the template parameters
2371/// of a template template parameter, recursively.
2374 // A template template parameter which is a parameter pack is also a pack
2375 // expansion.
2376 if (TTP->isParameterPack())
2377 return false;
2378
2380 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2381 NamedDecl *P = Params->getParam(I);
2382 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2383 if (!TTP->isParameterPack())
2384 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2385 if (TC->hasExplicitTemplateArgs())
2386 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2389 return true;
2390 continue;
2391 }
2392
2393 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2394 if (!NTTP->isParameterPack() &&
2395 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2396 NTTP->getTypeSourceInfo(),
2398 return true;
2399
2400 continue;
2401 }
2402
2403 if (TemplateTemplateParmDecl *InnerTTP
2404 = dyn_cast<TemplateTemplateParmDecl>(P))
2405 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2406 return true;
2407 }
2408
2409 return false;
2410}
2411
2413 TemplateParameterList *OldParams,
2415 SkipBodyInfo *SkipBody) {
2416 bool Invalid = false;
2417
2418 // C++ [temp.param]p10:
2419 // The set of default template-arguments available for use with a
2420 // template declaration or definition is obtained by merging the
2421 // default arguments from the definition (if in scope) and all
2422 // declarations in scope in the same way default function
2423 // arguments are (8.3.6).
2424 bool SawDefaultArgument = false;
2425 SourceLocation PreviousDefaultArgLoc;
2426
2427 // Dummy initialization to avoid warnings.
2428 TemplateParameterList::iterator OldParam = NewParams->end();
2429 if (OldParams)
2430 OldParam = OldParams->begin();
2431
2432 bool RemoveDefaultArguments = false;
2433 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2434 NewParamEnd = NewParams->end();
2435 NewParam != NewParamEnd; ++NewParam) {
2436 // Whether we've seen a duplicate default argument in the same translation
2437 // unit.
2438 bool RedundantDefaultArg = false;
2439 // Whether we've found inconsis inconsitent default arguments in different
2440 // translation unit.
2441 bool InconsistentDefaultArg = false;
2442 // The name of the module which contains the inconsistent default argument.
2443 std::string PrevModuleName;
2444
2445 SourceLocation OldDefaultLoc;
2446 SourceLocation NewDefaultLoc;
2447
2448 // Variable used to diagnose missing default arguments
2449 bool MissingDefaultArg = false;
2450
2451 // Variable used to diagnose non-final parameter packs
2452 bool SawParameterPack = false;
2453
2454 if (TemplateTypeParmDecl *NewTypeParm
2455 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2456 // Check the presence of a default argument here.
2457 if (NewTypeParm->hasDefaultArgument() &&
2459 *this, TPC, NewTypeParm->getLocation(),
2460 NewTypeParm->getDefaultArgument().getSourceRange()))
2461 NewTypeParm->removeDefaultArgument();
2462
2463 // Merge default arguments for template type parameters.
2464 TemplateTypeParmDecl *OldTypeParm
2465 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2466 if (NewTypeParm->isParameterPack()) {
2467 assert(!NewTypeParm->hasDefaultArgument() &&
2468 "Parameter packs can't have a default argument!");
2469 SawParameterPack = true;
2470 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2471 NewTypeParm->hasDefaultArgument() &&
2472 (!SkipBody || !SkipBody->ShouldSkip)) {
2473 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2474 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2475 SawDefaultArgument = true;
2476
2477 if (!OldTypeParm->getOwningModule())
2478 RedundantDefaultArg = true;
2479 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2480 NewTypeParm)) {
2481 InconsistentDefaultArg = true;
2482 PrevModuleName =
2484 }
2485 PreviousDefaultArgLoc = NewDefaultLoc;
2486 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2487 // Merge the default argument from the old declaration to the
2488 // new declaration.
2489 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2490 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2491 } else if (NewTypeParm->hasDefaultArgument()) {
2492 SawDefaultArgument = true;
2493 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2494 } else if (SawDefaultArgument)
2495 MissingDefaultArg = true;
2496 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2497 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2498 // Check for unexpanded parameter packs, except in a template template
2499 // parameter pack, as in those any unexpanded packs should be expanded
2500 // along with the parameter itself.
2502 !NewNonTypeParm->isParameterPack() &&
2503 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2504 NewNonTypeParm->getTypeSourceInfo(),
2506 Invalid = true;
2507 continue;
2508 }
2509
2510 // Check the presence of a default argument here.
2511 if (NewNonTypeParm->hasDefaultArgument() &&
2513 *this, TPC, NewNonTypeParm->getLocation(),
2514 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2515 NewNonTypeParm->removeDefaultArgument();
2516 }
2517
2518 // Merge default arguments for non-type template parameters
2519 NonTypeTemplateParmDecl *OldNonTypeParm
2520 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2521 if (NewNonTypeParm->isParameterPack()) {
2522 assert(!NewNonTypeParm->hasDefaultArgument() &&
2523 "Parameter packs can't have a default argument!");
2524 if (!NewNonTypeParm->isPackExpansion())
2525 SawParameterPack = true;
2526 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2527 NewNonTypeParm->hasDefaultArgument() &&
2528 (!SkipBody || !SkipBody->ShouldSkip)) {
2529 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2530 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2531 SawDefaultArgument = true;
2532 if (!OldNonTypeParm->getOwningModule())
2533 RedundantDefaultArg = true;
2534 else if (!getASTContext().isSameDefaultTemplateArgument(
2535 OldNonTypeParm, NewNonTypeParm)) {
2536 InconsistentDefaultArg = true;
2537 PrevModuleName =
2538 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2539 }
2540 PreviousDefaultArgLoc = NewDefaultLoc;
2541 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2542 // Merge the default argument from the old declaration to the
2543 // new declaration.
2544 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2545 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2546 } else if (NewNonTypeParm->hasDefaultArgument()) {
2547 SawDefaultArgument = true;
2548 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2549 } else if (SawDefaultArgument)
2550 MissingDefaultArg = true;
2551 } else {
2552 TemplateTemplateParmDecl *NewTemplateParm
2553 = cast<TemplateTemplateParmDecl>(*NewParam);
2554
2555 // Check for unexpanded parameter packs, recursively.
2556 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2557 Invalid = true;
2558 continue;
2559 }
2560
2561 // Check the presence of a default argument here.
2562 if (NewTemplateParm->hasDefaultArgument() &&
2564 NewTemplateParm->getLocation(),
2565 NewTemplateParm->getDefaultArgument().getSourceRange()))
2566 NewTemplateParm->removeDefaultArgument();
2567
2568 // Merge default arguments for template template parameters
2569 TemplateTemplateParmDecl *OldTemplateParm
2570 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2571 if (NewTemplateParm->isParameterPack()) {
2572 assert(!NewTemplateParm->hasDefaultArgument() &&
2573 "Parameter packs can't have a default argument!");
2574 if (!NewTemplateParm->isPackExpansion())
2575 SawParameterPack = true;
2576 } else if (OldTemplateParm &&
2577 hasVisibleDefaultArgument(OldTemplateParm) &&
2578 NewTemplateParm->hasDefaultArgument() &&
2579 (!SkipBody || !SkipBody->ShouldSkip)) {
2580 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2581 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2582 SawDefaultArgument = true;
2583 if (!OldTemplateParm->getOwningModule())
2584 RedundantDefaultArg = true;
2585 else if (!getASTContext().isSameDefaultTemplateArgument(
2586 OldTemplateParm, NewTemplateParm)) {
2587 InconsistentDefaultArg = true;
2588 PrevModuleName =
2589 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2590 }
2591 PreviousDefaultArgLoc = NewDefaultLoc;
2592 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2593 // Merge the default argument from the old declaration to the
2594 // new declaration.
2595 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2596 PreviousDefaultArgLoc
2597 = OldTemplateParm->getDefaultArgument().getLocation();
2598 } else if (NewTemplateParm->hasDefaultArgument()) {
2599 SawDefaultArgument = true;
2600 PreviousDefaultArgLoc
2601 = NewTemplateParm->getDefaultArgument().getLocation();
2602 } else if (SawDefaultArgument)
2603 MissingDefaultArg = true;
2604 }
2605
2606 // C++11 [temp.param]p11:
2607 // If a template parameter of a primary class template or alias template
2608 // is a template parameter pack, it shall be the last template parameter.
2609 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2610 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2611 Diag((*NewParam)->getLocation(),
2612 diag::err_template_param_pack_must_be_last_template_parameter);
2613 Invalid = true;
2614 }
2615
2616 // [basic.def.odr]/13:
2617 // There can be more than one definition of a
2618 // ...
2619 // default template argument
2620 // ...
2621 // in a program provided that each definition appears in a different
2622 // translation unit and the definitions satisfy the [same-meaning
2623 // criteria of the ODR].
2624 //
2625 // Simply, the design of modules allows the definition of template default
2626 // argument to be repeated across translation unit. Note that the ODR is
2627 // checked elsewhere. But it is still not allowed to repeat template default
2628 // argument in the same translation unit.
2629 if (RedundantDefaultArg) {
2630 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2631 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2632 Invalid = true;
2633 } else if (InconsistentDefaultArg) {
2634 // We could only diagnose about the case that the OldParam is imported.
2635 // The case NewParam is imported should be handled in ASTReader.
2636 Diag(NewDefaultLoc,
2637 diag::err_template_param_default_arg_inconsistent_redefinition);
2638 Diag(OldDefaultLoc,
2639 diag::note_template_param_prev_default_arg_in_other_module)
2640 << PrevModuleName;
2641 Invalid = true;
2642 } else if (MissingDefaultArg &&
2643 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2644 TPC == TPC_FriendClassTemplate)) {
2645 // C++ 23[temp.param]p14:
2646 // If a template-parameter of a class template, variable template, or
2647 // alias template has a default template argument, each subsequent
2648 // template-parameter shall either have a default template argument
2649 // supplied or be a template parameter pack.
2650 Diag((*NewParam)->getLocation(),
2651 diag::err_template_param_default_arg_missing);
2652 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2653 Invalid = true;
2654 RemoveDefaultArguments = true;
2655 }
2656
2657 // If we have an old template parameter list that we're merging
2658 // in, move on to the next parameter.
2659 if (OldParams)
2660 ++OldParam;
2661 }
2662
2663 // We were missing some default arguments at the end of the list, so remove
2664 // all of the default arguments.
2665 if (RemoveDefaultArguments) {
2666 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2667 NewParamEnd = NewParams->end();
2668 NewParam != NewParamEnd; ++NewParam) {
2669 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2670 TTP->removeDefaultArgument();
2671 else if (NonTypeTemplateParmDecl *NTTP
2672 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2673 NTTP->removeDefaultArgument();
2674 else
2675 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2676 }
2677 }
2678
2679 return Invalid;
2680}
2681
2682namespace {
2683
2684/// A class which looks for a use of a certain level of template
2685/// parameter.
2686struct DependencyChecker : DynamicRecursiveASTVisitor {
2687 unsigned Depth;
2688
2689 // Whether we're looking for a use of a template parameter that makes the
2690 // overall construct type-dependent / a dependent type. This is strictly
2691 // best-effort for now; we may fail to match at all for a dependent type
2692 // in some cases if this is set.
2693 bool IgnoreNonTypeDependent;
2694
2695 bool Match;
2696 SourceLocation MatchLoc;
2697
2698 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2699 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2700 Match(false) {}
2701
2702 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2703 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2704 NamedDecl *ND = Params->getParam(0);
2705 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2706 Depth = PD->getDepth();
2707 } else if (NonTypeTemplateParmDecl *PD =
2708 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2709 Depth = PD->getDepth();
2710 } else {
2711 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2712 }
2713 }
2714
2715 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2716 if (ParmDepth >= Depth) {
2717 Match = true;
2718 MatchLoc = Loc;
2719 return true;
2720 }
2721 return false;
2722 }
2723
2724 bool TraverseStmt(Stmt *S) override {
2725 // Prune out non-type-dependent expressions if requested. This can
2726 // sometimes result in us failing to find a template parameter reference
2727 // (if a value-dependent expression creates a dependent type), but this
2728 // mode is best-effort only.
2729 if (auto *E = dyn_cast_or_null<Expr>(S))
2730 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2731 return true;
2733 }
2734
2735 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2736 if (IgnoreNonTypeDependent && !TL.isNull() &&
2737 !TL.getType()->isDependentType())
2738 return true;
2739 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2740 }
2741
2742 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2743 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2744 }
2745
2746 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2747 // For a best-effort search, keep looking until we find a location.
2748 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2749 }
2750
2751 bool TraverseTemplateName(TemplateName N) override {
2752 if (TemplateTemplateParmDecl *PD =
2753 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2754 if (Matches(PD->getDepth()))
2755 return false;
2757 }
2758
2759 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2760 if (NonTypeTemplateParmDecl *PD =
2761 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2762 if (Matches(PD->getDepth(), E->getExprLoc()))
2763 return false;
2764 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2765 }
2766
2767 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2768 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2769 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2770 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2771 return false;
2772 }
2773 for (auto &TLoc : ULE->template_arguments())
2775 }
2776 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2777 }
2778
2779 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2780 return TraverseType(T->getReplacementType());
2781 }
2782
2783 bool VisitSubstTemplateTypeParmPackType(
2784 SubstTemplateTypeParmPackType *T) override {
2785 return TraverseTemplateArgument(T->getArgumentPack());
2786 }
2787
2788 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2789 bool TraverseQualifier) override {
2790 // An InjectedClassNameType will never have a dependent template name,
2791 // so no need to traverse it.
2792 return TraverseTemplateArguments(
2793 T->getTemplateArgs(T->getOriginalDecl()->getASTContext()));
2794 }
2795};
2796} // end anonymous namespace
2797
2798/// Determines whether a given type depends on the given parameter
2799/// list.
2800static bool
2802 if (!Params->size())
2803 return false;
2804
2805 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2806 Checker.TraverseType(T);
2807 return Checker.Match;
2808}
2809
2810// Find the source range corresponding to the named type in the given
2811// nested-name-specifier, if any.
2813 QualType T,
2814 const CXXScopeSpec &SS) {
2816 for (;;) {
2819 break;
2820 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2821 return NNSLoc.castAsTypeLoc().getSourceRange();
2822 // FIXME: This will always be empty.
2823 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2824 }
2825
2826 return SourceRange();
2827}
2828
2830 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2831 TemplateIdAnnotation *TemplateId,
2832 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2833 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2834 IsMemberSpecialization = false;
2835 Invalid = false;
2836
2837 // The sequence of nested types to which we will match up the template
2838 // parameter lists. We first build this list by starting with the type named
2839 // by the nested-name-specifier and walking out until we run out of types.
2840 SmallVector<QualType, 4> NestedTypes;
2841 QualType T;
2842 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2843 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2844 if (CXXRecordDecl *Record =
2845 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2846 T = Context.getCanonicalTagType(Record);
2847 else
2848 T = QualType(Qualifier.getAsType(), 0);
2849 }
2850
2851 // If we found an explicit specialization that prevents us from needing
2852 // 'template<>' headers, this will be set to the location of that
2853 // explicit specialization.
2854 SourceLocation ExplicitSpecLoc;
2855
2856 while (!T.isNull()) {
2857 NestedTypes.push_back(T);
2858
2859 // Retrieve the parent of a record type.
2860 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2861 // If this type is an explicit specialization, we're done.
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2865 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2866 ExplicitSpecLoc = Spec->getLocation();
2867 break;
2868 }
2869 } else if (Record->getTemplateSpecializationKind()
2871 ExplicitSpecLoc = Record->getLocation();
2872 break;
2873 }
2874
2875 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2876 T = Context.getTypeDeclType(Parent);
2877 else
2878 T = QualType();
2879 continue;
2880 }
2881
2882 if (const TemplateSpecializationType *TST
2883 = T->getAs<TemplateSpecializationType>()) {
2884 TemplateName Name = TST->getTemplateName();
2885 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2886 // Look one step prior in a dependent template specialization type.
2887 if (NestedNameSpecifier NNS = DTS->getQualifier();
2889 T = QualType(NNS.getAsType(), 0);
2890 else
2891 T = QualType();
2892 continue;
2893 }
2894 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2895 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2896 T = Context.getTypeDeclType(Parent);
2897 else
2898 T = QualType();
2899 continue;
2900 }
2901 }
2902
2903 // Look one step prior in a dependent name type.
2904 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2905 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2907 T = QualType(NNS.getAsType(), 0);
2908 else
2909 T = QualType();
2910 continue;
2911 }
2912
2913 // Retrieve the parent of an enumeration type.
2914 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2915 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2916 // check here.
2917 EnumDecl *Enum = EnumT->getOriginalDecl();
2918
2919 // Get to the parent type.
2920 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2921 T = Context.getCanonicalTypeDeclType(Parent);
2922 else
2923 T = QualType();
2924 continue;
2925 }
2926
2927 T = QualType();
2928 }
2929 // Reverse the nested types list, since we want to traverse from the outermost
2930 // to the innermost while checking template-parameter-lists.
2931 std::reverse(NestedTypes.begin(), NestedTypes.end());
2932
2933 // C++0x [temp.expl.spec]p17:
2934 // A member or a member template may be nested within many
2935 // enclosing class templates. In an explicit specialization for
2936 // such a member, the member declaration shall be preceded by a
2937 // template<> for each enclosing class template that is
2938 // explicitly specialized.
2939 bool SawNonEmptyTemplateParameterList = false;
2940
2941 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2942 if (SawNonEmptyTemplateParameterList) {
2943 if (!SuppressDiagnostic)
2944 Diag(DeclLoc, diag::err_specialize_member_of_template)
2945 << !Recovery << Range;
2946 Invalid = true;
2947 IsMemberSpecialization = false;
2948 return true;
2949 }
2950
2951 return false;
2952 };
2953
2954 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2955 // Check that we can have an explicit specialization here.
2956 if (CheckExplicitSpecialization(Range, true))
2957 return true;
2958
2959 // We don't have a template header, but we should.
2960 SourceLocation ExpectedTemplateLoc;
2961 if (!ParamLists.empty())
2962 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2963 else
2964 ExpectedTemplateLoc = DeclStartLoc;
2965
2966 if (!SuppressDiagnostic)
2967 Diag(DeclLoc, diag::err_template_spec_needs_header)
2968 << Range
2969 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2970 return false;
2971 };
2972
2973 unsigned ParamIdx = 0;
2974 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2975 ++TypeIdx) {
2976 T = NestedTypes[TypeIdx];
2977
2978 // Whether we expect a 'template<>' header.
2979 bool NeedEmptyTemplateHeader = false;
2980
2981 // Whether we expect a template header with parameters.
2982 bool NeedNonemptyTemplateHeader = false;
2983
2984 // For a dependent type, the set of template parameters that we
2985 // expect to see.
2986 TemplateParameterList *ExpectedTemplateParams = nullptr;
2987
2988 // C++0x [temp.expl.spec]p15:
2989 // A member or a member template may be nested within many enclosing
2990 // class templates. In an explicit specialization for such a member, the
2991 // member declaration shall be preceded by a template<> for each
2992 // enclosing class template that is explicitly specialized.
2993 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2996 ExpectedTemplateParams = Partial->getTemplateParameters();
2997 NeedNonemptyTemplateHeader = true;
2998 } else if (Record->isDependentType()) {
2999 if (Record->getDescribedClassTemplate()) {
3000 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3001 ->getTemplateParameters();
3002 NeedNonemptyTemplateHeader = true;
3003 }
3004 } else if (ClassTemplateSpecializationDecl *Spec
3005 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3006 // C++0x [temp.expl.spec]p4:
3007 // Members of an explicitly specialized class template are defined
3008 // in the same manner as members of normal classes, and not using
3009 // the template<> syntax.
3010 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3011 NeedEmptyTemplateHeader = true;
3012 else
3013 continue;
3014 } else if (Record->getTemplateSpecializationKind()) {
3015 if (Record->getTemplateSpecializationKind()
3017 TypeIdx == NumTypes - 1)
3018 IsMemberSpecialization = true;
3019
3020 continue;
3021 }
3022 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3023 TemplateName Name = TST->getTemplateName();
3024 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3025 ExpectedTemplateParams = Template->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 } else if (Name.getAsDeducedTemplateName()) {
3028 // FIXME: We actually could/should check the template arguments here
3029 // against the corresponding template parameter list.
3030 NeedNonemptyTemplateHeader = false;
3031 }
3032 }
3033
3034 // C++ [temp.expl.spec]p16:
3035 // In an explicit specialization declaration for a member of a class
3036 // template or a member template that appears in namespace scope, the
3037 // member template and some of its enclosing class templates may remain
3038 // unspecialized, except that the declaration shall not explicitly
3039 // specialize a class member template if its enclosing class templates
3040 // are not explicitly specialized as well.
3041 if (ParamIdx < ParamLists.size()) {
3042 if (ParamLists[ParamIdx]->size() == 0) {
3043 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3044 false))
3045 return nullptr;
3046 } else
3047 SawNonEmptyTemplateParameterList = true;
3048 }
3049
3050 if (NeedEmptyTemplateHeader) {
3051 // If we're on the last of the types, and we need a 'template<>' header
3052 // here, then it's a member specialization.
3053 if (TypeIdx == NumTypes - 1)
3054 IsMemberSpecialization = true;
3055
3056 if (ParamIdx < ParamLists.size()) {
3057 if (ParamLists[ParamIdx]->size() > 0) {
3058 // The header has template parameters when it shouldn't. Complain.
3059 if (!SuppressDiagnostic)
3060 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3061 diag::err_template_param_list_matches_nontemplate)
3062 << T
3063 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3064 ParamLists[ParamIdx]->getRAngleLoc())
3066 Invalid = true;
3067 return nullptr;
3068 }
3069
3070 // Consume this template header.
3071 ++ParamIdx;
3072 continue;
3073 }
3074
3075 if (!IsFriend)
3076 if (DiagnoseMissingExplicitSpecialization(
3078 return nullptr;
3079
3080 continue;
3081 }
3082
3083 if (NeedNonemptyTemplateHeader) {
3084 // In friend declarations we can have template-ids which don't
3085 // depend on the corresponding template parameter lists. But
3086 // assume that empty parameter lists are supposed to match this
3087 // template-id.
3088 if (IsFriend && T->isDependentType()) {
3089 if (ParamIdx < ParamLists.size() &&
3091 ExpectedTemplateParams = nullptr;
3092 else
3093 continue;
3094 }
3095
3096 if (ParamIdx < ParamLists.size()) {
3097 // Check the template parameter list, if we can.
3098 if (ExpectedTemplateParams &&
3100 ExpectedTemplateParams,
3101 !SuppressDiagnostic, TPL_TemplateMatch))
3102 Invalid = true;
3103
3104 if (!Invalid &&
3105 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3107 Invalid = true;
3108
3109 ++ParamIdx;
3110 continue;
3111 }
3112
3113 if (!SuppressDiagnostic)
3114 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3115 << T
3117 Invalid = true;
3118 continue;
3119 }
3120 }
3121
3122 // If there were at least as many template-ids as there were template
3123 // parameter lists, then there are no template parameter lists remaining for
3124 // the declaration itself.
3125 if (ParamIdx >= ParamLists.size()) {
3126 if (TemplateId && !IsFriend) {
3127 // We don't have a template header for the declaration itself, but we
3128 // should.
3129 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3130 TemplateId->RAngleLoc));
3131
3132 // Fabricate an empty template parameter list for the invented header.
3134 SourceLocation(), {},
3135 SourceLocation(), nullptr);
3136 }
3137
3138 return nullptr;
3139 }
3140
3141 // If there were too many template parameter lists, complain about that now.
3142 if (ParamIdx < ParamLists.size() - 1) {
3143 bool HasAnyExplicitSpecHeader = false;
3144 bool AllExplicitSpecHeaders = true;
3145 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3146 if (ParamLists[I]->size() == 0)
3147 HasAnyExplicitSpecHeader = true;
3148 else
3149 AllExplicitSpecHeaders = false;
3150 }
3151
3152 if (!SuppressDiagnostic)
3153 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3154 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3155 : diag::err_template_spec_extra_headers)
3156 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3157 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3158
3159 // If there was a specialization somewhere, such that 'template<>' is
3160 // not required, and there were any 'template<>' headers, note where the
3161 // specialization occurred.
3162 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3163 !SuppressDiagnostic)
3164 Diag(ExplicitSpecLoc,
3165 diag::note_explicit_template_spec_does_not_need_header)
3166 << NestedTypes.back();
3167
3168 // We have a template parameter list with no corresponding scope, which
3169 // means that the resulting template declaration can't be instantiated
3170 // properly (we'll end up with dependent nodes when we shouldn't).
3171 if (!AllExplicitSpecHeaders)
3172 Invalid = true;
3173 }
3174
3175 // C++ [temp.expl.spec]p16:
3176 // In an explicit specialization declaration for a member of a class
3177 // template or a member template that ap- pears in namespace scope, the
3178 // member template and some of its enclosing class templates may remain
3179 // unspecialized, except that the declaration shall not explicitly
3180 // specialize a class member template if its en- closing class templates
3181 // are not explicitly specialized as well.
3182 if (ParamLists.back()->size() == 0 &&
3183 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3184 false))
3185 return nullptr;
3186
3187 // Return the last template parameter list, which corresponds to the
3188 // entity being declared.
3189 return ParamLists.back();
3190}
3191
3193 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3194 Diag(Template->getLocation(), diag::note_template_declared_here)
3196 ? 0
3198 ? 1
3200 ? 2
3202 << Template->getDeclName();
3203 return;
3204 }
3205
3207 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3208 IEnd = OST->end();
3209 I != IEnd; ++I)
3210 Diag((*I)->getLocation(), diag::note_template_declared_here)
3211 << 0 << (*I)->getDeclName();
3212
3213 return;
3214 }
3215}
3216
3218 TemplateName BaseTemplate,
3219 SourceLocation TemplateLoc,
3221 auto lookUpCommonType = [&](TemplateArgument T1,
3222 TemplateArgument T2) -> QualType {
3223 // Don't bother looking for other specializations if both types are
3224 // builtins - users aren't allowed to specialize for them
3225 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3226 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3227 {T1, T2});
3228
3232 Args.addArgument(TemplateArgumentLoc(
3233 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3234
3235 EnterExpressionEvaluationContext UnevaluatedContext(
3237 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3239
3240 QualType BaseTemplateInst = S.CheckTemplateIdType(
3241 Keyword, BaseTemplate, TemplateLoc, Args,
3242 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3243
3244 if (SFINAE.hasErrorOccurred())
3245 return QualType();
3246
3247 return BaseTemplateInst;
3248 };
3249
3250 // Note A: For the common_type trait applied to a template parameter pack T of
3251 // types, the member type shall be either defined or not present as follows:
3252 switch (Ts.size()) {
3253
3254 // If sizeof...(T) is zero, there shall be no member type.
3255 case 0:
3256 return QualType();
3257
3258 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3259 // pack T. The member typedef-name type shall denote the same type, if any, as
3260 // common_type_t<T0, T0>; otherwise there shall be no member type.
3261 case 1:
3262 return lookUpCommonType(Ts[0], Ts[0]);
3263
3264 // If sizeof...(T) is two, let the first and second types constituting T be
3265 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3266 // as decay_t<T1> and decay_t<T2>, respectively.
3267 case 2: {
3268 QualType T1 = Ts[0].getAsType();
3269 QualType T2 = Ts[1].getAsType();
3270 QualType D1 = S.BuiltinDecay(T1, {});
3271 QualType D2 = S.BuiltinDecay(T2, {});
3272
3273 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3274 // the same type, if any, as common_type_t<D1, D2>.
3275 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3276 return lookUpCommonType(D1, D2);
3277
3278 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3279 // denotes a valid type, let C denote that type.
3280 {
3281 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3282 EnterExpressionEvaluationContext UnevaluatedContext(
3284 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3286
3287 // false
3289 VK_PRValue);
3290 ExprResult Cond = &CondExpr;
3291
3292 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3293 if (ConstRefQual) {
3294 D1.addConst();
3295 D2.addConst();
3296 }
3297
3298 // declval<D1>()
3299 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3300 ExprResult LHS = &LHSExpr;
3301
3302 // declval<D2>()
3303 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3304 ExprResult RHS = &RHSExpr;
3305
3308
3309 // decltype(false ? declval<D1>() : declval<D2>())
3310 QualType Result =
3311 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3312
3313 if (Result.isNull() || SFINAE.hasErrorOccurred())
3314 return QualType();
3315
3316 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3317 return S.BuiltinDecay(Result, TemplateLoc);
3318 };
3319
3320 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3321 return Res;
3322
3323 // Let:
3324 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3325 // COND-RES(X, Y) be
3326 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3327
3328 // C++20 only
3329 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3330 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3331 if (!S.Context.getLangOpts().CPlusPlus20)
3332 return QualType();
3333 return CheckConditionalOperands(true);
3334 }
3335 }
3336
3337 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3338 // denote the first, second, and (pack of) remaining types constituting T. Let
3339 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3340 // a type C, the member typedef-name type shall denote the same type, if any,
3341 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3342 default: {
3343 QualType Result = Ts.front().getAsType();
3344 for (auto T : llvm::drop_begin(Ts)) {
3345 Result = lookUpCommonType(Result, T.getAsType());
3346 if (Result.isNull())
3347 return QualType();
3348 }
3349 return Result;
3350 }
3351 }
3352}
3353
3354static bool isInVkNamespace(const RecordType *RT) {
3355 DeclContext *DC = RT->getOriginalDecl()->getDeclContext();
3356 if (!DC)
3357 return false;
3358
3359 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3360 if (!ND)
3361 return false;
3362
3363 return ND->getQualifiedNameAsString() == "hlsl::vk";
3364}
3365
3366static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3367 QualType OperandArg,
3368 SourceLocation Loc) {
3369 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3370 bool Literal = false;
3371 SourceLocation LiteralLoc;
3372 if (isInVkNamespace(RT) && RT->getOriginalDecl()->getName() == "Literal") {
3373 auto SpecDecl =
3374 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3375 assert(SpecDecl);
3376
3377 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3378 QualType ConstantType = LiteralArgs[0].getAsType();
3379 RT = ConstantType->getAsCanonical<RecordType>();
3380 Literal = true;
3381 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3382 }
3383
3384 if (RT && isInVkNamespace(RT) &&
3385 RT->getOriginalDecl()->getName() == "integral_constant") {
3386 auto SpecDecl =
3387 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3388 assert(SpecDecl);
3389
3390 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3391
3392 QualType ConstantType = ConstantArgs[0].getAsType();
3393 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3394
3395 if (Literal)
3396 return SpirvOperand::createLiteral(Value);
3397 return SpirvOperand::createConstant(ConstantType, Value);
3398 } else if (Literal) {
3399 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3400 return SpirvOperand();
3401 }
3402 }
3403 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3404 diag::err_call_incomplete_argument))
3405 return SpirvOperand();
3406 return SpirvOperand::createType(OperandArg);
3407}
3408
3411 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3412 TemplateArgumentListInfo &TemplateArgs) {
3413 ASTContext &Context = SemaRef.getASTContext();
3414
3415 switch (BTD->getBuiltinTemplateKind()) {
3416 case BTK__make_integer_seq: {
3417 // Specializations of __make_integer_seq<S, T, N> are treated like
3418 // S<T, 0, ..., N-1>.
3419
3420 QualType OrigType = Converted[1].getAsType();
3421 // C++14 [inteseq.intseq]p1:
3422 // T shall be an integer type.
3423 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3424 SemaRef.Diag(TemplateArgs[1].getLocation(),
3425 diag::err_integer_sequence_integral_element_type);
3426 return QualType();
3427 }
3428
3429 TemplateArgument NumArgsArg = Converted[2];
3430 if (NumArgsArg.isDependent())
3431 return QualType();
3432
3433 TemplateArgumentListInfo SyntheticTemplateArgs;
3434 // The type argument, wrapped in substitution sugar, gets reused as the
3435 // first template argument in the synthetic template argument list.
3436 SyntheticTemplateArgs.addArgument(
3439 OrigType, TemplateArgs[1].getLocation())));
3440
3441 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3442 // Expand N into 0 ... N-1.
3443 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3444 I < NumArgs; ++I) {
3445 TemplateArgument TA(Context, I, OrigType);
3446 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3447 TA, OrigType, TemplateArgs[2].getLocation()));
3448 }
3449 } else {
3450 // C++14 [inteseq.make]p1:
3451 // If N is negative the program is ill-formed.
3452 SemaRef.Diag(TemplateArgs[2].getLocation(),
3453 diag::err_integer_sequence_negative_length);
3454 return QualType();
3455 }
3456
3457 // The first template argument will be reused as the template decl that
3458 // our synthetic template arguments will be applied to.
3459 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3460 TemplateLoc, SyntheticTemplateArgs,
3461 /*Scope=*/nullptr,
3462 /*ForNestedNameSpecifier=*/false);
3463 }
3464
3465 case BTK__type_pack_element: {
3466 // Specializations of
3467 // __type_pack_element<Index, T_1, ..., T_N>
3468 // are treated like T_Index.
3469 assert(Converted.size() == 2 &&
3470 "__type_pack_element should be given an index and a parameter pack");
3471
3472 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3473 if (IndexArg.isDependent() || Ts.isDependent())
3474 return QualType();
3475
3476 llvm::APSInt Index = IndexArg.getAsIntegral();
3477 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3478 "type std::size_t, and hence be non-negative");
3479 // If the Index is out of bounds, the program is ill-formed.
3480 if (Index >= Ts.pack_size()) {
3481 SemaRef.Diag(TemplateArgs[0].getLocation(),
3482 diag::err_type_pack_element_out_of_bounds);
3483 return QualType();
3484 }
3485
3486 // We simply return the type at index `Index`.
3487 int64_t N = Index.getExtValue();
3488 return Ts.getPackAsArray()[N].getAsType();
3489 }
3490
3491 case BTK__builtin_common_type: {
3492 assert(Converted.size() == 4);
3493 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3494 return QualType();
3495
3496 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3497 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3498 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3499 TemplateLoc, Ts);
3500 !CT.isNull()) {
3504 CT, TemplateArgs[1].getLocation())));
3505 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3506 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3507 TAs, /*Scope=*/nullptr,
3508 /*ForNestedNameSpecifier=*/false);
3509 }
3510 QualType HasNoTypeMember = Converted[2].getAsType();
3511 return HasNoTypeMember;
3512 }
3513
3514 case BTK__hlsl_spirv_type: {
3515 assert(Converted.size() == 4);
3516
3517 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3518 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3519 }
3520
3521 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3522 return QualType();
3523
3524 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3525 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3526 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3527
3528 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3529
3531
3532 for (auto &OperandTA : OperandArgs) {
3533 QualType OperandArg = OperandTA.getAsType();
3534 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3535 TemplateArgs[3].getLocation());
3536 if (!Operand.isValid())
3537 return QualType();
3538 Operands.push_back(Operand);
3539 }
3540
3541 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3542 }
3543 case BTK__builtin_dedup_pack: {
3544 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3545 "a parameter pack");
3546 TemplateArgument Ts = Converted[0];
3547 // Delay the computation until we can compute the final result. We choose
3548 // not to remove the duplicates upfront before substitution to keep the code
3549 // simple.
3550 if (Ts.isDependent())
3551 return QualType();
3552 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3554 llvm::SmallDenseSet<QualType> Seen;
3555 // Synthesize a new template argument list, removing duplicates.
3556 for (auto T : Ts.getPackAsArray()) {
3557 assert(T.getKind() == clang::TemplateArgument::Type);
3558 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3559 continue;
3560 OutArgs.push_back(T);
3561 }
3562 return Context.getSubstBuiltinTemplatePack(
3563 TemplateArgument::CreatePackCopy(Context, OutArgs));
3564 }
3565 }
3566 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3567}
3568
3569/// Determine whether this alias template is "enable_if_t".
3570/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3572 return AliasTemplate->getName() == "enable_if_t" ||
3573 AliasTemplate->getName() == "__enable_if_t";
3574}
3575
3576/// Collect all of the separable terms in the given condition, which
3577/// might be a conjunction.
3578///
3579/// FIXME: The right answer is to convert the logical expression into
3580/// disjunctive normal form, so we can find the first failed term
3581/// within each possible clause.
3582static void collectConjunctionTerms(Expr *Clause,
3583 SmallVectorImpl<Expr *> &Terms) {
3584 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3585 if (BinOp->getOpcode() == BO_LAnd) {
3586 collectConjunctionTerms(BinOp->getLHS(), Terms);
3587 collectConjunctionTerms(BinOp->getRHS(), Terms);
3588 return;
3589 }
3590 }
3591
3592 Terms.push_back(Clause);
3593}
3594
3595// The ranges-v3 library uses an odd pattern of a top-level "||" with
3596// a left-hand side that is value-dependent but never true. Identify
3597// the idiom and ignore that term.
3599 // Top-level '||'.
3600 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3601 if (!BinOp) return Cond;
3602
3603 if (BinOp->getOpcode() != BO_LOr) return Cond;
3604
3605 // With an inner '==' that has a literal on the right-hand side.
3606 Expr *LHS = BinOp->getLHS();
3607 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3608 if (!InnerBinOp) return Cond;
3609
3610 if (InnerBinOp->getOpcode() != BO_EQ ||
3611 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3612 return Cond;
3613
3614 // If the inner binary operation came from a macro expansion named
3615 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3616 // of the '||', which is the real, user-provided condition.
3617 SourceLocation Loc = InnerBinOp->getExprLoc();
3618 if (!Loc.isMacroID()) return Cond;
3619
3620 StringRef MacroName = PP.getImmediateMacroName(Loc);
3621 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3622 return BinOp->getRHS();
3623
3624 return Cond;
3625}
3626
3627namespace {
3628
3629// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3630// within failing boolean expression, such as substituting template parameters
3631// for actual types.
3632class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3633public:
3634 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3635 : Policy(P) {}
3636
3637 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3638 const auto *DR = dyn_cast<DeclRefExpr>(E);
3639 if (DR && DR->getQualifier()) {
3640 // If this is a qualified name, expand the template arguments in nested
3641 // qualifiers.
3642 DR->getQualifier().print(OS, Policy, true);
3643 // Then print the decl itself.
3644 const ValueDecl *VD = DR->getDecl();
3645 OS << VD->getName();
3646 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3647 // This is a template variable, print the expanded template arguments.
3648 printTemplateArgumentList(
3649 OS, IV->getTemplateArgs().asArray(), Policy,
3650 IV->getSpecializedTemplate()->getTemplateParameters());
3651 }
3652 return true;
3653 }
3654 return false;
3655 }
3656
3657private:
3658 const PrintingPolicy Policy;
3659};
3660
3661} // end anonymous namespace
3662
3663std::pair<Expr *, std::string>
3666
3667 // Separate out all of the terms in a conjunction.
3670
3671 // Determine which term failed.
3672 Expr *FailedCond = nullptr;
3673 for (Expr *Term : Terms) {
3674 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3675
3676 // Literals are uninteresting.
3677 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3678 isa<IntegerLiteral>(TermAsWritten))
3679 continue;
3680
3681 // The initialization of the parameter from the argument is
3682 // a constant-evaluated context.
3685
3686 bool Succeeded;
3687 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3688 !Succeeded) {
3689 FailedCond = TermAsWritten;
3690 break;
3691 }
3692 }
3693 if (!FailedCond)
3694 FailedCond = Cond->IgnoreParenImpCasts();
3695
3696 std::string Description;
3697 {
3698 llvm::raw_string_ostream Out(Description);
3700 Policy.PrintAsCanonical = true;
3701 FailedBooleanConditionPrinterHelper Helper(Policy);
3702 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3703 }
3704 return { FailedCond, Description };
3705}
3706
3707static TemplateName
3709 const AssumedTemplateStorage *ATN,
3710 SourceLocation NameLoc) {
3711 // We assumed this undeclared identifier to be an (ADL-only) function
3712 // template name, but it was used in a context where a type was required.
3713 // Try to typo-correct it now.
3714 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3715 struct CandidateCallback : CorrectionCandidateCallback {
3716 bool ValidateCandidate(const TypoCorrection &TC) override {
3717 return TC.getCorrectionDecl() &&
3719 }
3720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3721 return std::make_unique<CandidateCallback>(*this);
3722 }
3723 } FilterCCC;
3724
3725 TypoCorrection Corrected =
3727 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3728 if (Corrected && Corrected.getFoundDecl()) {
3729 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3730 << ATN->getDeclName());
3732 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3734 }
3735
3736 return TemplateName();
3737}
3738
3740 TemplateName Name,
3741 SourceLocation TemplateLoc,
3742 TemplateArgumentListInfo &TemplateArgs,
3743 Scope *Scope, bool ForNestedNameSpecifier) {
3744 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3745
3746 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3747 if (!Template) {
3748 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3749 Template = S->getParameterPack();
3750 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3751 if (DTN->getName().getIdentifier())
3752 // When building a template-id where the template-name is dependent,
3753 // assume the template is a type template. Either our assumption is
3754 // correct, or the code is ill-formed and will be diagnosed when the
3755 // dependent name is substituted.
3756 return Context.getTemplateSpecializationType(Keyword, Name,
3757 TemplateArgs.arguments(),
3758 /*CanonicalArgs=*/{});
3759 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3761 *this, Scope, ATN, TemplateLoc);
3762 CorrectedName.isNull()) {
3763 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3764 return QualType();
3765 } else {
3766 Name = CorrectedName;
3767 Template = Name.getAsTemplateDecl();
3768 }
3769 }
3770 }
3771 if (!Template ||
3773 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3774 if (ForNestedNameSpecifier)
3775 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3776 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3777 else
3778 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3780 return QualType();
3781 }
3782
3783 // Check that the template argument list is well-formed for this
3784 // template.
3786 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3787 DefaultArgs, /*PartialTemplateArgs=*/false,
3788 CTAI,
3789 /*UpdateArgsWithConversions=*/true))
3790 return QualType();
3791
3792 QualType CanonType;
3793
3795 // We might have a substituted template template parameter pack. If so,
3796 // build a template specialization type for it.
3798 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3799
3800 // C++0x [dcl.type.elab]p2:
3801 // If the identifier resolves to a typedef-name or the simple-template-id
3802 // resolves to an alias template specialization, the
3803 // elaborated-type-specifier is ill-formed.
3806 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3809 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3810 }
3811
3812 // Find the canonical type for this type alias template specialization.
3813 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3814 if (Pattern->isInvalidDecl())
3815 return QualType();
3816
3817 // Only substitute for the innermost template argument list.
3818 MultiLevelTemplateArgumentList TemplateArgLists;
3820 /*Final=*/true);
3821 TemplateArgLists.addOuterRetainedLevels(
3822 AliasTemplate->getTemplateParameters()->getDepth());
3823
3825
3826 // Diagnose uses of this alias.
3827 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3828
3829 // FIXME: The TemplateArgs passed here are not used for the context note,
3830 // nor they should, because this note will be pointing to the specialization
3831 // anyway. These arguments are needed for a hack for instantiating lambdas
3832 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3833 // arguments will be used for collating the template arguments needed to
3834 // instantiate the lambda.
3835 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3836 /*Entity=*/AliasTemplate,
3837 /*TemplateArgs=*/CTAI.SugaredConverted);
3838 if (Inst.isInvalid())
3839 return QualType();
3840
3841 std::optional<ContextRAII> SavedContext;
3842 if (!AliasTemplate->getDeclContext()->isFileContext())
3843 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3844
3845 CanonType =
3846 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3847 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3848 if (CanonType.isNull()) {
3849 // If this was enable_if and we failed to find the nested type
3850 // within enable_if in a SFINAE context, dig out the specific
3851 // enable_if condition that failed and present that instead.
3853 if (auto DeductionInfo = isSFINAEContext()) {
3854 if (*DeductionInfo &&
3855 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3856 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3857 diag::err_typename_nested_not_found_enable_if &&
3858 TemplateArgs[0].getArgument().getKind()
3860 Expr *FailedCond;
3861 std::string FailedDescription;
3862 std::tie(FailedCond, FailedDescription) =
3863 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3864
3865 // Remove the old SFINAE diagnostic.
3866 PartialDiagnosticAt OldDiag =
3868 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3869
3870 // Add a new SFINAE diagnostic specifying which condition
3871 // failed.
3872 (*DeductionInfo)->addSFINAEDiagnostic(
3873 OldDiag.first,
3874 PDiag(diag::err_typename_nested_not_found_requirement)
3875 << FailedDescription
3876 << FailedCond->getSourceRange());
3877 }
3878 }
3879 }
3880
3881 return QualType();
3882 }
3883 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3884 CanonType = checkBuiltinTemplateIdType(
3885 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3886 } else if (Name.isDependent() ||
3887 TemplateSpecializationType::anyDependentTemplateArguments(
3888 TemplateArgs, CTAI.CanonicalConverted)) {
3889 // This class template specialization is a dependent
3890 // type. Therefore, its canonical type is another class template
3891 // specialization type that contains all of the converted
3892 // arguments in canonical form. This ensures that, e.g., A<T> and
3893 // A<T, T> have identical types when A is declared as:
3894 //
3895 // template<typename T, typename U = T> struct A;
3896 CanonType = Context.getCanonicalTemplateSpecializationType(
3898 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3899 CTAI.CanonicalConverted);
3900 assert(CanonType->isCanonicalUnqualified());
3901
3902 // This might work out to be a current instantiation, in which
3903 // case the canonical type needs to be the InjectedClassNameType.
3904 //
3905 // TODO: in theory this could be a simple hashtable lookup; most
3906 // changes to CurContext don't change the set of current
3907 // instantiations.
3909 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3910 // If we get out to a namespace, we're done.
3911 if (Ctx->isFileContext()) break;
3912
3913 // If this isn't a record, keep looking.
3914 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3915 if (!Record) continue;
3916
3917 // Look for one of the two cases with InjectedClassNameTypes
3918 // and check whether it's the same template.
3920 !Record->getDescribedClassTemplate())
3921 continue;
3922
3923 // Fetch the injected class name type and check whether its
3924 // injected type is equal to the type we just built.
3925 CanQualType ICNT = Context.getCanonicalTagType(Record);
3926 CanQualType Injected =
3927 Record->getCanonicalTemplateSpecializationType(Context);
3928
3929 if (CanonType != Injected)
3930 continue;
3931
3932 // If so, the canonical type of this TST is the injected
3933 // class name type of the record we just found.
3934 CanonType = ICNT;
3935 break;
3936 }
3937 }
3938 } else if (ClassTemplateDecl *ClassTemplate =
3939 dyn_cast<ClassTemplateDecl>(Template)) {
3940 // Find the class template specialization declaration that
3941 // corresponds to these arguments.
3942 void *InsertPos = nullptr;
3944 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3945 if (!Decl) {
3946 // This is the first time we have referenced this class template
3947 // specialization. Create the canonical declaration and add it to
3948 // the set of specializations.
3950 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3951 ClassTemplate->getDeclContext(),
3952 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3953 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3954 CTAI.StrictPackMatch, nullptr);
3955 ClassTemplate->AddSpecialization(Decl, InsertPos);
3956 if (ClassTemplate->isOutOfLine())
3957 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3958 }
3959
3960 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3961 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3962 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3963 if (!Inst.isInvalid()) {
3965 CTAI.CanonicalConverted,
3966 /*Final=*/false);
3967 InstantiateAttrsForDecl(TemplateArgLists,
3968 ClassTemplate->getTemplatedDecl(), Decl);
3969 }
3970 }
3971
3972 // Diagnose uses of this specialization.
3973 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3974
3975 CanonType = Context.getCanonicalTagType(Decl);
3976 assert(isa<RecordType>(CanonType) &&
3977 "type of non-dependent specialization is not a RecordType");
3978 } else {
3979 llvm_unreachable("Unhandled template kind");
3980 }
3981
3982 // Build the fully-sugared type for this class template
3983 // specialization, which refers back to the class template
3984 // specialization we created or found.
3985 return Context.getTemplateSpecializationType(
3986 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3987 CanonType);
3988}
3989
3991 TemplateNameKind &TNK,
3992 SourceLocation NameLoc,
3993 IdentifierInfo *&II) {
3994 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3995
3996 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
3997 assert(ATN && "not an assumed template name");
3998 II = ATN->getDeclName().getAsIdentifierInfo();
3999
4000 if (TemplateName Name =
4001 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4002 !Name.isNull()) {
4003 // Resolved to a type template name.
4004 ParsedName = TemplateTy::make(Name);
4005 TNK = TNK_Type_template;
4006 }
4007}
4008
4010 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4011 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4012 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4013 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4014 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4015 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4016 ImplicitTypenameContext AllowImplicitTypename) {
4017 if (SS.isInvalid())
4018 return true;
4019
4020 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4021 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4022
4023 // C++ [temp.res]p3:
4024 // A qualified-id that refers to a type and in which the
4025 // nested-name-specifier depends on a template-parameter (14.6.2)
4026 // shall be prefixed by the keyword typename to indicate that the
4027 // qualified-id denotes a type, forming an
4028 // elaborated-type-specifier (7.1.5.3).
4029 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4030 // C++2a relaxes some of those restrictions in [temp.res]p5.
4031 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4032 SS.getScopeRep(), TemplateII);
4034 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4035 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4036 << NNS;
4037 if (!getLangOpts().CPlusPlus20)
4038 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4039 } else
4040 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4041
4042 // FIXME: This is not quite correct recovery as we don't transform SS
4043 // into the corresponding dependent form (and we don't diagnose missing
4044 // 'template' keywords within SS as a result).
4045 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4046 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4047 TemplateArgsIn, RAngleLoc);
4048 }
4049
4050 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4051 // it's not actually allowed to be used as a type in most cases. Because
4052 // we annotate it before we know whether it's valid, we have to check for
4053 // this case here.
4054 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4055 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4056 Diag(TemplateIILoc,
4057 TemplateKWLoc.isInvalid()
4058 ? diag::err_out_of_line_qualified_id_type_names_constructor
4059 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4060 << TemplateII << 0 /*injected-class-name used as template name*/
4061 << 1 /*if any keyword was present, it was 'template'*/;
4062 }
4063 }
4064
4065 // Translate the parser's template argument list in our AST format.
4066 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4067 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4068
4070 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4071 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4072 if (SpecTy.isNull())
4073 return true;
4074
4075 // Build type-source information.
4076 TypeLocBuilder TLB;
4077 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4078 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4079 TemplateIILoc, TemplateArgs);
4080 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4081}
4082
4084 TypeSpecifierType TagSpec,
4085 SourceLocation TagLoc,
4086 CXXScopeSpec &SS,
4087 SourceLocation TemplateKWLoc,
4088 TemplateTy TemplateD,
4089 SourceLocation TemplateLoc,
4090 SourceLocation LAngleLoc,
4091 ASTTemplateArgsPtr TemplateArgsIn,
4092 SourceLocation RAngleLoc) {
4093 if (SS.isInvalid())
4094 return TypeResult(true);
4095
4096 // Translate the parser's template argument list in our AST format.
4097 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4098 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4099
4100 // Determine the tag kind
4104
4106 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4107 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4108 if (Result.isNull())
4109 return TypeResult(true);
4110
4111 // Check the tag kind
4112 if (const RecordType *RT = Result->getAs<RecordType>()) {
4113 RecordDecl *D = RT->getOriginalDecl();
4114
4115 IdentifierInfo *Id = D->getIdentifier();
4116 assert(Id && "templated class must have an identifier");
4117
4119 TagLoc, Id)) {
4120 Diag(TagLoc, diag::err_use_with_wrong_tag)
4121 << Result
4123 Diag(D->getLocation(), diag::note_previous_use);
4124 }
4125 }
4126
4127 // Provide source-location information for the template specialization.
4128 TypeLocBuilder TLB;
4130 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4131 TemplateArgs);
4133}
4134
4135static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4136 NamedDecl *PrevDecl,
4137 SourceLocation Loc,
4139
4141
4143 unsigned Depth,
4144 unsigned Index) {
4145 switch (Arg.getKind()) {
4153 return false;
4154
4156 QualType Type = Arg.getAsType();
4157 const TemplateTypeParmType *TPT =
4158 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4159 return TPT && !Type.hasQualifiers() &&
4160 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4161 }
4162
4164 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4165 if (!DRE || !DRE->getDecl())
4166 return false;
4167 const NonTypeTemplateParmDecl *NTTP =
4168 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4169 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4170 }
4171
4173 const TemplateTemplateParmDecl *TTP =
4174 dyn_cast_or_null<TemplateTemplateParmDecl>(
4176 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4177 }
4178 llvm_unreachable("unexpected kind of template argument");
4179}
4180
4182 TemplateParameterList *SpecParams,
4184 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4185 return false;
4186
4187 unsigned Depth = Params->getDepth();
4188
4189 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4190 TemplateArgument Arg = Args[I];
4191
4192 // If the parameter is a pack expansion, the argument must be a pack
4193 // whose only element is a pack expansion.
4194 if (Params->getParam(I)->isParameterPack()) {
4195 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4196 !Arg.pack_begin()->isPackExpansion())
4197 return false;
4198 Arg = Arg.pack_begin()->getPackExpansionPattern();
4199 }
4200
4201 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4202 return false;
4203
4204 // For NTTPs further specialization is allowed via deduced types, so
4205 // we need to make sure to only reject here if primary template and
4206 // specialization use the same type for the NTTP.
4207 if (auto *SpecNTTP =
4208 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4209 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4210 if (!NTTP || NTTP->getType().getCanonicalType() !=
4211 SpecNTTP->getType().getCanonicalType())
4212 return false;
4213 }
4214 }
4215
4216 return true;
4217}
4218
4219template<typename PartialSpecDecl>
4220static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4221 if (Partial->getDeclContext()->isDependentContext())
4222 return;
4223
4224 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4225 // for non-substitution-failure issues?
4226 TemplateDeductionInfo Info(Partial->getLocation());
4227 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4228 return;
4229
4230 auto *Template = Partial->getSpecializedTemplate();
4231 S.Diag(Partial->getLocation(),
4232 diag::ext_partial_spec_not_more_specialized_than_primary)
4234
4235 if (Info.hasSFINAEDiagnostic()) {
4239 SmallString<128> SFINAEArgString;
4240 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4241 S.Diag(Diag.first,
4242 diag::note_partial_spec_not_more_specialized_than_primary)
4243 << SFINAEArgString;
4244 }
4245
4247 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4248 Template->getAssociatedConstraints(TemplateAC);
4249 Partial->getAssociatedConstraints(PartialAC);
4251 TemplateAC);
4252}
4253
4254static void
4256 const llvm::SmallBitVector &DeducibleParams) {
4257 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4258 if (!DeducibleParams[I]) {
4259 NamedDecl *Param = TemplateParams->getParam(I);
4260 if (Param->getDeclName())
4261 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4262 << Param->getDeclName();
4263 else
4264 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4265 << "(anonymous)";
4266 }
4267 }
4268}
4269
4270
4271template<typename PartialSpecDecl>
4273 PartialSpecDecl *Partial) {
4274 // C++1z [temp.class.spec]p8: (DR1495)
4275 // - The specialization shall be more specialized than the primary
4276 // template (14.5.5.2).
4278
4279 // C++ [temp.class.spec]p8: (DR1315)
4280 // - Each template-parameter shall appear at least once in the
4281 // template-id outside a non-deduced context.
4282 // C++1z [temp.class.spec.match]p3 (P0127R2)
4283 // If the template arguments of a partial specialization cannot be
4284 // deduced because of the structure of its template-parameter-list
4285 // and the template-id, the program is ill-formed.
4286 auto *TemplateParams = Partial->getTemplateParameters();
4287 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4288 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4289 TemplateParams->getDepth(), DeducibleParams);
4290
4291 if (!DeducibleParams.all()) {
4292 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4293 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4295 << (NumNonDeducible > 1)
4296 << SourceRange(Partial->getLocation(),
4297 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4298 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4299 }
4300}
4301
4306
4311
4313 // C++1z [temp.param]p11:
4314 // A template parameter of a deduction guide template that does not have a
4315 // default-argument shall be deducible from the parameter-type-list of the
4316 // deduction guide template.
4317 auto *TemplateParams = TD->getTemplateParameters();
4318 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4319 MarkDeducedTemplateParameters(TD, DeducibleParams);
4320 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4321 // A parameter pack is deducible (to an empty pack).
4322 auto *Param = TemplateParams->getParam(I);
4323 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4324 DeducibleParams[I] = true;
4325 }
4326
4327 if (!DeducibleParams.all()) {
4328 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4329 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4330 << (NumNonDeducible > 1);
4331 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4332 }
4333}
4334
4337 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4339 // D must be variable template id.
4341 "Variable template specialization is declared with a template id.");
4342
4343 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4344 TemplateArgumentListInfo TemplateArgs =
4345 makeTemplateArgumentListInfo(*this, *TemplateId);
4346 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4347 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4348 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4349
4350 TemplateName Name = TemplateId->Template.get();
4351
4352 // The template-id must name a variable template.
4354 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4355 if (!VarTemplate) {
4356 NamedDecl *FnTemplate;
4357 if (auto *OTS = Name.getAsOverloadedTemplate())
4358 FnTemplate = *OTS->begin();
4359 else
4360 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4361 if (FnTemplate)
4362 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4363 << FnTemplate->getDeclName();
4364 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4366 }
4367
4368 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4369 auto Message = DSA->getMessage();
4370 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4371 << VarTemplate << !Message.empty() << Message;
4372 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4373 }
4374
4375 // Check for unexpanded parameter packs in any of the template arguments.
4376 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4377 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4381 return true;
4382
4383 // Check that the template argument list is well-formed for this
4384 // template.
4386 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4387 /*DefaultArgs=*/{},
4388 /*PartialTemplateArgs=*/false, CTAI,
4389 /*UpdateArgsWithConversions=*/true))
4390 return true;
4391
4392 // Find the variable template (partial) specialization declaration that
4393 // corresponds to these arguments.
4396 TemplateArgs.size(),
4397 CTAI.CanonicalConverted))
4398 return true;
4399
4400 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4401 // we also do them during instantiation.
4402 if (!Name.isDependent() &&
4403 !TemplateSpecializationType::anyDependentTemplateArguments(
4404 TemplateArgs, CTAI.CanonicalConverted)) {
4405 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4406 << VarTemplate->getDeclName();
4408 }
4409
4410 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4411 TemplateParams, CTAI.CanonicalConverted) &&
4412 (!Context.getLangOpts().CPlusPlus20 ||
4413 !TemplateParams->hasAssociatedConstraints())) {
4414 // C++ [temp.class.spec]p9b3:
4415 //
4416 // -- The argument list of the specialization shall not be identical
4417 // to the implicit argument list of the primary template.
4418 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4419 << /*variable template*/ 1
4420 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4421 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4422 // FIXME: Recover from this by treating the declaration as a
4423 // redeclaration of the primary template.
4424 return true;
4425 }
4426 }
4427
4428 void *InsertPos = nullptr;
4429 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4430
4432 PrevDecl = VarTemplate->findPartialSpecialization(
4433 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4434 else
4435 PrevDecl =
4436 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4437
4439
4440 // Check whether we can declare a variable template specialization in
4441 // the current scope.
4442 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4443 TemplateNameLoc,
4445 return true;
4446
4447 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4448 // Since the only prior variable template specialization with these
4449 // arguments was referenced but not declared, reuse that
4450 // declaration node as our own, updating its source location and
4451 // the list of outer template parameters to reflect our new declaration.
4452 Specialization = PrevDecl;
4453 Specialization->setLocation(TemplateNameLoc);
4454 PrevDecl = nullptr;
4455 } else if (IsPartialSpecialization) {
4456 // Create a new class template partial specialization declaration node.
4458 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4461 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4462 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4463 CTAI.CanonicalConverted);
4464 Partial->setTemplateArgsAsWritten(TemplateArgs);
4465
4466 if (!PrevPartial)
4467 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4468 Specialization = Partial;
4469
4470 // If we are providing an explicit specialization of a member variable
4471 // template specialization, make a note of that.
4472 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4473 PrevPartial->setMemberSpecialization();
4474
4476 } else {
4477 // Create a new class template specialization declaration node for
4478 // this explicit specialization or friend declaration.
4480 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4481 VarTemplate, DI->getType(), DI, SC, CTAI.CanonicalConverted);
4482 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4483
4484 if (!PrevDecl)
4485 VarTemplate->AddSpecialization(Specialization, InsertPos);
4486 }
4487
4488 // C++ [temp.expl.spec]p6:
4489 // If a template, a member template or the member of a class template is
4490 // explicitly specialized then that specialization shall be declared
4491 // before the first use of that specialization that would cause an implicit
4492 // instantiation to take place, in every translation unit in which such a
4493 // use occurs; no diagnostic is required.
4494 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4495 bool Okay = false;
4496 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4497 // Is there any previous explicit specialization declaration?
4499 Okay = true;
4500 break;
4501 }
4502 }
4503
4504 if (!Okay) {
4505 SourceRange Range(TemplateNameLoc, RAngleLoc);
4506 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4507 << Name << Range;
4508
4509 Diag(PrevDecl->getPointOfInstantiation(),
4510 diag::note_instantiation_required_here)
4511 << (PrevDecl->getTemplateSpecializationKind() !=
4513 return true;
4514 }
4515 }
4516
4517 Specialization->setLexicalDeclContext(CurContext);
4518
4519 // Add the specialization into its lexical context, so that it can
4520 // be seen when iterating through the list of declarations in that
4521 // context. However, specializations are not found by name lookup.
4522 CurContext->addDecl(Specialization);
4523
4524 // Note that this is an explicit specialization.
4525 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4526
4527 Previous.clear();
4528 if (PrevDecl)
4529 Previous.addDecl(PrevDecl);
4530 else if (Specialization->isStaticDataMember() &&
4531 Specialization->isOutOfLine())
4532 Specialization->setAccess(VarTemplate->getAccess());
4533
4534 return Specialization;
4535}
4536
4537namespace {
4538/// A partial specialization whose template arguments have matched
4539/// a given template-id.
4540struct PartialSpecMatchResult {
4543};
4544
4545// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4546// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4547static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4548 if (Var->getName() != "format_kind" ||
4549 !Var->getDeclContext()->isStdNamespace())
4550 return false;
4551
4552 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4553 // release in which users can access std::format_kind.
4554 // We can use 20250520 as the final date, see the following commits.
4555 // GCC releases/gcc-15 branch:
4556 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4557 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4558 // GCC master branch:
4559 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4560 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4561 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4562}
4563} // end anonymous namespace
4564
4567 SourceLocation TemplateNameLoc,
4568 const TemplateArgumentListInfo &TemplateArgs,
4569 bool SetWrittenArgs) {
4570 assert(Template && "A variable template id without template?");
4571
4572 // Check that the template argument list is well-formed for this template.
4575 Template, TemplateNameLoc,
4576 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4577 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4578 /*UpdateArgsWithConversions=*/true))
4579 return true;
4580
4581 // Produce a placeholder value if the specialization is dependent.
4582 if (Template->getDeclContext()->isDependentContext() ||
4583 TemplateSpecializationType::anyDependentTemplateArguments(
4584 TemplateArgs, CTAI.CanonicalConverted)) {
4585 if (ParsingInitForAutoVars.empty())
4586 return DeclResult();
4587
4588 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4589 const TemplateArgument &Arg2) {
4590 return Context.isSameTemplateArgument(Arg1, Arg2);
4591 };
4592
4593 if (VarDecl *Var = Template->getTemplatedDecl();
4594 ParsingInitForAutoVars.count(Var) &&
4595 // See comments on this function definition
4596 !IsLibstdcxxStdFormatKind(PP, Var) &&
4597 llvm::equal(
4598 CTAI.CanonicalConverted,
4599 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4600 IsSameTemplateArg)) {
4601 Diag(TemplateNameLoc,
4602 diag::err_auto_variable_cannot_appear_in_own_initializer)
4603 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4604 return true;
4605 }
4606
4608 Template->getPartialSpecializations(PartialSpecs);
4609 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4610 if (ParsingInitForAutoVars.count(Partial) &&
4611 llvm::equal(CTAI.CanonicalConverted,
4612 Partial->getTemplateArgs().asArray(),
4613 IsSameTemplateArg)) {
4614 Diag(TemplateNameLoc,
4615 diag::err_auto_variable_cannot_appear_in_own_initializer)
4616 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4617 << Partial->getType();
4618 return true;
4619 }
4620
4621 return DeclResult();
4622 }
4623
4624 // Find the variable template specialization declaration that
4625 // corresponds to these arguments.
4626 void *InsertPos = nullptr;
4628 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4629 checkSpecializationReachability(TemplateNameLoc, Spec);
4630 if (Spec->getType()->isUndeducedType()) {
4631 if (ParsingInitForAutoVars.count(Spec))
4632 Diag(TemplateNameLoc,
4633 diag::err_auto_variable_cannot_appear_in_own_initializer)
4634 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4635 << Spec->getType();
4636 else
4637 // We are substituting the initializer of this variable template
4638 // specialization.
4639 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4640 << Spec << Spec->getType();
4641
4642 return true;
4643 }
4644 // If we already have a variable template specialization, return it.
4645 return Spec;
4646 }
4647
4648 // This is the first time we have referenced this variable template
4649 // specialization. Create the canonical declaration and add it to
4650 // the set of specializations, based on the closest partial specialization
4651 // that it represents. That is,
4652 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4653 const TemplateArgumentList *PartialSpecArgs = nullptr;
4654 bool AmbiguousPartialSpec = false;
4655 typedef PartialSpecMatchResult MatchResult;
4657 SourceLocation PointOfInstantiation = TemplateNameLoc;
4658 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4659 /*ForTakingAddress=*/false);
4660
4661 // 1. Attempt to find the closest partial specialization that this
4662 // specializes, if any.
4663 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4664 // Perhaps better after unification of DeduceTemplateArguments() and
4665 // getMoreSpecializedPartialSpecialization().
4667 Template->getPartialSpecializations(PartialSpecs);
4668
4669 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4670 // C++ [temp.spec.partial.member]p2:
4671 // If the primary member template is explicitly specialized for a given
4672 // (implicit) specialization of the enclosing class template, the partial
4673 // specializations of the member template are ignored for this
4674 // specialization of the enclosing class template. If a partial
4675 // specialization of the member template is explicitly specialized for a
4676 // given (implicit) specialization of the enclosing class template, the
4677 // primary member template and its other partial specializations are still
4678 // considered for this specialization of the enclosing class template.
4679 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4680 !Partial->getMostRecentDecl()->isMemberSpecialization())
4681 continue;
4682
4683 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4684
4686 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4688 // Store the failed-deduction information for use in diagnostics, later.
4689 // TODO: Actually use the failed-deduction info?
4690 FailedCandidates.addCandidate().set(
4693 (void)Result;
4694 } else {
4695 Matched.push_back(PartialSpecMatchResult());
4696 Matched.back().Partial = Partial;
4697 Matched.back().Args = Info.takeSugared();
4698 }
4699 }
4700
4701 if (Matched.size() >= 1) {
4702 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4703 if (Matched.size() == 1) {
4704 // -- If exactly one matching specialization is found, the
4705 // instantiation is generated from that specialization.
4706 // We don't need to do anything for this.
4707 } else {
4708 // -- If more than one matching specialization is found, the
4709 // partial order rules (14.5.4.2) are used to determine
4710 // whether one of the specializations is more specialized
4711 // than the others. If none of the specializations is more
4712 // specialized than all of the other matching
4713 // specializations, then the use of the variable template is
4714 // ambiguous and the program is ill-formed.
4715 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4716 PEnd = Matched.end();
4717 P != PEnd; ++P) {
4718 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4719 PointOfInstantiation) ==
4720 P->Partial)
4721 Best = P;
4722 }
4723
4724 // Determine if the best partial specialization is more specialized than
4725 // the others.
4726 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4727 PEnd = Matched.end();
4728 P != PEnd; ++P) {
4730 P->Partial, Best->Partial,
4731 PointOfInstantiation) != Best->Partial) {
4732 AmbiguousPartialSpec = true;
4733 break;
4734 }
4735 }
4736 }
4737
4738 // Instantiate using the best variable template partial specialization.
4739 InstantiationPattern = Best->Partial;
4740 PartialSpecArgs = Best->Args;
4741 } else {
4742 // -- If no match is found, the instantiation is generated
4743 // from the primary template.
4744 // InstantiationPattern = Template->getTemplatedDecl();
4745 }
4746
4747 // 2. Create the canonical declaration.
4748 // Note that we do not instantiate a definition until we see an odr-use
4749 // in DoMarkVarDeclReferenced().
4750 // FIXME: LateAttrs et al.?
4752 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4753 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4754 if (!Decl)
4755 return true;
4756 if (SetWrittenArgs)
4757 Decl->setTemplateArgsAsWritten(TemplateArgs);
4758
4759 if (AmbiguousPartialSpec) {
4760 // Partial ordering did not produce a clear winner. Complain.
4762 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4763 << Decl;
4764
4765 // Print the matching partial specializations.
4766 for (MatchResult P : Matched)
4767 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4768 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4769 *P.Args);
4770 return true;
4771 }
4772
4774 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4775 Decl->setInstantiationOf(D, PartialSpecArgs);
4776
4777 checkSpecializationReachability(TemplateNameLoc, Decl);
4778
4779 assert(Decl && "No variable template specialization?");
4780 return Decl;
4781}
4782
4784 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4785 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4786 const TemplateArgumentListInfo *TemplateArgs) {
4787
4788 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4789 *TemplateArgs, /*SetWrittenArgs=*/false);
4790 if (Decl.isInvalid())
4791 return ExprError();
4792
4793 if (!Decl.get())
4794 return ExprResult();
4795
4796 VarDecl *Var = cast<VarDecl>(Decl.get());
4799 NameInfo.getLoc());
4800
4801 // Build an ordinary singleton decl ref.
4802 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4803}
4804
4806 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4808 const TemplateArgumentListInfo *TemplateArgs) {
4809 assert(Template && "A variable template id without template?");
4810
4811 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4812 Template->templateParameterKind() !=
4814 return ExprResult();
4815
4816 // Check that the template argument list is well-formed for this template.
4819 Template, TemplateLoc,
4820 // FIXME: TemplateArgs will not be modified because
4821 // UpdateArgsWithConversions is false, however, we should
4822 // CheckTemplateArgumentList to be const-correct.
4823 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4824 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4825 /*UpdateArgsWithConversions=*/false))
4826 return true;
4827
4829 R.addDecl(Template);
4830
4831 // FIXME: We model references to variable template and concept parameters
4832 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4833 // data, can generally be used in the same places and work the same way.
4834 // However, it might be cleaner to use a dedicated AST node in the long run.
4837 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4838 /*KnownDependent=*/false,
4839 /*KnownInstantiationDependent=*/false);
4840}
4841
4843 SourceLocation Loc) {
4844 Diag(Loc, diag::err_template_missing_args)
4845 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4846 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4847 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4848 }
4849}
4850
4852 bool TemplateKeyword,
4853 TemplateDecl *TD,
4854 SourceLocation Loc) {
4855 TemplateName Name = Context.getQualifiedTemplateName(
4856 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4858}
4859
4861 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4862 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4863 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4864 bool DoCheckConstraintSatisfaction) {
4865 assert(NamedConcept && "A concept template id without a template?");
4866
4867 if (NamedConcept->isInvalidDecl())
4868 return ExprError();
4869
4872 NamedConcept, ConceptNameInfo.getLoc(),
4873 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4874 /*DefaultArgs=*/{},
4875 /*PartialTemplateArgs=*/false, CTAI,
4876 /*UpdateArgsWithConversions=*/false))
4877 return ExprError();
4878
4879 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4880
4881 // There's a bug with CTAI.CanonicalConverted.
4882 // If the template argument contains a DependentDecltypeType that includes a
4883 // TypeAliasType, and the same written type had occurred previously in the
4884 // source, then the DependentDecltypeType would be canonicalized to that
4885 // previous type which would mess up the substitution.
4886 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4888 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4889 CTAI.SugaredConverted);
4890 ConstraintSatisfaction Satisfaction;
4891 bool AreArgsDependent =
4892 TemplateSpecializationType::anyDependentTemplateArguments(
4893 *TemplateArgs, CTAI.SugaredConverted);
4894 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4895 /*Final=*/false);
4897 Context,
4899 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4901
4902 bool Error = false;
4903 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4904 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4905 DoCheckConstraintSatisfaction) {
4906
4908
4911
4913 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4914 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4915 TemplateArgs->getRAngleLoc()),
4916 Satisfaction, CL);
4917 Satisfaction.ContainsErrors = Error;
4918 }
4919
4920 if (Error)
4921 return ExprError();
4922
4924 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4925}
4926
4928 SourceLocation TemplateKWLoc,
4929 LookupResult &R,
4930 bool RequiresADL,
4931 const TemplateArgumentListInfo *TemplateArgs) {
4932 // FIXME: Can we do any checking at this point? I guess we could check the
4933 // template arguments that we have against the template name, if the template
4934 // name refers to a single template. That's not a terribly common case,
4935 // though.
4936 // foo<int> could identify a single function unambiguously
4937 // This approach does NOT work, since f<int>(1);
4938 // gets resolved prior to resorting to overload resolution
4939 // i.e., template<class T> void f(double);
4940 // vs template<class T, class U> void f(U);
4941
4942 // These should be filtered out by our callers.
4943 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4944
4945 // Non-function templates require a template argument list.
4946 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4947 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4949 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4950 return ExprError();
4951 }
4952 }
4953 bool KnownDependent = false;
4954 // In C++1y, check variable template ids.
4955 if (R.getAsSingle<VarTemplateDecl>()) {
4958 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4959 if (Res.isInvalid() || Res.isUsable())
4960 return Res;
4961 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4962 KnownDependent = true;
4963 }
4964
4965 // We don't want lookup warnings at this point.
4967
4968 if (R.getAsSingle<ConceptDecl>()) {
4969 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4971 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4972 }
4973
4974 // Check variable template ids (C++17) and concept template parameters
4975 // (C++26).
4980 TemplateKWLoc, TemplateArgs);
4981
4982 // Function templates
4985 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4986 R.begin(), R.end(), KnownDependent,
4987 /*KnownInstantiationDependent=*/false);
4988 // Model the templates with UnresolvedTemplateTy. The expression should then
4989 // either be transformed in an instantiation or be diagnosed in
4990 // CheckPlaceholderExpr.
4991 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4993 ULE->setType(Context.UnresolvedTemplateTy);
4994
4995 return ULE;
4996}
4997
4999 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5000 const DeclarationNameInfo &NameInfo,
5001 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5002 assert(TemplateArgs || TemplateKWLoc.isValid());
5003
5004 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5005 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5006 /*EnteringContext=*/false, TemplateKWLoc))
5007 return ExprError();
5008
5009 if (R.isAmbiguous())
5010 return ExprError();
5011
5013 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5014
5015 if (R.empty()) {
5017 Diag(NameInfo.getLoc(), diag::err_no_member)
5018 << NameInfo.getName() << DC << SS.getRange();
5019 return ExprError();
5020 }
5021
5022 // If necessary, build an implicit class member access.
5023 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5024 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5025 /*S=*/nullptr);
5026
5027 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5028}
5029
5031 CXXScopeSpec &SS,
5032 SourceLocation TemplateKWLoc,
5033 const UnqualifiedId &Name,
5034 ParsedType ObjectType,
5035 bool EnteringContext,
5037 bool AllowInjectedClassName) {
5038 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5039 Diag(TemplateKWLoc,
5041 diag::warn_cxx98_compat_template_outside_of_template :
5042 diag::ext_template_outside_of_template)
5043 << FixItHint::CreateRemoval(TemplateKWLoc);
5044
5045 if (SS.isInvalid())
5046 return TNK_Non_template;
5047
5048 // Figure out where isTemplateName is going to look.
5049 DeclContext *LookupCtx = nullptr;
5050 if (SS.isNotEmpty())
5051 LookupCtx = computeDeclContext(SS, EnteringContext);
5052 else if (ObjectType)
5053 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5054
5055 // C++0x [temp.names]p5:
5056 // If a name prefixed by the keyword template is not the name of
5057 // a template, the program is ill-formed. [Note: the keyword
5058 // template may not be applied to non-template members of class
5059 // templates. -end note ] [ Note: as is the case with the
5060 // typename prefix, the template prefix is allowed in cases
5061 // where it is not strictly necessary; i.e., when the
5062 // nested-name-specifier or the expression on the left of the ->
5063 // or . is not dependent on a template-parameter, or the use
5064 // does not appear in the scope of a template. -end note]
5065 //
5066 // Note: C++03 was more strict here, because it banned the use of
5067 // the "template" keyword prior to a template-name that was not a
5068 // dependent name. C++ DR468 relaxed this requirement (the
5069 // "template" keyword is now permitted). We follow the C++0x
5070 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5071 bool MemberOfUnknownSpecialization;
5072 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5073 ObjectType, EnteringContext, Result,
5074 MemberOfUnknownSpecialization);
5075 if (TNK != TNK_Non_template) {
5076 // We resolved this to a (non-dependent) template name. Return it.
5077 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5078 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5080 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5081 // C++14 [class.qual]p2:
5082 // In a lookup in which function names are not ignored and the
5083 // nested-name-specifier nominates a class C, if the name specified
5084 // [...] is the injected-class-name of C, [...] the name is instead
5085 // considered to name the constructor
5086 //
5087 // We don't get here if naming the constructor would be valid, so we
5088 // just reject immediately and recover by treating the
5089 // injected-class-name as naming the template.
5090 Diag(Name.getBeginLoc(),
5091 diag::ext_out_of_line_qualified_id_type_names_constructor)
5092 << Name.Identifier
5093 << 0 /*injected-class-name used as template name*/
5094 << TemplateKWLoc.isValid();
5095 }
5096 return TNK;
5097 }
5098
5099 if (!MemberOfUnknownSpecialization) {
5100 // Didn't find a template name, and the lookup wasn't dependent.
5101 // Do the lookup again to determine if this is a "nothing found" case or
5102 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5103 // need to do this.
5105 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5107 // Tell LookupTemplateName that we require a template so that it diagnoses
5108 // cases where it finds a non-template.
5109 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5110 ? RequiredTemplateKind(TemplateKWLoc)
5112 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5113 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5114 !R.isAmbiguous()) {
5115 if (LookupCtx)
5116 Diag(Name.getBeginLoc(), diag::err_no_member)
5117 << DNI.getName() << LookupCtx << SS.getRange();
5118 else
5119 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5120 << DNI.getName() << SS.getRange();
5121 }
5122 return TNK_Non_template;
5123 }
5124
5125 NestedNameSpecifier Qualifier = SS.getScopeRep();
5126
5127 switch (Name.getKind()) {
5129 Result = TemplateTy::make(Context.getDependentTemplateName(
5130 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5132
5134 Result = TemplateTy::make(Context.getDependentTemplateName(
5135 {Qualifier, Name.OperatorFunctionId.Operator,
5136 TemplateKWLoc.isValid()}));
5137 return TNK_Function_template;
5138
5140 // This is a kind of template name, but can never occur in a dependent
5141 // scope (literal operators can only be declared at namespace scope).
5142 break;
5143
5144 default:
5145 break;
5146 }
5147
5148 // This name cannot possibly name a dependent template. Diagnose this now
5149 // rather than building a dependent template name that can never be valid.
5150 Diag(Name.getBeginLoc(),
5151 diag::err_template_kw_refers_to_dependent_non_template)
5153 << TemplateKWLoc.isValid() << TemplateKWLoc;
5154 return TNK_Non_template;
5155}
5156
5159 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5160 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5161 const TemplateArgument &Arg = AL.getArgument();
5163 TypeSourceInfo *TSI = nullptr;
5164
5165 // Check template type parameter.
5166 switch(Arg.getKind()) {
5168 // C++ [temp.arg.type]p1:
5169 // A template-argument for a template-parameter which is a
5170 // type shall be a type-id.
5171 ArgType = Arg.getAsType();
5172 TSI = AL.getTypeSourceInfo();
5173 break;
5176 // We have a template type parameter but the template argument
5177 // is a template without any arguments.
5178 SourceRange SR = AL.getSourceRange();
5181 return true;
5182 }
5184 // We have a template type parameter but the template argument is an
5185 // expression; see if maybe it is missing the "typename" keyword.
5186 CXXScopeSpec SS;
5187 DeclarationNameInfo NameInfo;
5188
5189 if (DependentScopeDeclRefExpr *ArgExpr =
5190 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5191 SS.Adopt(ArgExpr->getQualifierLoc());
5192 NameInfo = ArgExpr->getNameInfo();
5193 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5194 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5195 if (ArgExpr->isImplicitAccess()) {
5196 SS.Adopt(ArgExpr->getQualifierLoc());
5197 NameInfo = ArgExpr->getMemberNameInfo();
5198 }
5199 }
5200
5201 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5202 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5203 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5204
5205 if (Result.getAsSingle<TypeDecl>() ||
5206 Result.wasNotFoundInCurrentInstantiation()) {
5207 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5208 // Suggest that the user add 'typename' before the NNS.
5210 Diag(Loc, getLangOpts().MSVCCompat
5211 ? diag::ext_ms_template_type_arg_missing_typename
5212 : diag::err_template_arg_must_be_type_suggest)
5213 << FixItHint::CreateInsertion(Loc, "typename ");
5215
5216 // Recover by synthesizing a type using the location information that we
5217 // already have.
5218 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5219 SS.getScopeRep(), II);
5220 TypeLocBuilder TLB;
5222 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5224 TL.setNameLoc(NameInfo.getLoc());
5225 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5226
5227 // Overwrite our input TemplateArgumentLoc so that we can recover
5228 // properly.
5231
5232 break;
5233 }
5234 }
5235 // fallthrough
5236 [[fallthrough]];
5237 }
5238 default: {
5239 // We allow instantiating a template with template argument packs when
5240 // building deduction guides or mapping constraint template parameters.
5241 if (Arg.getKind() == TemplateArgument::Pack &&
5242 (CodeSynthesisContexts.back().Kind ==
5245 SugaredConverted.push_back(Arg);
5246 CanonicalConverted.push_back(Arg);
5247 return false;
5248 }
5249 // We have a template type parameter but the template argument
5250 // is not a type.
5251 SourceRange SR = AL.getSourceRange();
5252 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5254
5255 return true;
5256 }
5257 }
5258
5259 if (CheckTemplateArgument(TSI))
5260 return true;
5261
5262 // Objective-C ARC:
5263 // If an explicitly-specified template argument type is a lifetime type
5264 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5265 if (getLangOpts().ObjCAutoRefCount &&
5266 ArgType->isObjCLifetimeType() &&
5267 !ArgType.getObjCLifetime()) {
5268 Qualifiers Qs;
5270 ArgType = Context.getQualifiedType(ArgType, Qs);
5271 }
5272
5273 SugaredConverted.push_back(TemplateArgument(ArgType));
5274 CanonicalConverted.push_back(
5275 TemplateArgument(Context.getCanonicalType(ArgType)));
5276 return false;
5277}
5278
5279/// Substitute template arguments into the default template argument for
5280/// the given template type parameter.
5281///
5282/// \param SemaRef the semantic analysis object for which we are performing
5283/// the substitution.
5284///
5285/// \param Template the template that we are synthesizing template arguments
5286/// for.
5287///
5288/// \param TemplateLoc the location of the template name that started the
5289/// template-id we are checking.
5290///
5291/// \param RAngleLoc the location of the right angle bracket ('>') that
5292/// terminates the template-id.
5293///
5294/// \param Param the template template parameter whose default we are
5295/// substituting into.
5296///
5297/// \param Converted the list of template arguments provided for template
5298/// parameters that precede \p Param in the template parameter list.
5299///
5300/// \param Output the resulting substituted template argument.
5301///
5302/// \returns true if an error occurred.
5304 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5305 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5306 ArrayRef<TemplateArgument> SugaredConverted,
5307 ArrayRef<TemplateArgument> CanonicalConverted,
5308 TemplateArgumentLoc &Output) {
5309 Output = Param->getDefaultArgument();
5310
5311 // If the argument type is dependent, instantiate it now based
5312 // on the previously-computed template arguments.
5313 if (Output.getArgument().isInstantiationDependent()) {
5314 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5315 SugaredConverted,
5316 SourceRange(TemplateLoc, RAngleLoc));
5317 if (Inst.isInvalid())
5318 return true;
5319
5320 // Only substitute for the innermost template argument list.
5321 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5322 /*Final=*/true);
5323 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5324 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5325
5326 bool ForLambdaCallOperator = false;
5327 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5328 ForLambdaCallOperator = Rec->isLambda();
5329 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5330 !ForLambdaCallOperator);
5331
5332 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5333 Param->getDefaultArgumentLoc(),
5334 Param->getDeclName()))
5335 return true;
5336 }
5337
5338 return false;
5339}
5340
5341/// Substitute template arguments into the default template argument for
5342/// the given non-type template parameter.
5343///
5344/// \param SemaRef the semantic analysis object for which we are performing
5345/// the substitution.
5346///
5347/// \param Template the template that we are synthesizing template arguments
5348/// for.
5349///
5350/// \param TemplateLoc the location of the template name that started the
5351/// template-id we are checking.
5352///
5353/// \param RAngleLoc the location of the right angle bracket ('>') that
5354/// terminates the template-id.
5355///
5356/// \param Param the non-type template parameter whose default we are
5357/// substituting into.
5358///
5359/// \param Converted the list of template arguments provided for template
5360/// parameters that precede \p Param in the template parameter list.
5361///
5362/// \returns the substituted template argument, or NULL if an error occurred.
5364 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5365 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5366 ArrayRef<TemplateArgument> SugaredConverted,
5367 ArrayRef<TemplateArgument> CanonicalConverted,
5368 TemplateArgumentLoc &Output) {
5369 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5370 SugaredConverted,
5371 SourceRange(TemplateLoc, RAngleLoc));
5372 if (Inst.isInvalid())
5373 return true;
5374
5375 // Only substitute for the innermost template argument list.
5376 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5377 /*Final=*/true);
5378 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5379 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5380
5381 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5382 EnterExpressionEvaluationContext ConstantEvaluated(
5384 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5385 TemplateArgLists, Output);
5386}
5387
5388/// Substitute template arguments into the default template argument for
5389/// the given template template parameter.
5390///
5391/// \param SemaRef the semantic analysis object for which we are performing
5392/// the substitution.
5393///
5394/// \param Template the template that we are synthesizing template arguments
5395/// for.
5396///
5397/// \param TemplateLoc the location of the template name that started the
5398/// template-id we are checking.
5399///
5400/// \param RAngleLoc the location of the right angle bracket ('>') that
5401/// terminates the template-id.
5402///
5403/// \param Param the template template parameter whose default we are
5404/// substituting into.
5405///
5406/// \param Converted the list of template arguments provided for template
5407/// parameters that precede \p Param in the template parameter list.
5408///
5409/// \param QualifierLoc Will be set to the nested-name-specifier (with
5410/// source-location information) that precedes the template name.
5411///
5412/// \returns the substituted template argument, or NULL if an error occurred.
5414 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5415 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5417 ArrayRef<TemplateArgument> SugaredConverted,
5418 ArrayRef<TemplateArgument> CanonicalConverted,
5419 NestedNameSpecifierLoc &QualifierLoc) {
5421 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5422 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5423 if (Inst.isInvalid())
5424 return TemplateName();
5425
5426 // Only substitute for the innermost template argument list.
5427 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5428 /*Final=*/true);
5429 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5430 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5431
5432 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5433
5434 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5435 QualifierLoc = A.getTemplateQualifierLoc();
5436 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5438 A.getTemplateNameLoc(), TemplateArgLists);
5439}
5440
5442 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5443 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5444 ArrayRef<TemplateArgument> SugaredConverted,
5445 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5446 HasDefaultArg = false;
5447
5448 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5449 if (!hasReachableDefaultArgument(TypeParm))
5450 return TemplateArgumentLoc();
5451
5452 HasDefaultArg = true;
5453 TemplateArgumentLoc Output;
5454 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5455 RAngleLoc, TypeParm, SugaredConverted,
5456 CanonicalConverted, Output))
5457 return TemplateArgumentLoc();
5458 return Output;
5459 }
5460
5461 if (NonTypeTemplateParmDecl *NonTypeParm
5462 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5463 if (!hasReachableDefaultArgument(NonTypeParm))
5464 return TemplateArgumentLoc();
5465
5466 HasDefaultArg = true;
5467 TemplateArgumentLoc Output;
5468 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5469 RAngleLoc, NonTypeParm, SugaredConverted,
5470 CanonicalConverted, Output))
5471 return TemplateArgumentLoc();
5472 return Output;
5473 }
5474
5475 TemplateTemplateParmDecl *TempTempParm
5477 if (!hasReachableDefaultArgument(TempTempParm))
5478 return TemplateArgumentLoc();
5479
5480 HasDefaultArg = true;
5481 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5482 NestedNameSpecifierLoc QualifierLoc;
5484 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5485 SugaredConverted, CanonicalConverted, QualifierLoc);
5486 if (TName.isNull())
5487 return TemplateArgumentLoc();
5488
5489 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5490 QualifierLoc, A.getTemplateNameLoc());
5491}
5492
5493/// Convert a template-argument that we parsed as a type into a template, if
5494/// possible. C++ permits injected-class-names to perform dual service as
5495/// template template arguments and as template type arguments.
5498 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5499 if (!TagLoc)
5500 return TemplateArgumentLoc();
5501
5502 // If this type was written as an injected-class-name, it can be used as a
5503 // template template argument.
5504 // If this type was written as an injected-class-name, it may have been
5505 // converted to a RecordType during instantiation. If the RecordType is
5506 // *not* wrapped in a TemplateSpecializationType and denotes a class
5507 // template specialization, it must have come from an injected-class-name.
5508
5509 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5510 if (Name.isNull())
5511 return TemplateArgumentLoc();
5512
5513 return TemplateArgumentLoc(Context, Name,
5514 /*TemplateKWLoc=*/SourceLocation(),
5515 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5516}
5517
5520 SourceLocation TemplateLoc,
5521 SourceLocation RAngleLoc,
5522 unsigned ArgumentPackIndex,
5525 // Check template type parameters.
5526 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5527 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5528 CTAI.CanonicalConverted);
5529
5530 const TemplateArgument &Arg = ArgLoc.getArgument();
5531 // Check non-type template parameters.
5532 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5533 // Do substitution on the type of the non-type template parameter
5534 // with the template arguments we've seen thus far. But if the
5535 // template has a dependent context then we cannot substitute yet.
5536 QualType NTTPType = NTTP->getType();
5537 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5538 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5539
5540 if (NTTPType->isInstantiationDependentType()) {
5541 // Do substitution on the type of the non-type template parameter.
5542 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5543 CTAI.SugaredConverted,
5544 SourceRange(TemplateLoc, RAngleLoc));
5545 if (Inst.isInvalid())
5546 return true;
5547
5549 /*Final=*/true);
5550 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5551 // If the parameter is a pack expansion, expand this slice of the pack.
5552 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5553 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5554 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5555 NTTP->getDeclName());
5556 } else {
5557 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5558 NTTP->getDeclName());
5559 }
5560
5561 // If that worked, check the non-type template parameter type
5562 // for validity.
5563 if (!NTTPType.isNull())
5564 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5565 NTTP->getLocation());
5566 if (NTTPType.isNull())
5567 return true;
5568 }
5569
5570 auto checkExpr = [&](Expr *E) -> Expr * {
5571 TemplateArgument SugaredResult, CanonicalResult;
5572 unsigned CurSFINAEErrors = NumSFINAEErrors;
5574 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5575 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5576 // If the current template argument causes an error, give up now.
5577 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5578 return nullptr;
5579 CTAI.SugaredConverted.push_back(SugaredResult);
5580 CTAI.CanonicalConverted.push_back(CanonicalResult);
5581 return Res.get();
5582 };
5583
5584 switch (Arg.getKind()) {
5586 llvm_unreachable("Should never see a NULL template argument here");
5587
5589 Expr *E = Arg.getAsExpr();
5590 Expr *R = checkExpr(E);
5591 if (!R)
5592 return true;
5593 // If the resulting expression is new, then use it in place of the
5594 // old expression in the template argument.
5595 if (R != E) {
5596 TemplateArgument TA(R, /*IsCanonical=*/false);
5597 ArgLoc = TemplateArgumentLoc(TA, R);
5598 }
5599 break;
5600 }
5601
5602 // As for the converted NTTP kinds, they still might need another
5603 // conversion, as the new corresponding parameter might be different.
5604 // Ideally, we would always perform substitution starting with sugared types
5605 // and never need these, as we would still have expressions. Since these are
5606 // needed so rarely, it's probably a better tradeoff to just convert them
5607 // back to expressions.
5612 // FIXME: StructuralValue is untested here.
5613 ExprResult R =
5615 assert(R.isUsable());
5616 if (!checkExpr(R.get()))
5617 return true;
5618 break;
5619 }
5620
5623 // We were given a template template argument. It may not be ill-formed;
5624 // see below.
5627 // We have a template argument such as \c T::template X, which we
5628 // parsed as a template template argument. However, since we now
5629 // know that we need a non-type template argument, convert this
5630 // template name into an expression.
5631
5632 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5633 ArgLoc.getTemplateNameLoc());
5634
5635 CXXScopeSpec SS;
5636 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5637 // FIXME: the template-template arg was a DependentTemplateName,
5638 // so it was provided with a template keyword. However, its source
5639 // location is not stored in the template argument structure.
5640 SourceLocation TemplateKWLoc;
5642 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5643 nullptr);
5644
5645 // If we parsed the template argument as a pack expansion, create a
5646 // pack expansion expression.
5649 if (E.isInvalid())
5650 return true;
5651 }
5652
5653 TemplateArgument SugaredResult, CanonicalResult;
5655 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5656 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5657 if (E.isInvalid())
5658 return true;
5659
5660 CTAI.SugaredConverted.push_back(SugaredResult);
5661 CTAI.CanonicalConverted.push_back(CanonicalResult);
5662 break;
5663 }
5664
5665 // We have a template argument that actually does refer to a class
5666 // template, alias template, or template template parameter, and
5667 // therefore cannot be a non-type template argument.
5668 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5669 << ArgLoc.getSourceRange();
5671
5672 return true;
5673
5675 // We have a non-type template parameter but the template
5676 // argument is a type.
5677
5678 // C++ [temp.arg]p2:
5679 // In a template-argument, an ambiguity between a type-id and
5680 // an expression is resolved to a type-id, regardless of the
5681 // form of the corresponding template-parameter.
5682 //
5683 // We warn specifically about this case, since it can be rather
5684 // confusing for users.
5685 QualType T = Arg.getAsType();
5686 SourceRange SR = ArgLoc.getSourceRange();
5687 if (T->isFunctionType())
5688 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5689 else
5690 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5692 return true;
5693 }
5694
5696 llvm_unreachable("Caller must expand template argument packs");
5697 }
5698
5699 return false;
5700 }
5701
5702
5703 // Check template template parameters.
5705
5706 TemplateParameterList *Params = TempParm->getTemplateParameters();
5707 if (TempParm->isExpandedParameterPack())
5708 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5709
5710 // Substitute into the template parameter list of the template
5711 // template parameter, since previously-supplied template arguments
5712 // may appear within the template template parameter.
5713 //
5714 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5715 {
5716 // Set up a template instantiation context.
5718 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5719 CTAI.SugaredConverted,
5720 SourceRange(TemplateLoc, RAngleLoc));
5721 if (Inst.isInvalid())
5722 return true;
5723
5724 Params = SubstTemplateParams(
5725 Params, CurContext,
5727 /*Final=*/true),
5728 /*EvaluateConstraints=*/false);
5729 if (!Params)
5730 return true;
5731 }
5732
5733 // C++1z [temp.local]p1: (DR1004)
5734 // When [the injected-class-name] is used [...] as a template-argument for
5735 // a template template-parameter [...] it refers to the class template
5736 // itself.
5737 if (Arg.getKind() == TemplateArgument::Type) {
5739 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5740 if (!ConvertedArg.getArgument().isNull())
5741 ArgLoc = ConvertedArg;
5742 }
5743
5744 switch (Arg.getKind()) {
5746 llvm_unreachable("Should never see a NULL template argument here");
5747
5750 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5751 CTAI.PartialOrdering,
5752 &CTAI.StrictPackMatch))
5753 return true;
5754
5755 CTAI.SugaredConverted.push_back(Arg);
5756 CTAI.CanonicalConverted.push_back(
5757 Context.getCanonicalTemplateArgument(Arg));
5758 break;
5759
5762 auto Kind = 0;
5763 switch (TempParm->templateParameterKind()) {
5765 Kind = 1;
5766 break;
5768 Kind = 2;
5769 break;
5770 default:
5771 break;
5772 }
5773
5774 // We have a template template parameter but the template
5775 // argument does not refer to a template.
5776 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5777 << Kind << getLangOpts().CPlusPlus11;
5778 return true;
5779 }
5780
5785 llvm_unreachable("non-type argument with template template parameter");
5786
5788 llvm_unreachable("Caller must expand template argument packs");
5789 }
5790
5791 return false;
5792}
5793
5794/// Diagnose a missing template argument.
5795template<typename TemplateParmDecl>
5797 TemplateDecl *TD,
5798 const TemplateParmDecl *D,
5800 // Dig out the most recent declaration of the template parameter; there may be
5801 // declarations of the template that are more recent than TD.
5803 ->getTemplateParameters()
5804 ->getParam(D->getIndex()));
5805
5806 // If there's a default argument that's not reachable, diagnose that we're
5807 // missing a module import.
5809 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5811 D->getDefaultArgumentLoc(), Modules,
5813 /*Recover*/true);
5814 return true;
5815 }
5816
5817 // FIXME: If there's a more recent default argument that *is* visible,
5818 // diagnose that it was declared too late.
5819
5821
5822 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5823 << /*not enough args*/0
5825 << TD;
5826 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5827 return true;
5828}
5829
5830/// Check that the given template argument list is well-formed
5831/// for specializing the given template.
5833 TemplateDecl *Template, SourceLocation TemplateLoc,
5834 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5835 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5836 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5838 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5839 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5841}
5842
5843/// Check that the given template argument list is well-formed
5844/// for specializing the given template.
5847 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5848 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5849 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5851
5853 *ConstraintsNotSatisfied = false;
5854
5855 // Make a copy of the template arguments for processing. Only make the
5856 // changes at the end when successful in matching the arguments to the
5857 // template.
5858 TemplateArgumentListInfo NewArgs = TemplateArgs;
5859
5860 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5861
5862 // C++23 [temp.arg.general]p1:
5863 // [...] The type and form of each template-argument specified in
5864 // a template-id shall match the type and form specified for the
5865 // corresponding parameter declared by the template in its
5866 // template-parameter-list.
5867 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5868 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5869 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5870 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5871 LocalInstantiationScope InstScope(*this, true);
5872 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5873 ParamEnd = Params->end(),
5874 Param = ParamBegin;
5875 Param != ParamEnd;
5876 /* increment in loop */) {
5877 if (size_t ParamIdx = Param - ParamBegin;
5878 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5879 // All written arguments should have been consumed by this point.
5880 assert(ArgIdx == NumArgs && "bad default argument deduction");
5881 if (ParamIdx == DefaultArgs.StartPos) {
5882 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5883 // Default arguments from a DeducedTemplateName are already converted.
5884 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5885 CTAI.SugaredConverted.push_back(DefArg);
5886 CTAI.CanonicalConverted.push_back(
5887 Context.getCanonicalTemplateArgument(DefArg));
5888 ++Param;
5889 }
5890 continue;
5891 }
5892 }
5893
5894 // If we have an expanded parameter pack, make sure we don't have too
5895 // many arguments.
5896 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5897 if (*Expansions == SugaredArgumentPack.size()) {
5898 // We're done with this parameter pack. Pack up its arguments and add
5899 // them to the list.
5900 CTAI.SugaredConverted.push_back(
5901 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5902 SugaredArgumentPack.clear();
5903
5904 CTAI.CanonicalConverted.push_back(
5905 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5906 CanonicalArgumentPack.clear();
5907
5908 // This argument is assigned to the next parameter.
5909 ++Param;
5910 continue;
5911 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5912 // Not enough arguments for this parameter pack.
5913 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5914 << /*not enough args*/0
5916 << Template;
5918 return true;
5919 }
5920 }
5921
5922 // Check for builtins producing template packs in this context, we do not
5923 // support them yet.
5924 if (const NonTypeTemplateParmDecl *NTTP =
5925 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5926 NTTP && NTTP->isPackExpansion()) {
5927 auto TL = NTTP->getTypeSourceInfo()
5928 ->getTypeLoc()
5931 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5932 for (const auto &UPP : Unexpanded) {
5933 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5934 if (!TST)
5935 continue;
5936 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5937 // Expanding a built-in pack in this context is not yet supported.
5938 Diag(TL.getEllipsisLoc(),
5939 diag::err_unsupported_builtin_template_pack_expansion)
5940 << TST->getTemplateName();
5941 return true;
5942 }
5943 }
5944
5945 if (ArgIdx < NumArgs) {
5946 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5947 bool NonPackParameter =
5948 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5949 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5950
5951 if (ArgIsExpansion && CTAI.MatchingTTP) {
5952 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5953 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5954 ++Param) {
5955 TemplateArgument &Arg = Args[Param - First];
5956 Arg = ArgLoc.getArgument();
5957 if (!(*Param)->isTemplateParameterPack() ||
5958 getExpandedPackSize(*Param))
5959 Arg = Arg.getPackExpansionPattern();
5960 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5961 SaveAndRestore _1(CTAI.PartialOrdering, false);
5962 SaveAndRestore _2(CTAI.MatchingTTP, true);
5963 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5964 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5966 return true;
5967 Arg = NewArgLoc.getArgument();
5968 CTAI.CanonicalConverted.back().setIsDefaulted(
5969 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5970 CTAI.CanonicalConverted,
5971 Params->getDepth()));
5972 }
5973 ArgLoc =
5975 ArgLoc.getLocInfo());
5976 } else {
5977 SaveAndRestore _1(CTAI.PartialOrdering, false);
5978 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5979 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5981 return true;
5982 CTAI.CanonicalConverted.back().setIsDefaulted(
5983 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5984 *Param, CTAI.CanonicalConverted,
5985 Params->getDepth()));
5986 if (ArgIsExpansion && NonPackParameter) {
5987 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5988 // alias template or concept, and it's not part of a parameter pack.
5989 // This can't be canonicalized, so reject it now.
5991 Diag(ArgLoc.getLocation(),
5992 diag::err_template_expansion_into_fixed_list)
5993 << (isa<ConceptDecl>(Template) ? 1 : 0)
5994 << ArgLoc.getSourceRange();
5996 return true;
5997 }
5998 }
5999 }
6000
6001 // We're now done with this argument.
6002 ++ArgIdx;
6003
6004 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6005 // Directly convert the remaining arguments, because we don't know what
6006 // parameters they'll match up with.
6007
6008 if (!SugaredArgumentPack.empty()) {
6009 // If we were part way through filling in an expanded parameter pack,
6010 // fall back to just producing individual arguments.
6011 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6012 SugaredArgumentPack.begin(),
6013 SugaredArgumentPack.end());
6014 SugaredArgumentPack.clear();
6015
6016 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6017 CanonicalArgumentPack.begin(),
6018 CanonicalArgumentPack.end());
6019 CanonicalArgumentPack.clear();
6020 }
6021
6022 while (ArgIdx < NumArgs) {
6023 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6024 CTAI.SugaredConverted.push_back(Arg);
6025 CTAI.CanonicalConverted.push_back(
6026 Context.getCanonicalTemplateArgument(Arg));
6027 ++ArgIdx;
6028 }
6029
6030 return false;
6031 }
6032
6033 if ((*Param)->isTemplateParameterPack()) {
6034 // The template parameter was a template parameter pack, so take the
6035 // deduced argument and place it on the argument pack. Note that we
6036 // stay on the same template parameter so that we can deduce more
6037 // arguments.
6038 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6039 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6040 } else {
6041 // Move to the next template parameter.
6042 ++Param;
6043 }
6044 continue;
6045 }
6046
6047 // If we're checking a partial template argument list, we're done.
6048 if (PartialTemplateArgs) {
6049 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6050 CTAI.SugaredConverted.push_back(
6051 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6052 CTAI.CanonicalConverted.push_back(
6053 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6054 }
6055 return false;
6056 }
6057
6058 // If we have a template parameter pack with no more corresponding
6059 // arguments, just break out now and we'll fill in the argument pack below.
6060 if ((*Param)->isTemplateParameterPack()) {
6061 assert(!getExpandedPackSize(*Param) &&
6062 "Should have dealt with this already");
6063
6064 // A non-expanded parameter pack before the end of the parameter list
6065 // only occurs for an ill-formed template parameter list, unless we've
6066 // got a partial argument list for a function template, so just bail out.
6067 if (Param + 1 != ParamEnd) {
6068 assert(
6069 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6070 "Concept templates must have parameter packs at the end.");
6071 return true;
6072 }
6073
6074 CTAI.SugaredConverted.push_back(
6075 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6076 SugaredArgumentPack.clear();
6077
6078 CTAI.CanonicalConverted.push_back(
6079 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6080 CanonicalArgumentPack.clear();
6081
6082 ++Param;
6083 continue;
6084 }
6085
6086 // Check whether we have a default argument.
6087 bool HasDefaultArg;
6088
6089 // Retrieve the default template argument from the template
6090 // parameter. For each kind of template parameter, we substitute the
6091 // template arguments provided thus far and any "outer" template arguments
6092 // (when the template parameter was part of a nested template) into
6093 // the default argument.
6095 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6096 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6097
6098 if (Arg.getArgument().isNull()) {
6099 if (!HasDefaultArg) {
6100 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6101 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6102 NewArgs);
6103 if (NonTypeTemplateParmDecl *NTTP =
6104 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6105 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6106 NewArgs);
6107 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6109 NewArgs);
6110 }
6111 return true;
6112 }
6113
6114 // Introduce an instantiation record that describes where we are using
6115 // the default template argument. We're not actually instantiating a
6116 // template here, we just create this object to put a note into the
6117 // context stack.
6118 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6119 CTAI.SugaredConverted,
6120 SourceRange(TemplateLoc, RAngleLoc));
6121 if (Inst.isInvalid())
6122 return true;
6123
6124 SaveAndRestore _1(CTAI.PartialOrdering, false);
6125 SaveAndRestore _2(CTAI.MatchingTTP, false);
6126 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6127 // Check the default template argument.
6128 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6129 CTAI, CTAK_Specified))
6130 return true;
6131
6132 CTAI.SugaredConverted.back().setIsDefaulted(true);
6133 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6134
6135 // Core issue 150 (assumed resolution): if this is a template template
6136 // parameter, keep track of the default template arguments from the
6137 // template definition.
6138 if (isTemplateTemplateParameter)
6139 NewArgs.addArgument(Arg);
6140
6141 // Move to the next template parameter and argument.
6142 ++Param;
6143 ++ArgIdx;
6144 }
6145
6146 // If we're performing a partial argument substitution, allow any trailing
6147 // pack expansions; they might be empty. This can happen even if
6148 // PartialTemplateArgs is false (the list of arguments is complete but
6149 // still dependent).
6150 if (CTAI.MatchingTTP ||
6152 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6153 while (ArgIdx < NumArgs &&
6154 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6155 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6156 CTAI.SugaredConverted.push_back(Arg);
6157 CTAI.CanonicalConverted.push_back(
6158 Context.getCanonicalTemplateArgument(Arg));
6159 }
6160 }
6161
6162 // If we have any leftover arguments, then there were too many arguments.
6163 // Complain and fail.
6164 if (ArgIdx < NumArgs) {
6165 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6166 << /*too many args*/1
6168 << Template
6169 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6171 return true;
6172 }
6173
6174 // No problems found with the new argument list, propagate changes back
6175 // to caller.
6176 if (UpdateArgsWithConversions)
6177 TemplateArgs = std::move(NewArgs);
6178
6179 if (!PartialTemplateArgs) {
6180 // Setup the context/ThisScope for the case where we are needing to
6181 // re-instantiate constraints outside of normal instantiation.
6182 DeclContext *NewContext = Template->getDeclContext();
6183
6184 // If this template is in a template, make sure we extract the templated
6185 // decl.
6186 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6187 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6188 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6189
6190 Qualifiers ThisQuals;
6191 if (const auto *Method =
6192 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6193 ThisQuals = Method->getMethodQualifiers();
6194
6195 ContextRAII Context(*this, NewContext);
6196 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6197
6199 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6200 /*RelativeToPrimary=*/true,
6201 /*Pattern=*/nullptr,
6202 /*ForConceptInstantiation=*/true);
6203 if (!isa<ConceptDecl>(Template) &&
6205 Template, MLTAL,
6206 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6209 return true;
6210 }
6211 }
6212
6213 return false;
6214}
6215
6216namespace {
6217 class UnnamedLocalNoLinkageFinder
6218 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6219 {
6220 Sema &S;
6221 SourceRange SR;
6222
6224
6225 public:
6226 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6227
6228 bool Visit(QualType T) {
6229 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6230 }
6231
6232#define TYPE(Class, Parent) \
6233 bool Visit##Class##Type(const Class##Type *);
6234#define ABSTRACT_TYPE(Class, Parent) \
6235 bool Visit##Class##Type(const Class##Type *) { return false; }
6236#define NON_CANONICAL_TYPE(Class, Parent) \
6237 bool Visit##Class##Type(const Class##Type *) { return false; }
6238#include "clang/AST/TypeNodes.inc"
6239
6240 bool VisitTagDecl(const TagDecl *Tag);
6241 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6242 };
6243} // end anonymous namespace
6244
6245bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6246 return false;
6247}
6248
6249bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6250 return Visit(T->getElementType());
6251}
6252
6253bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6254 return Visit(T->getPointeeType());
6255}
6256
6257bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6258 const BlockPointerType* T) {
6259 return Visit(T->getPointeeType());
6260}
6261
6262bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6263 const LValueReferenceType* T) {
6264 return Visit(T->getPointeeType());
6265}
6266
6267bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6268 const RValueReferenceType* T) {
6269 return Visit(T->getPointeeType());
6270}
6271
6272bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6273 const MemberPointerType *T) {
6274 if (Visit(T->getPointeeType()))
6275 return true;
6276 if (auto *RD = T->getMostRecentCXXRecordDecl())
6277 return VisitTagDecl(RD);
6278 return VisitNestedNameSpecifier(T->getQualifier());
6279}
6280
6281bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6282 const ConstantArrayType* T) {
6283 return Visit(T->getElementType());
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6287 const IncompleteArrayType* T) {
6288 return Visit(T->getElementType());
6289}
6290
6291bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6292 const VariableArrayType* T) {
6293 return Visit(T->getElementType());
6294}
6295
6296bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6297 const DependentSizedArrayType* T) {
6298 return Visit(T->getElementType());
6299}
6300
6301bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6303 return Visit(T->getElementType());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6307 const DependentSizedMatrixType *T) {
6308 return Visit(T->getElementType());
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6313 return Visit(T->getPointeeType());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6317 return Visit(T->getElementType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6321 const DependentVectorType *T) {
6322 return Visit(T->getElementType());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6326 return Visit(T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6330 const ConstantMatrixType *T) {
6331 return Visit(T->getElementType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6335 const FunctionProtoType* T) {
6336 for (const auto &A : T->param_types()) {
6337 if (Visit(A))
6338 return true;
6339 }
6340
6341 return Visit(T->getReturnType());
6342}
6343
6344bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6345 const FunctionNoProtoType* T) {
6346 return Visit(T->getReturnType());
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6350 const UnresolvedUsingType*) {
6351 return false;
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6355 return false;
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6359 return Visit(T->getUnmodifiedType());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6363 return false;
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6367 const PackIndexingType *) {
6368 return false;
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6372 const UnaryTransformType*) {
6373 return false;
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6377 return Visit(T->getDeducedType());
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6381 const DeducedTemplateSpecializationType *T) {
6382 return Visit(T->getDeducedType());
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6386 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6390 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6394 const TemplateTypeParmType*) {
6395 return false;
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6399 const SubstTemplateTypeParmPackType *) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6404 const SubstBuiltinTemplatePackType *) {
6405 return false;
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6409 const TemplateSpecializationType*) {
6410 return false;
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6414 const InjectedClassNameType* T) {
6415 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6419 const DependentNameType* T) {
6420 return VisitNestedNameSpecifier(T->getQualifier());
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6424 const PackExpansionType* T) {
6425 return Visit(T->getPattern());
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6429 return false;
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6433 const ObjCInterfaceType *) {
6434 return false;
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6438 const ObjCObjectPointerType *) {
6439 return false;
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6443 return Visit(T->getValueType());
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6447 return false;
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6451 return false;
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6455 const ArrayParameterType *T) {
6456 return VisitConstantArrayType(T);
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6460 const DependentBitIntType *T) {
6461 return false;
6462}
6463
6464bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6465 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6466 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6467 ? diag::warn_cxx98_compat_template_arg_local_type
6468 : diag::ext_template_arg_local_type)
6469 << S.Context.getCanonicalTagType(Tag) << SR;
6470 return true;
6471 }
6472
6473 if (!Tag->hasNameForLinkage()) {
6474 S.Diag(SR.getBegin(),
6475 S.getLangOpts().CPlusPlus11 ?
6476 diag::warn_cxx98_compat_template_arg_unnamed_type :
6477 diag::ext_template_arg_unnamed_type) << SR;
6478 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6479 return true;
6480 }
6481
6482 return false;
6483}
6484
6485bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6486 NestedNameSpecifier NNS) {
6487 switch (NNS.getKind()) {
6492 return false;
6494 return Visit(QualType(NNS.getAsType(), 0));
6495 }
6496 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6497}
6498
6499bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6500 const HLSLAttributedResourceType *T) {
6501 if (T->hasContainedType() && Visit(T->getContainedType()))
6502 return true;
6503 return Visit(T->getWrappedType());
6504}
6505
6506bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6507 const HLSLInlineSpirvType *T) {
6508 for (auto &Operand : T->getOperands())
6509 if (Operand.isConstant() && Operand.isLiteral())
6510 if (Visit(Operand.getResultType()))
6511 return true;
6512 return false;
6513}
6514
6516 assert(ArgInfo && "invalid TypeSourceInfo");
6517 QualType Arg = ArgInfo->getType();
6518 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6519 QualType CanonArg = Context.getCanonicalType(Arg);
6520
6521 if (CanonArg->isVariablyModifiedType()) {
6522 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6523 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6524 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6525 }
6526
6527 // C++03 [temp.arg.type]p2:
6528 // A local type, a type with no linkage, an unnamed type or a type
6529 // compounded from any of these types shall not be used as a
6530 // template-argument for a template type-parameter.
6531 //
6532 // C++11 allows these, and even in C++03 we allow them as an extension with
6533 // a warning.
6534 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6535 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6536 (void)Finder.Visit(CanonArg);
6537 }
6538
6539 return false;
6540}
6541
6547
6548/// Determine whether the given template argument is a null pointer
6549/// value of the appropriate type.
6552 QualType ParamType, Expr *Arg,
6553 Decl *Entity = nullptr) {
6554 if (Arg->isValueDependent() || Arg->isTypeDependent())
6555 return NPV_NotNullPointer;
6556
6557 // dllimport'd entities aren't constant but are available inside of template
6558 // arguments.
6559 if (Entity && Entity->hasAttr<DLLImportAttr>())
6560 return NPV_NotNullPointer;
6561
6562 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6563 llvm_unreachable(
6564 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6565
6566 if (!S.getLangOpts().CPlusPlus11)
6567 return NPV_NotNullPointer;
6568
6569 // Determine whether we have a constant expression.
6571 if (ArgRV.isInvalid())
6572 return NPV_Error;
6573 Arg = ArgRV.get();
6574
6575 Expr::EvalResult EvalResult;
6577 EvalResult.Diag = &Notes;
6578 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6579 EvalResult.HasSideEffects) {
6580 SourceLocation DiagLoc = Arg->getExprLoc();
6581
6582 // If our only note is the usual "invalid subexpression" note, just point
6583 // the caret at its location rather than producing an essentially
6584 // redundant note.
6585 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6586 diag::note_invalid_subexpr_in_const_expr) {
6587 DiagLoc = Notes[0].first;
6588 Notes.clear();
6589 }
6590
6591 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6592 << Arg->getType() << Arg->getSourceRange();
6593 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6594 S.Diag(Notes[I].first, Notes[I].second);
6595
6597 return NPV_Error;
6598 }
6599
6600 // C++11 [temp.arg.nontype]p1:
6601 // - an address constant expression of type std::nullptr_t
6602 if (Arg->getType()->isNullPtrType())
6603 return NPV_NullPointer;
6604
6605 // - a constant expression that evaluates to a null pointer value (4.10); or
6606 // - a constant expression that evaluates to a null member pointer value
6607 // (4.11); or
6608 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6609 (EvalResult.Val.isMemberPointer() &&
6610 !EvalResult.Val.getMemberPointerDecl())) {
6611 // If our expression has an appropriate type, we've succeeded.
6612 bool ObjCLifetimeConversion;
6613 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6614 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6615 ObjCLifetimeConversion))
6616 return NPV_NullPointer;
6617
6618 // The types didn't match, but we know we got a null pointer; complain,
6619 // then recover as if the types were correct.
6620 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6621 << Arg->getType() << ParamType << Arg->getSourceRange();
6623 return NPV_NullPointer;
6624 }
6625
6626 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6627 // We found a pointer that isn't null, but doesn't refer to an object.
6628 // We could just return NPV_NotNullPointer, but we can print a better
6629 // message with the information we have here.
6630 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6631 << EvalResult.Val.getAsString(S.Context, ParamType);
6633 return NPV_Error;
6634 }
6635
6636 // If we don't have a null pointer value, but we do have a NULL pointer
6637 // constant, suggest a cast to the appropriate type.
6639 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6640 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6641 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6643 ")");
6645 return NPV_NullPointer;
6646 }
6647
6648 // FIXME: If we ever want to support general, address-constant expressions
6649 // as non-type template arguments, we should return the ExprResult here to
6650 // be interpreted by the caller.
6651 return NPV_NotNullPointer;
6652}
6653
6654/// Checks whether the given template argument is compatible with its
6655/// template parameter.
6656static bool
6658 QualType ParamType, Expr *ArgIn,
6659 Expr *Arg, QualType ArgType) {
6660 bool ObjCLifetimeConversion;
6661 if (ParamType->isPointerType() &&
6662 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6663 S.IsQualificationConversion(ArgType, ParamType, false,
6664 ObjCLifetimeConversion)) {
6665 // For pointer-to-object types, qualification conversions are
6666 // permitted.
6667 } else {
6668 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6669 if (!ParamRef->getPointeeType()->isFunctionType()) {
6670 // C++ [temp.arg.nontype]p5b3:
6671 // For a non-type template-parameter of type reference to
6672 // object, no conversions apply. The type referred to by the
6673 // reference may be more cv-qualified than the (otherwise
6674 // identical) type of the template- argument. The
6675 // template-parameter is bound directly to the
6676 // template-argument, which shall be an lvalue.
6677
6678 // FIXME: Other qualifiers?
6679 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6680 unsigned ArgQuals = ArgType.getCVRQualifiers();
6681
6682 if ((ParamQuals | ArgQuals) != ParamQuals) {
6683 S.Diag(Arg->getBeginLoc(),
6684 diag::err_template_arg_ref_bind_ignores_quals)
6685 << ParamType << Arg->getType() << Arg->getSourceRange();
6687 return true;
6688 }
6689 }
6690 }
6691
6692 // At this point, the template argument refers to an object or
6693 // function with external linkage. We now need to check whether the
6694 // argument and parameter types are compatible.
6695 if (!S.Context.hasSameUnqualifiedType(ArgType,
6696 ParamType.getNonReferenceType())) {
6697 // We can't perform this conversion or binding.
6698 if (ParamType->isReferenceType())
6699 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6700 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6701 else
6702 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6703 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6705 return true;
6706 }
6707 }
6708
6709 return false;
6710}
6711
6712/// Checks whether the given template argument is the address
6713/// of an object or function according to C++ [temp.arg.nontype]p1.
6715 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6716 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6717 bool Invalid = false;
6718 Expr *Arg = ArgIn;
6719 QualType ArgType = Arg->getType();
6720
6721 bool AddressTaken = false;
6722 SourceLocation AddrOpLoc;
6723 if (S.getLangOpts().MicrosoftExt) {
6724 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6725 // dereference and address-of operators.
6726 Arg = Arg->IgnoreParenCasts();
6727
6728 bool ExtWarnMSTemplateArg = false;
6729 UnaryOperatorKind FirstOpKind;
6730 SourceLocation FirstOpLoc;
6731 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6732 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6733 if (UnOpKind == UO_Deref)
6734 ExtWarnMSTemplateArg = true;
6735 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6736 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6737 if (!AddrOpLoc.isValid()) {
6738 FirstOpKind = UnOpKind;
6739 FirstOpLoc = UnOp->getOperatorLoc();
6740 }
6741 } else
6742 break;
6743 }
6744 if (FirstOpLoc.isValid()) {
6745 if (ExtWarnMSTemplateArg)
6746 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6747 << ArgIn->getSourceRange();
6748
6749 if (FirstOpKind == UO_AddrOf)
6750 AddressTaken = true;
6751 else if (Arg->getType()->isPointerType()) {
6752 // We cannot let pointers get dereferenced here, that is obviously not a
6753 // constant expression.
6754 assert(FirstOpKind == UO_Deref);
6755 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6756 << Arg->getSourceRange();
6757 }
6758 }
6759 } else {
6760 // See through any implicit casts we added to fix the type.
6761 Arg = Arg->IgnoreImpCasts();
6762
6763 // C++ [temp.arg.nontype]p1:
6764 //
6765 // A template-argument for a non-type, non-template
6766 // template-parameter shall be one of: [...]
6767 //
6768 // -- the address of an object or function with external
6769 // linkage, including function templates and function
6770 // template-ids but excluding non-static class members,
6771 // expressed as & id-expression where the & is optional if
6772 // the name refers to a function or array, or if the
6773 // corresponding template-parameter is a reference; or
6774
6775 // In C++98/03 mode, give an extension warning on any extra parentheses.
6776 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6777 bool ExtraParens = false;
6778 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6779 if (!Invalid && !ExtraParens) {
6780 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6781 << Arg->getSourceRange();
6782 ExtraParens = true;
6783 }
6784
6785 Arg = Parens->getSubExpr();
6786 }
6787
6788 while (SubstNonTypeTemplateParmExpr *subst =
6789 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6790 Arg = subst->getReplacement()->IgnoreImpCasts();
6791
6792 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6793 if (UnOp->getOpcode() == UO_AddrOf) {
6794 Arg = UnOp->getSubExpr();
6795 AddressTaken = true;
6796 AddrOpLoc = UnOp->getOperatorLoc();
6797 }
6798 }
6799
6800 while (SubstNonTypeTemplateParmExpr *subst =
6801 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6802 Arg = subst->getReplacement()->IgnoreImpCasts();
6803 }
6804
6805 ValueDecl *Entity = nullptr;
6806 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6807 Entity = DRE->getDecl();
6808 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6809 Entity = CUE->getGuidDecl();
6810
6811 // If our parameter has pointer type, check for a null template value.
6812 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6813 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6814 Entity)) {
6815 case NPV_NullPointer:
6816 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6817 SugaredConverted = TemplateArgument(ParamType,
6818 /*isNullPtr=*/true);
6819 CanonicalConverted =
6821 /*isNullPtr=*/true);
6822 return false;
6823
6824 case NPV_Error:
6825 return true;
6826
6827 case NPV_NotNullPointer:
6828 break;
6829 }
6830 }
6831
6832 // Stop checking the precise nature of the argument if it is value dependent,
6833 // it should be checked when instantiated.
6834 if (Arg->isValueDependent()) {
6835 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6836 CanonicalConverted =
6837 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6838 return false;
6839 }
6840
6841 if (!Entity) {
6842 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6843 << Arg->getSourceRange();
6845 return true;
6846 }
6847
6848 // Cannot refer to non-static data members
6849 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6850 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6851 << Entity << Arg->getSourceRange();
6853 return true;
6854 }
6855
6856 // Cannot refer to non-static member functions
6857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6858 if (!Method->isStatic()) {
6859 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6860 << Method << Arg->getSourceRange();
6862 return true;
6863 }
6864 }
6865
6866 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6867 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6868 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6869
6870 // A non-type template argument must refer to an object or function.
6871 if (!Func && !Var && !Guid) {
6872 // We found something, but we don't know specifically what it is.
6873 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6874 << Arg->getSourceRange();
6875 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6876 return true;
6877 }
6878
6879 // Address / reference template args must have external linkage in C++98.
6880 if (Entity->getFormalLinkage() == Linkage::Internal) {
6881 S.Diag(Arg->getBeginLoc(),
6882 S.getLangOpts().CPlusPlus11
6883 ? diag::warn_cxx98_compat_template_arg_object_internal
6884 : diag::ext_template_arg_object_internal)
6885 << !Func << Entity << Arg->getSourceRange();
6886 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6887 << !Func;
6888 } else if (!Entity->hasLinkage()) {
6889 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6890 << !Func << Entity << Arg->getSourceRange();
6891 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6892 << !Func;
6893 return true;
6894 }
6895
6896 if (Var) {
6897 // A value of reference type is not an object.
6898 if (Var->getType()->isReferenceType()) {
6899 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6900 << Var->getType() << Arg->getSourceRange();
6902 return true;
6903 }
6904
6905 // A template argument must have static storage duration.
6906 if (Var->getTLSKind()) {
6907 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6908 << Arg->getSourceRange();
6909 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6910 return true;
6911 }
6912 }
6913
6914 if (AddressTaken && ParamType->isReferenceType()) {
6915 // If we originally had an address-of operator, but the
6916 // parameter has reference type, complain and (if things look
6917 // like they will work) drop the address-of operator.
6918 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6919 ParamType.getNonReferenceType())) {
6920 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6921 << ParamType;
6923 return true;
6924 }
6925
6926 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6927 << ParamType
6928 << FixItHint::CreateRemoval(AddrOpLoc);
6930
6931 ArgType = Entity->getType();
6932 }
6933
6934 // If the template parameter has pointer type, either we must have taken the
6935 // address or the argument must decay to a pointer.
6936 if (!AddressTaken && ParamType->isPointerType()) {
6937 if (Func) {
6938 // Function-to-pointer decay.
6939 ArgType = S.Context.getPointerType(Func->getType());
6940 } else if (Entity->getType()->isArrayType()) {
6941 // Array-to-pointer decay.
6942 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6943 } else {
6944 // If the template parameter has pointer type but the address of
6945 // this object was not taken, complain and (possibly) recover by
6946 // taking the address of the entity.
6947 ArgType = S.Context.getPointerType(Entity->getType());
6948 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6949 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6950 << ParamType;
6952 return true;
6953 }
6954
6955 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6956 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6957
6959 }
6960 }
6961
6962 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6963 Arg, ArgType))
6964 return true;
6965
6966 // Create the template argument.
6967 SugaredConverted = TemplateArgument(Entity, ParamType);
6968 CanonicalConverted =
6970 S.Context.getCanonicalType(ParamType));
6971 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6972 return false;
6973}
6974
6975/// Checks whether the given template argument is a pointer to
6976/// member constant according to C++ [temp.arg.nontype]p1.
6978 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6979 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6980 bool Invalid = false;
6981
6982 Expr *Arg = ResultArg;
6983 bool ObjCLifetimeConversion;
6984
6985 // C++ [temp.arg.nontype]p1:
6986 //
6987 // A template-argument for a non-type, non-template
6988 // template-parameter shall be one of: [...]
6989 //
6990 // -- a pointer to member expressed as described in 5.3.1.
6991 DeclRefExpr *DRE = nullptr;
6992
6993 // In C++98/03 mode, give an extension warning on any extra parentheses.
6994 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6995 bool ExtraParens = false;
6996 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6997 if (!Invalid && !ExtraParens) {
6998 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6999 << Arg->getSourceRange();
7000 ExtraParens = true;
7001 }
7002
7003 Arg = Parens->getSubExpr();
7004 }
7005
7006 while (SubstNonTypeTemplateParmExpr *subst =
7007 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7008 Arg = subst->getReplacement()->IgnoreImpCasts();
7009
7010 // A pointer-to-member constant written &Class::member.
7011 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7012 if (UnOp->getOpcode() == UO_AddrOf) {
7013 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7014 if (DRE && !DRE->getQualifier())
7015 DRE = nullptr;
7016 }
7017 }
7018 // A constant of pointer-to-member type.
7019 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7020 ValueDecl *VD = DRE->getDecl();
7021 if (VD->getType()->isMemberPointerType()) {
7023 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7024 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7025 CanonicalConverted =
7026 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7027 } else {
7028 SugaredConverted = TemplateArgument(VD, ParamType);
7029 CanonicalConverted =
7031 S.Context.getCanonicalType(ParamType));
7032 }
7033 return Invalid;
7034 }
7035 }
7036
7037 DRE = nullptr;
7038 }
7039
7040 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7041
7042 // Check for a null pointer value.
7043 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7044 Entity)) {
7045 case NPV_Error:
7046 return true;
7047 case NPV_NullPointer:
7048 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7049 SugaredConverted = TemplateArgument(ParamType,
7050 /*isNullPtr*/ true);
7051 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7052 /*isNullPtr*/ true);
7053 return false;
7054 case NPV_NotNullPointer:
7055 break;
7056 }
7057
7058 if (S.IsQualificationConversion(ResultArg->getType(),
7059 ParamType.getNonReferenceType(), false,
7060 ObjCLifetimeConversion)) {
7061 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7062 ResultArg->getValueKind())
7063 .get();
7064 } else if (!S.Context.hasSameUnqualifiedType(
7065 ResultArg->getType(), ParamType.getNonReferenceType())) {
7066 // We can't perform this conversion.
7067 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7068 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7070 return true;
7071 }
7072
7073 if (!DRE)
7074 return S.Diag(Arg->getBeginLoc(),
7075 diag::err_template_arg_not_pointer_to_member_form)
7076 << Arg->getSourceRange();
7077
7078 if (isa<FieldDecl>(DRE->getDecl()) ||
7080 isa<CXXMethodDecl>(DRE->getDecl())) {
7081 assert((isa<FieldDecl>(DRE->getDecl()) ||
7084 ->isImplicitObjectMemberFunction()) &&
7085 "Only non-static member pointers can make it here");
7086
7087 // Okay: this is the address of a non-static member, and therefore
7088 // a member pointer constant.
7089 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7090 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7091 CanonicalConverted =
7092 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7093 } else {
7094 ValueDecl *D = DRE->getDecl();
7095 SugaredConverted = TemplateArgument(D, ParamType);
7096 CanonicalConverted =
7098 S.Context.getCanonicalType(ParamType));
7099 }
7100 return Invalid;
7101 }
7102
7103 // We found something else, but we don't know specifically what it is.
7104 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7105 << Arg->getSourceRange();
7106 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7107 return true;
7108}
7109
7110/// Check a template argument against its corresponding
7111/// non-type template parameter.
7112///
7113/// This routine implements the semantics of C++ [temp.arg.nontype].
7114/// If an error occurred, it returns ExprError(); otherwise, it
7115/// returns the converted template argument. \p ParamType is the
7116/// type of the non-type template parameter after it has been instantiated.
7118 Expr *Arg,
7119 TemplateArgument &SugaredConverted,
7120 TemplateArgument &CanonicalConverted,
7121 bool StrictCheck,
7123 SourceLocation StartLoc = Arg->getBeginLoc();
7124 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7125 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7126 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7127 DeductionArg = NewDeductionArg;
7128 if (ArgPE) {
7129 // Recreate a pack expansion if we unwrapped one.
7130 Arg = new (Context) PackExpansionExpr(
7131 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7132 } else {
7133 Arg = DeductionArg;
7134 }
7135 };
7136
7137 // If the parameter type somehow involves auto, deduce the type now.
7138 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7139 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7140 if (IsDeduced) {
7141 // When checking a deduced template argument, deduce from its type even if
7142 // the type is dependent, in order to check the types of non-type template
7143 // arguments line up properly in partial ordering.
7144 TypeSourceInfo *TSI =
7145 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7147 InitializedEntity Entity =
7150 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7151 Expr *Inits[1] = {DeductionArg};
7152 ParamType =
7153 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7154 if (ParamType.isNull())
7155 return ExprError();
7156 } else {
7157 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7158 Param->getTemplateDepth() + 1);
7159 ParamType = QualType();
7161 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7162 /*DependentDeduction=*/true,
7163 // We do not check constraints right now because the
7164 // immediately-declared constraint of the auto type is
7165 // also an associated constraint, and will be checked
7166 // along with the other associated constraints after
7167 // checking the template argument list.
7168 /*IgnoreConstraints=*/true);
7170 ParamType = TSI->getType();
7171 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7173 return ExprError();
7174 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7175 Diag(Arg->getExprLoc(),
7176 diag::err_non_type_template_parm_type_deduction_failure)
7177 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7178 << Arg->getSourceRange();
7180 return ExprError();
7181 }
7182 ParamType = SubstAutoTypeDependent(ParamType);
7183 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7184 }
7185 }
7186 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7187 // an error. The error message normally references the parameter
7188 // declaration, but here we'll pass the argument location because that's
7189 // where the parameter type is deduced.
7190 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7191 if (ParamType.isNull()) {
7193 return ExprError();
7194 }
7195 }
7196
7197 // We should have already dropped all cv-qualifiers by now.
7198 assert(!ParamType.hasQualifiers() &&
7199 "non-type template parameter type cannot be qualified");
7200
7201 // If either the parameter has a dependent type or the argument is
7202 // type-dependent, there's nothing we can check now.
7203 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7204 // Force the argument to the type of the parameter to maintain invariants.
7205 if (!IsDeduced) {
7207 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7208 ParamType->isLValueReferenceType() ? VK_LValue
7209 : ParamType->isRValueReferenceType() ? VK_XValue
7210 : VK_PRValue);
7211 if (E.isInvalid())
7212 return ExprError();
7213 setDeductionArg(E.get());
7214 }
7215 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7216 CanonicalConverted = TemplateArgument(
7217 Context.getCanonicalTemplateArgument(SugaredConverted));
7218 return Arg;
7219 }
7220
7221 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7222 if (CTAK == CTAK_Deduced && !StrictCheck &&
7223 (ParamType->isReferenceType()
7224 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7225 DeductionArg->getType())
7226 : !Context.hasSameUnqualifiedType(ParamType,
7227 DeductionArg->getType()))) {
7228 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7229 // we should actually be checking the type of the template argument in P,
7230 // not the type of the template argument deduced from A, against the
7231 // template parameter type.
7232 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7233 << Arg->getType() << ParamType.getUnqualifiedType();
7235 return ExprError();
7236 }
7237
7238 // If the argument is a pack expansion, we don't know how many times it would
7239 // expand. If we continue checking the argument, this will make the template
7240 // definition ill-formed if it would be ill-formed for any number of
7241 // expansions during instantiation time. When partial ordering or matching
7242 // template template parameters, this is exactly what we want. Otherwise, the
7243 // normal template rules apply: we accept the template if it would be valid
7244 // for any number of expansions (i.e. none).
7245 if (ArgPE && !StrictCheck) {
7246 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7247 CanonicalConverted = TemplateArgument(
7248 Context.getCanonicalTemplateArgument(SugaredConverted));
7249 return Arg;
7250 }
7251
7252 // Avoid making a copy when initializing a template parameter of class type
7253 // from a template parameter object of the same type. This is going beyond
7254 // the standard, but is required for soundness: in
7255 // template<A a> struct X { X *p; X<a> *q; };
7256 // ... we need p and q to have the same type.
7257 //
7258 // Similarly, don't inject a call to a copy constructor when initializing
7259 // from a template parameter of the same type.
7260 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7261 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7262 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7263 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7264 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7265
7266 SugaredConverted = TemplateArgument(TPO, ParamType);
7267 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7268 ParamType.getCanonicalType());
7269 return Arg;
7270 }
7272 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7273 CanonicalConverted =
7274 Context.getCanonicalTemplateArgument(SugaredConverted);
7275 return Arg;
7276 }
7277 }
7278
7279 // The initialization of the parameter from the argument is
7280 // a constant-evaluated context.
7283
7284 bool IsConvertedConstantExpression = true;
7285 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7287 StartLoc, /*DirectInit=*/false, DeductionArg);
7288 Expr *Inits[1] = {DeductionArg};
7289 InitializedEntity Entity =
7291 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7292 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7293 if (Result.isInvalid() || !Result.get())
7294 return ExprError();
7296 if (Result.isInvalid() || !Result.get())
7297 return ExprError();
7298 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7299 /*DiscardedValue=*/false,
7300 /*IsConstexpr=*/true,
7301 /*IsTemplateArgument=*/true)
7302 .get());
7303 IsConvertedConstantExpression = false;
7304 }
7305
7306 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7307 // C++17 [temp.arg.nontype]p1:
7308 // A template-argument for a non-type template parameter shall be
7309 // a converted constant expression of the type of the template-parameter.
7310 APValue Value;
7311 ExprResult ArgResult;
7312 if (IsConvertedConstantExpression) {
7314 DeductionArg, ParamType,
7315 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7316 assert(!ArgResult.isUnset());
7317 if (ArgResult.isInvalid()) {
7319 return ExprError();
7320 }
7321 } else {
7322 ArgResult = DeductionArg;
7323 }
7324
7325 // For a value-dependent argument, CheckConvertedConstantExpression is
7326 // permitted (and expected) to be unable to determine a value.
7327 if (ArgResult.get()->isValueDependent()) {
7328 setDeductionArg(ArgResult.get());
7329 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7330 CanonicalConverted =
7331 Context.getCanonicalTemplateArgument(SugaredConverted);
7332 return Arg;
7333 }
7334
7335 APValue PreNarrowingValue;
7337 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7338 false, PreNarrowingValue);
7339 if (ArgResult.isInvalid())
7340 return ExprError();
7341 setDeductionArg(ArgResult.get());
7342
7343 if (Value.isLValue()) {
7344 APValue::LValueBase Base = Value.getLValueBase();
7345 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7346 // For a non-type template-parameter of pointer or reference type,
7347 // the value of the constant expression shall not refer to
7348 assert(ParamType->isPointerOrReferenceType() ||
7349 ParamType->isNullPtrType());
7350 // -- a temporary object
7351 // -- a string literal
7352 // -- the result of a typeid expression, or
7353 // -- a predefined __func__ variable
7354 if (Base &&
7355 (!VD ||
7357 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7358 << Arg->getSourceRange();
7359 return ExprError();
7360 }
7361
7362 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7363 VD->getType()->isArrayType() &&
7364 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7365 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7366 if (ArgPE) {
7367 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7368 CanonicalConverted =
7369 Context.getCanonicalTemplateArgument(SugaredConverted);
7370 } else {
7371 SugaredConverted = TemplateArgument(VD, ParamType);
7372 CanonicalConverted =
7374 ParamType.getCanonicalType());
7375 }
7376 return Arg;
7377 }
7378
7379 // -- a subobject [until C++20]
7380 if (!getLangOpts().CPlusPlus20) {
7381 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7382 Value.isLValueOnePastTheEnd()) {
7383 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7384 << Value.getAsString(Context, ParamType);
7385 return ExprError();
7386 }
7387 assert((VD || !ParamType->isReferenceType()) &&
7388 "null reference should not be a constant expression");
7389 assert((!VD || !ParamType->isNullPtrType()) &&
7390 "non-null value of type nullptr_t?");
7391 }
7392 }
7393
7394 if (Value.isAddrLabelDiff())
7395 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7396
7397 if (ArgPE) {
7398 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7399 CanonicalConverted =
7400 Context.getCanonicalTemplateArgument(SugaredConverted);
7401 } else {
7402 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7403 CanonicalConverted =
7405 }
7406 return Arg;
7407 }
7408
7409 // These should have all been handled above using the C++17 rules.
7410 assert(!ArgPE && !StrictCheck);
7411
7412 // C++ [temp.arg.nontype]p5:
7413 // The following conversions are performed on each expression used
7414 // as a non-type template-argument. If a non-type
7415 // template-argument cannot be converted to the type of the
7416 // corresponding template-parameter then the program is
7417 // ill-formed.
7418 if (ParamType->isIntegralOrEnumerationType()) {
7419 // C++11:
7420 // -- for a non-type template-parameter of integral or
7421 // enumeration type, conversions permitted in a converted
7422 // constant expression are applied.
7423 //
7424 // C++98:
7425 // -- for a non-type template-parameter of integral or
7426 // enumeration type, integral promotions (4.5) and integral
7427 // conversions (4.7) are applied.
7428
7429 if (getLangOpts().CPlusPlus11) {
7430 // C++ [temp.arg.nontype]p1:
7431 // A template-argument for a non-type, non-template template-parameter
7432 // shall be one of:
7433 //
7434 // -- for a non-type template-parameter of integral or enumeration
7435 // type, a converted constant expression of the type of the
7436 // template-parameter; or
7437 llvm::APSInt Value;
7439 Arg, ParamType, Value, CCEKind::TemplateArg);
7440 if (ArgResult.isInvalid())
7441 return ExprError();
7442 Arg = ArgResult.get();
7443
7444 // We can't check arbitrary value-dependent arguments.
7445 if (Arg->isValueDependent()) {
7446 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7447 CanonicalConverted =
7448 Context.getCanonicalTemplateArgument(SugaredConverted);
7449 return Arg;
7450 }
7451
7452 // Widen the argument value to sizeof(parameter type). This is almost
7453 // always a no-op, except when the parameter type is bool. In
7454 // that case, this may extend the argument from 1 bit to 8 bits.
7455 QualType IntegerType = ParamType;
7456 if (const auto *ED = IntegerType->getAsEnumDecl())
7457 IntegerType = ED->getIntegerType();
7458 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7459 ? Context.getIntWidth(IntegerType)
7460 : Context.getTypeSize(IntegerType));
7461
7462 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7463 CanonicalConverted =
7464 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7465 return Arg;
7466 }
7467
7468 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7469 if (ArgResult.isInvalid())
7470 return ExprError();
7471 Arg = ArgResult.get();
7472
7473 QualType ArgType = Arg->getType();
7474
7475 // C++ [temp.arg.nontype]p1:
7476 // A template-argument for a non-type, non-template
7477 // template-parameter shall be one of:
7478 //
7479 // -- an integral constant-expression of integral or enumeration
7480 // type; or
7481 // -- the name of a non-type template-parameter; or
7482 llvm::APSInt Value;
7483 if (!ArgType->isIntegralOrEnumerationType()) {
7484 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7485 << ArgType << Arg->getSourceRange();
7487 return ExprError();
7488 }
7489 if (!Arg->isValueDependent()) {
7490 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7491 QualType T;
7492
7493 public:
7494 TmplArgICEDiagnoser(QualType T) : T(T) { }
7495
7496 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7497 SourceLocation Loc) override {
7498 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7499 }
7500 } Diagnoser(ArgType);
7501
7502 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7503 if (!Arg)
7504 return ExprError();
7505 }
7506
7507 // From here on out, all we care about is the unqualified form
7508 // of the argument type.
7509 ArgType = ArgType.getUnqualifiedType();
7510
7511 // Try to convert the argument to the parameter's type.
7512 if (Context.hasSameType(ParamType, ArgType)) {
7513 // Okay: no conversion necessary
7514 } else if (ParamType->isBooleanType()) {
7515 // This is an integral-to-boolean conversion.
7516 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7517 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7518 !ParamType->isEnumeralType()) {
7519 // This is an integral promotion or conversion.
7520 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7521 } else {
7522 // We can't perform this conversion.
7523 Diag(StartLoc, diag::err_template_arg_not_convertible)
7524 << Arg->getType() << ParamType << Arg->getSourceRange();
7526 return ExprError();
7527 }
7528
7529 // Add the value of this argument to the list of converted
7530 // arguments. We use the bitwidth and signedness of the template
7531 // parameter.
7532 if (Arg->isValueDependent()) {
7533 // The argument is value-dependent. Create a new
7534 // TemplateArgument with the converted expression.
7535 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7536 CanonicalConverted =
7537 Context.getCanonicalTemplateArgument(SugaredConverted);
7538 return Arg;
7539 }
7540
7541 QualType IntegerType = ParamType;
7542 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7543 IntegerType = ED->getIntegerType();
7544 }
7545
7546 if (ParamType->isBooleanType()) {
7547 // Value must be zero or one.
7548 Value = Value != 0;
7549 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7550 if (Value.getBitWidth() != AllowedBits)
7551 Value = Value.extOrTrunc(AllowedBits);
7552 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7553 } else {
7554 llvm::APSInt OldValue = Value;
7555
7556 // Coerce the template argument's value to the value it will have
7557 // based on the template parameter's type.
7558 unsigned AllowedBits = IntegerType->isBitIntType()
7559 ? Context.getIntWidth(IntegerType)
7560 : Context.getTypeSize(IntegerType);
7561 if (Value.getBitWidth() != AllowedBits)
7562 Value = Value.extOrTrunc(AllowedBits);
7563 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7564
7565 // Complain if an unsigned parameter received a negative value.
7566 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7567 (OldValue.isSigned() && OldValue.isNegative())) {
7568 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7569 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7570 << Arg->getSourceRange();
7572 }
7573
7574 // Complain if we overflowed the template parameter's type.
7575 unsigned RequiredBits;
7576 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7577 RequiredBits = OldValue.getActiveBits();
7578 else if (OldValue.isUnsigned())
7579 RequiredBits = OldValue.getActiveBits() + 1;
7580 else
7581 RequiredBits = OldValue.getSignificantBits();
7582 if (RequiredBits > AllowedBits) {
7583 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7584 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7585 << Arg->getSourceRange();
7587 }
7588 }
7589
7590 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7591 SugaredConverted = TemplateArgument(Context, Value, T);
7592 CanonicalConverted =
7593 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7594 return Arg;
7595 }
7596
7597 QualType ArgType = Arg->getType();
7598 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7599
7600 // Handle pointer-to-function, reference-to-function, and
7601 // pointer-to-member-function all in (roughly) the same way.
7602 if (// -- For a non-type template-parameter of type pointer to
7603 // function, only the function-to-pointer conversion (4.3) is
7604 // applied. If the template-argument represents a set of
7605 // overloaded functions (or a pointer to such), the matching
7606 // function is selected from the set (13.4).
7607 (ParamType->isPointerType() &&
7608 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7609 // -- For a non-type template-parameter of type reference to
7610 // function, no conversions apply. If the template-argument
7611 // represents a set of overloaded functions, the matching
7612 // function is selected from the set (13.4).
7613 (ParamType->isReferenceType() &&
7614 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7615 // -- For a non-type template-parameter of type pointer to
7616 // member function, no conversions apply. If the
7617 // template-argument represents a set of overloaded member
7618 // functions, the matching member function is selected from
7619 // the set (13.4).
7620 (ParamType->isMemberPointerType() &&
7621 ParamType->castAs<MemberPointerType>()->getPointeeType()
7622 ->isFunctionType())) {
7623
7624 if (Arg->getType() == Context.OverloadTy) {
7625 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7626 true,
7627 FoundResult)) {
7628 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7629 return ExprError();
7630
7631 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7632 if (Res.isInvalid())
7633 return ExprError();
7634 Arg = Res.get();
7635 ArgType = Arg->getType();
7636 } else
7637 return ExprError();
7638 }
7639
7640 if (!ParamType->isMemberPointerType()) {
7642 *this, Param, ParamType, Arg, SugaredConverted,
7643 CanonicalConverted))
7644 return ExprError();
7645 return Arg;
7646 }
7647
7649 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7650 return ExprError();
7651 return Arg;
7652 }
7653
7654 if (ParamType->isPointerType()) {
7655 // -- for a non-type template-parameter of type pointer to
7656 // object, qualification conversions (4.4) and the
7657 // array-to-pointer conversion (4.2) are applied.
7658 // C++0x also allows a value of std::nullptr_t.
7659 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7660 "Only object pointers allowed here");
7661
7663 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7664 return ExprError();
7665 return Arg;
7666 }
7667
7668 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7669 // -- For a non-type template-parameter of type reference to
7670 // object, no conversions apply. The type referred to by the
7671 // reference may be more cv-qualified than the (otherwise
7672 // identical) type of the template-argument. The
7673 // template-parameter is bound directly to the
7674 // template-argument, which must be an lvalue.
7675 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7676 "Only object references allowed here");
7677
7678 if (Arg->getType() == Context.OverloadTy) {
7680 ParamRefType->getPointeeType(),
7681 true,
7682 FoundResult)) {
7683 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7684 return ExprError();
7685 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7686 if (Res.isInvalid())
7687 return ExprError();
7688 Arg = Res.get();
7689 ArgType = Arg->getType();
7690 } else
7691 return ExprError();
7692 }
7693
7695 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7696 return ExprError();
7697 return Arg;
7698 }
7699
7700 // Deal with parameters of type std::nullptr_t.
7701 if (ParamType->isNullPtrType()) {
7702 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7703 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7704 CanonicalConverted =
7705 Context.getCanonicalTemplateArgument(SugaredConverted);
7706 return Arg;
7707 }
7708
7709 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7710 case NPV_NotNullPointer:
7711 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7712 << Arg->getType() << ParamType;
7714 return ExprError();
7715
7716 case NPV_Error:
7717 return ExprError();
7718
7719 case NPV_NullPointer:
7720 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7721 SugaredConverted = TemplateArgument(ParamType,
7722 /*isNullPtr=*/true);
7723 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7724 /*isNullPtr=*/true);
7725 return Arg;
7726 }
7727 }
7728
7729 // -- For a non-type template-parameter of type pointer to data
7730 // member, qualification conversions (4.4) are applied.
7731 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7732
7734 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7735 return ExprError();
7736 return Arg;
7737}
7738
7742
7745 const TemplateArgumentLoc &Arg) {
7746 // C++0x [temp.arg.template]p1:
7747 // A template-argument for a template template-parameter shall be
7748 // the name of a class template or an alias template, expressed as an
7749 // id-expression. When the template-argument names a class template, only
7750 // primary class templates are considered when matching the
7751 // template template argument with the corresponding parameter;
7752 // partial specializations are not considered even if their
7753 // parameter lists match that of the template template parameter.
7754 //
7755
7757 unsigned DiagFoundKind = 0;
7758
7759 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7760 switch (TTP->templateParameterKind()) {
7762 DiagFoundKind = 3;
7763 break;
7765 DiagFoundKind = 2;
7766 break;
7767 default:
7768 DiagFoundKind = 1;
7769 break;
7770 }
7771 Kind = TTP->templateParameterKind();
7772 } else if (isa<ConceptDecl>(Template)) {
7774 DiagFoundKind = 3;
7775 } else if (isa<FunctionTemplateDecl>(Template)) {
7777 DiagFoundKind = 0;
7778 } else if (isa<VarTemplateDecl>(Template)) {
7780 DiagFoundKind = 2;
7781 } else if (isa<ClassTemplateDecl>(Template) ||
7785 DiagFoundKind = 1;
7786 } else {
7787 assert(false && "Unexpected Decl");
7788 }
7789
7790 if (Kind == Param->templateParameterKind()) {
7791 return true;
7792 }
7793
7794 unsigned DiagKind = 0;
7795 switch (Param->templateParameterKind()) {
7797 DiagKind = 2;
7798 break;
7800 DiagKind = 1;
7801 break;
7802 default:
7803 DiagKind = 0;
7804 break;
7805 }
7806 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7807 << DiagKind;
7808 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7809 << DiagFoundKind << Template;
7810 return false;
7811}
7812
7813/// Check a template argument against its corresponding
7814/// template template parameter.
7815///
7816/// This routine implements the semantics of C++ [temp.arg.template].
7817/// It returns true if an error occurred, and false otherwise.
7819 TemplateParameterList *Params,
7821 bool PartialOrdering,
7822 bool *StrictPackMatch) {
7824 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7825 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7826 if (!Template) {
7827 // FIXME: Handle AssumedTemplateNames
7828 // Any dependent template name is fine.
7829 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7830 return false;
7831 }
7832
7833 if (Template->isInvalidDecl())
7834 return true;
7835
7837 return true;
7838 }
7839
7840 // C++1z [temp.arg.template]p3: (DR 150)
7841 // A template-argument matches a template template-parameter P when P
7842 // is at least as specialized as the template-argument A.
7844 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7845 PartialOrdering, StrictPackMatch))
7846 return true;
7847 // P2113
7848 // C++20[temp.func.order]p2
7849 // [...] If both deductions succeed, the partial ordering selects the
7850 // more constrained template (if one exists) as determined below.
7851 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7852 Params->getAssociatedConstraints(ParamsAC);
7853 // C++20[temp.arg.template]p3
7854 // [...] In this comparison, if P is unconstrained, the constraints on A
7855 // are not considered.
7856 if (ParamsAC.empty())
7857 return false;
7858
7859 Template->getAssociatedConstraints(TemplateAC);
7860
7861 bool IsParamAtLeastAsConstrained;
7862 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7863 IsParamAtLeastAsConstrained))
7864 return true;
7865 if (!IsParamAtLeastAsConstrained) {
7866 Diag(Arg.getLocation(),
7867 diag::err_template_template_parameter_not_at_least_as_constrained)
7868 << Template << Param << Arg.getSourceRange();
7869 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7870 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7872 TemplateAC);
7873 return true;
7874 }
7875 return false;
7876}
7877
7879 unsigned HereDiagID,
7880 unsigned ExternalDiagID) {
7881 if (Decl.getLocation().isValid())
7882 return S.Diag(Decl.getLocation(), HereDiagID);
7883
7884 SmallString<128> Str;
7885 llvm::raw_svector_ostream Out(Str);
7887 PP.TerseOutput = 1;
7888 Decl.print(Out, PP);
7889 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7890}
7891
7893 std::optional<SourceRange> ParamRange) {
7895 noteLocation(*this, Decl, diag::note_template_decl_here,
7896 diag::note_template_decl_external);
7897 if (ParamRange && ParamRange->isValid()) {
7898 assert(Decl.getLocation().isValid() &&
7899 "Parameter range has location when Decl does not");
7900 DB << *ParamRange;
7901 }
7902}
7903
7905 noteLocation(*this, Decl, diag::note_template_param_here,
7906 diag::note_template_param_external);
7907}
7908
7909/// Given a non-type template argument that refers to a
7910/// declaration and the type of its corresponding non-type template
7911/// parameter, produce an expression that properly refers to that
7912/// declaration.
7914 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7916 // C++ [temp.param]p8:
7917 //
7918 // A non-type template-parameter of type "array of T" or
7919 // "function returning T" is adjusted to be of type "pointer to
7920 // T" or "pointer to function returning T", respectively.
7921 if (ParamType->isArrayType())
7922 ParamType = Context.getArrayDecayedType(ParamType);
7923 else if (ParamType->isFunctionType())
7924 ParamType = Context.getPointerType(ParamType);
7925
7926 // For a NULL non-type template argument, return nullptr casted to the
7927 // parameter's type.
7928 if (Arg.getKind() == TemplateArgument::NullPtr) {
7929 return ImpCastExprToType(
7930 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7931 ParamType,
7932 ParamType->getAs<MemberPointerType>()
7933 ? CK_NullToMemberPointer
7934 : CK_NullToPointer);
7935 }
7936 assert(Arg.getKind() == TemplateArgument::Declaration &&
7937 "Only declaration template arguments permitted here");
7938
7939 ValueDecl *VD = Arg.getAsDecl();
7940
7941 CXXScopeSpec SS;
7942 if (ParamType->isMemberPointerType()) {
7943 // If this is a pointer to member, we need to use a qualified name to
7944 // form a suitable pointer-to-member constant.
7945 assert(VD->getDeclContext()->isRecord() &&
7946 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7948 CanQualType ClassType =
7949 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7950 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7951 SS.MakeTrivial(Context, Qualifier, Loc);
7952 }
7953
7955 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7956 if (RefExpr.isInvalid())
7957 return ExprError();
7958
7959 // For a pointer, the argument declaration is the pointee. Take its address.
7960 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7961 if (ParamType->isPointerType() && !ElemT.isNull() &&
7962 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7963 // Decay an array argument if we want a pointer to its first element.
7964 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7965 if (RefExpr.isInvalid())
7966 return ExprError();
7967 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7968 // For any other pointer, take the address (or form a pointer-to-member).
7969 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7970 if (RefExpr.isInvalid())
7971 return ExprError();
7972 } else if (ParamType->isRecordType()) {
7973 assert(isa<TemplateParamObjectDecl>(VD) &&
7974 "arg for class template param not a template parameter object");
7975 // No conversions apply in this case.
7976 return RefExpr;
7977 } else {
7978 assert(ParamType->isReferenceType() &&
7979 "unexpected type for decl template argument");
7980 if (NonTypeTemplateParmDecl *NTTP =
7981 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7982 QualType TemplateParamType = NTTP->getType();
7983 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7984 if (AT && AT->isDecltypeAuto()) {
7986 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7987 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7988 /*PackIndex=*/std::nullopt,
7989 /*RefParam=*/true, /*Final=*/true);
7990 }
7991 }
7992 }
7993
7994 // At this point we should have the right value category.
7995 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7996 "value kind mismatch for non-type template argument");
7997
7998 // The type of the template parameter can differ from the type of the
7999 // argument in various ways; convert it now if necessary.
8000 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8001 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8002 CastKind CK;
8003 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8004 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8005 CK = CK_NoOp;
8006 } else if (ParamType->isVoidPointerType() &&
8007 RefExpr.get()->getType()->isPointerType()) {
8008 CK = CK_BitCast;
8009 } else {
8010 // FIXME: Pointers to members can need conversion derived-to-base or
8011 // base-to-derived conversions. We currently don't retain enough
8012 // information to convert properly (we need to track a cast path or
8013 // subobject number in the template argument).
8014 llvm_unreachable(
8015 "unexpected conversion required for non-type template argument");
8016 }
8017 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8018 RefExpr.get()->getValueKind());
8019 }
8020
8021 return RefExpr;
8022}
8023
8024/// Construct a new expression that refers to the given
8025/// integral template argument with the given source-location
8026/// information.
8027///
8028/// This routine takes care of the mapping from an integral template
8029/// argument (which may have any integral type) to the appropriate
8030/// literal value.
8032 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8033 assert(OrigT->isIntegralOrEnumerationType());
8034
8035 // If this is an enum type that we're instantiating, we need to use an integer
8036 // type the same size as the enumerator. We don't want to build an
8037 // IntegerLiteral with enum type. The integer type of an enum type can be of
8038 // any integral type with C++11 enum classes, make sure we create the right
8039 // type of literal for it.
8040 QualType T = OrigT;
8041 if (const auto *ED = OrigT->getAsEnumDecl())
8042 T = ED->getIntegerType();
8043
8044 Expr *E;
8045 if (T->isAnyCharacterType()) {
8047 if (T->isWideCharType())
8049 else if (T->isChar8Type() && S.getLangOpts().Char8)
8051 else if (T->isChar16Type())
8053 else if (T->isChar32Type())
8055 else
8057
8058 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8059 } else if (T->isBooleanType()) {
8060 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8061 } else {
8062 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8063 }
8064
8065 if (OrigT->isEnumeralType()) {
8066 // FIXME: This is a hack. We need a better way to handle substituted
8067 // non-type template parameters.
8068 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8069 nullptr, S.CurFPFeatureOverrides(),
8070 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8071 Loc, Loc);
8072 }
8073
8074 return E;
8075}
8076
8078 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8079 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8080 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8081 ILE->setType(T);
8082 return ILE;
8083 };
8084
8085 switch (Val.getKind()) {
8087 // This cannot occur in a template argument at all.
8088 case APValue::Array:
8089 case APValue::Struct:
8090 case APValue::Union:
8091 // These can only occur within a template parameter object, which is
8092 // represented as a TemplateArgument::Declaration.
8093 llvm_unreachable("unexpected template argument value");
8094
8095 case APValue::Int:
8097 Loc);
8098
8099 case APValue::Float:
8100 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8101 T, Loc);
8102
8105 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8106 Val.getFixedPoint().getScale());
8107
8108 case APValue::ComplexInt: {
8109 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8111 S, ElemT, Val.getComplexIntReal(), Loc),
8113 S, ElemT, Val.getComplexIntImag(), Loc)});
8114 }
8115
8116 case APValue::ComplexFloat: {
8117 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8118 return MakeInitList(
8120 ElemT, Loc),
8122 ElemT, Loc)});
8123 }
8124
8125 case APValue::Vector: {
8126 QualType ElemT = T->castAs<VectorType>()->getElementType();
8128 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8130 S, ElemT, Val.getVectorElt(I), Loc));
8131 return MakeInitList(Elts);
8132 }
8133
8134 case APValue::None:
8136 llvm_unreachable("Unexpected APValue kind.");
8137 case APValue::LValue:
8139 // There isn't necessarily a valid equivalent source-level syntax for
8140 // these; in particular, a naive lowering might violate access control.
8141 // So for now we lower to a ConstantExpr holding the value, wrapped around
8142 // an OpaqueValueExpr.
8143 // FIXME: We should have a better representation for this.
8145 if (T->isReferenceType()) {
8146 T = T->getPointeeType();
8147 VK = VK_LValue;
8148 }
8149 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8150 return ConstantExpr::Create(S.Context, OVE, Val);
8151 }
8152 llvm_unreachable("Unhandled APValue::ValueKind enum");
8153}
8154
8157 SourceLocation Loc) {
8158 switch (Arg.getKind()) {
8164 llvm_unreachable("not a non-type template argument");
8165
8167 return Arg.getAsExpr();
8168
8172 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8173
8176 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8177
8180 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8181 }
8182 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8183}
8184
8185/// Match two template parameters within template parameter lists.
8187 Sema &S, NamedDecl *New,
8188 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8189 const NamedDecl *OldInstFrom, bool Complain,
8191 // Check the actual kind (type, non-type, template).
8192 if (Old->getKind() != New->getKind()) {
8193 if (Complain) {
8194 unsigned NextDiag = diag::err_template_param_different_kind;
8195 if (TemplateArgLoc.isValid()) {
8196 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8197 NextDiag = diag::note_template_param_different_kind;
8198 }
8199 S.Diag(New->getLocation(), NextDiag)
8200 << (Kind != Sema::TPL_TemplateMatch);
8201 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8202 << (Kind != Sema::TPL_TemplateMatch);
8203 }
8204
8205 return false;
8206 }
8207
8208 // Check that both are parameter packs or neither are parameter packs.
8209 // However, if we are matching a template template argument to a
8210 // template template parameter, the template template parameter can have
8211 // a parameter pack where the template template argument does not.
8212 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8213 if (Complain) {
8214 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8215 if (TemplateArgLoc.isValid()) {
8216 S.Diag(TemplateArgLoc,
8217 diag::err_template_arg_template_params_mismatch);
8218 NextDiag = diag::note_template_parameter_pack_non_pack;
8219 }
8220
8221 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8223 : 2;
8224 S.Diag(New->getLocation(), NextDiag)
8225 << ParamKind << New->isParameterPack();
8226 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8227 << ParamKind << Old->isParameterPack();
8228 }
8229
8230 return false;
8231 }
8232 // For non-type template parameters, check the type of the parameter.
8233 if (NonTypeTemplateParmDecl *OldNTTP =
8234 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8236
8237 // If we are matching a template template argument to a template
8238 // template parameter and one of the non-type template parameter types
8239 // is dependent, then we must wait until template instantiation time
8240 // to actually compare the arguments.
8242 (!OldNTTP->getType()->isDependentType() &&
8243 !NewNTTP->getType()->isDependentType())) {
8244 // C++20 [temp.over.link]p6:
8245 // Two [non-type] template-parameters are equivalent [if] they have
8246 // equivalent types ignoring the use of type-constraints for
8247 // placeholder types
8248 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8249 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8250 if (!S.Context.hasSameType(OldType, NewType)) {
8251 if (Complain) {
8252 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8253 if (TemplateArgLoc.isValid()) {
8254 S.Diag(TemplateArgLoc,
8255 diag::err_template_arg_template_params_mismatch);
8256 NextDiag = diag::note_template_nontype_parm_different_type;
8257 }
8258 S.Diag(NewNTTP->getLocation(), NextDiag)
8259 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8260 S.Diag(OldNTTP->getLocation(),
8261 diag::note_template_nontype_parm_prev_declaration)
8262 << OldNTTP->getType();
8263 }
8264 return false;
8265 }
8266 }
8267 }
8268 // For template template parameters, check the template parameter types.
8269 // The template parameter lists of template template
8270 // parameters must agree.
8271 else if (TemplateTemplateParmDecl *OldTTP =
8272 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8274 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8275 return false;
8277 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8278 OldTTP->getTemplateParameters(), Complain,
8281 : Kind),
8282 TemplateArgLoc))
8283 return false;
8284 }
8285
8289 const Expr *NewC = nullptr, *OldC = nullptr;
8290
8292 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8293 NewC = TC->getImmediatelyDeclaredConstraint();
8294 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8295 OldC = TC->getImmediatelyDeclaredConstraint();
8296 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8297 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8298 ->getPlaceholderTypeConstraint())
8299 NewC = E;
8300 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8301 ->getPlaceholderTypeConstraint())
8302 OldC = E;
8303 } else
8304 llvm_unreachable("unexpected template parameter type");
8305
8306 auto Diagnose = [&] {
8307 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8308 diag::err_template_different_type_constraint);
8309 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8310 diag::note_template_prev_declaration) << /*declaration*/0;
8311 };
8312
8313 if (!NewC != !OldC) {
8314 if (Complain)
8315 Diagnose();
8316 return false;
8317 }
8318
8319 if (NewC) {
8320 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8321 NewC)) {
8322 if (Complain)
8323 Diagnose();
8324 return false;
8325 }
8326 }
8327 }
8328
8329 return true;
8330}
8331
8332/// Diagnose a known arity mismatch when comparing template argument
8333/// lists.
8334static
8339 SourceLocation TemplateArgLoc) {
8340 unsigned NextDiag = diag::err_template_param_list_different_arity;
8341 if (TemplateArgLoc.isValid()) {
8342 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8343 NextDiag = diag::note_template_param_list_different_arity;
8344 }
8345 S.Diag(New->getTemplateLoc(), NextDiag)
8346 << (New->size() > Old->size())
8347 << (Kind != Sema::TPL_TemplateMatch)
8348 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8349 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8350 << (Kind != Sema::TPL_TemplateMatch)
8351 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8352}
8353
8356 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8357 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8358 if (Old->size() != New->size()) {
8359 if (Complain)
8361 TemplateArgLoc);
8362
8363 return false;
8364 }
8365
8366 // C++0x [temp.arg.template]p3:
8367 // A template-argument matches a template template-parameter (call it P)
8368 // when each of the template parameters in the template-parameter-list of
8369 // the template-argument's corresponding class template or alias template
8370 // (call it A) matches the corresponding template parameter in the
8371 // template-parameter-list of P. [...]
8372 TemplateParameterList::iterator NewParm = New->begin();
8373 TemplateParameterList::iterator NewParmEnd = New->end();
8374 for (TemplateParameterList::iterator OldParm = Old->begin(),
8375 OldParmEnd = Old->end();
8376 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8377 if (NewParm == NewParmEnd) {
8378 if (Complain)
8380 TemplateArgLoc);
8381 return false;
8382 }
8383 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8384 OldInstFrom, Complain, Kind,
8385 TemplateArgLoc))
8386 return false;
8387 }
8388
8389 // Make sure we exhausted all of the arguments.
8390 if (NewParm != NewParmEnd) {
8391 if (Complain)
8393 TemplateArgLoc);
8394
8395 return false;
8396 }
8397
8398 if (Kind != TPL_TemplateParamsEquivalent) {
8399 const Expr *NewRC = New->getRequiresClause();
8400 const Expr *OldRC = Old->getRequiresClause();
8401
8402 auto Diagnose = [&] {
8403 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8404 diag::err_template_different_requires_clause);
8405 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8406 diag::note_template_prev_declaration) << /*declaration*/0;
8407 };
8408
8409 if (!NewRC != !OldRC) {
8410 if (Complain)
8411 Diagnose();
8412 return false;
8413 }
8414
8415 if (NewRC) {
8416 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8417 NewRC)) {
8418 if (Complain)
8419 Diagnose();
8420 return false;
8421 }
8422 }
8423 }
8424
8425 return true;
8426}
8427
8428bool
8430 if (!S)
8431 return false;
8432
8433 // Find the nearest enclosing declaration scope.
8434 S = S->getDeclParent();
8435
8436 // C++ [temp.pre]p6: [P2096]
8437 // A template, explicit specialization, or partial specialization shall not
8438 // have C linkage.
8439 DeclContext *Ctx = S->getEntity();
8440 if (Ctx && Ctx->isExternCContext()) {
8441 SourceRange Range =
8442 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8443 ? TemplateParams->getParam(0)->getSourceRange()
8444 : TemplateParams->getSourceRange();
8445 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8446 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8447 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8448 return true;
8449 }
8450 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8451
8452 // C++ [temp]p2:
8453 // A template-declaration can appear only as a namespace scope or
8454 // class scope declaration.
8455 // C++ [temp.expl.spec]p3:
8456 // An explicit specialization may be declared in any scope in which the
8457 // corresponding primary template may be defined.
8458 // C++ [temp.class.spec]p6: [P2096]
8459 // A partial specialization may be declared in any scope in which the
8460 // corresponding primary template may be defined.
8461 if (Ctx) {
8462 if (Ctx->isFileContext())
8463 return false;
8464 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8465 // C++ [temp.mem]p2:
8466 // A local class shall not have member templates.
8467 if (RD->isLocalClass())
8468 return Diag(TemplateParams->getTemplateLoc(),
8469 diag::err_template_inside_local_class)
8470 << TemplateParams->getSourceRange();
8471 else
8472 return false;
8473 }
8474 }
8475
8476 return Diag(TemplateParams->getTemplateLoc(),
8477 diag::err_template_outside_namespace_or_class_scope)
8478 << TemplateParams->getSourceRange();
8479}
8480
8481/// Determine what kind of template specialization the given declaration
8482/// is.
8484 if (!D)
8485 return TSK_Undeclared;
8486
8487 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8488 return Record->getTemplateSpecializationKind();
8489 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8490 return Function->getTemplateSpecializationKind();
8491 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8492 return Var->getTemplateSpecializationKind();
8493
8494 return TSK_Undeclared;
8495}
8496
8497/// Check whether a specialization is well-formed in the current
8498/// context.
8499///
8500/// This routine determines whether a template specialization can be declared
8501/// in the current context (C++ [temp.expl.spec]p2).
8502///
8503/// \param S the semantic analysis object for which this check is being
8504/// performed.
8505///
8506/// \param Specialized the entity being specialized or instantiated, which
8507/// may be a kind of template (class template, function template, etc.) or
8508/// a member of a class template (member function, static data member,
8509/// member class).
8510///
8511/// \param PrevDecl the previous declaration of this entity, if any.
8512///
8513/// \param Loc the location of the explicit specialization or instantiation of
8514/// this entity.
8515///
8516/// \param IsPartialSpecialization whether this is a partial specialization of
8517/// a class template.
8518///
8519/// \returns true if there was an error that we cannot recover from, false
8520/// otherwise.
8522 NamedDecl *Specialized,
8523 NamedDecl *PrevDecl,
8524 SourceLocation Loc,
8526 // Keep these "kind" numbers in sync with the %select statements in the
8527 // various diagnostics emitted by this routine.
8528 int EntityKind = 0;
8529 if (isa<ClassTemplateDecl>(Specialized))
8530 EntityKind = IsPartialSpecialization? 1 : 0;
8531 else if (isa<VarTemplateDecl>(Specialized))
8532 EntityKind = IsPartialSpecialization ? 3 : 2;
8533 else if (isa<FunctionTemplateDecl>(Specialized))
8534 EntityKind = 4;
8535 else if (isa<CXXMethodDecl>(Specialized))
8536 EntityKind = 5;
8537 else if (isa<VarDecl>(Specialized))
8538 EntityKind = 6;
8539 else if (isa<RecordDecl>(Specialized))
8540 EntityKind = 7;
8541 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8542 EntityKind = 8;
8543 else {
8544 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8545 << S.getLangOpts().CPlusPlus11;
8546 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8547 return true;
8548 }
8549
8550 // C++ [temp.expl.spec]p2:
8551 // An explicit specialization may be declared in any scope in which
8552 // the corresponding primary template may be defined.
8554 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8555 << Specialized;
8556 return true;
8557 }
8558
8559 // C++ [temp.class.spec]p6:
8560 // A class template partial specialization may be declared in any
8561 // scope in which the primary template may be defined.
8562 DeclContext *SpecializedContext =
8563 Specialized->getDeclContext()->getRedeclContext();
8565
8566 // Make sure that this redeclaration (or definition) occurs in the same
8567 // scope or an enclosing namespace.
8568 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8569 : DC->Equals(SpecializedContext))) {
8570 if (isa<TranslationUnitDecl>(SpecializedContext))
8571 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8572 << EntityKind << Specialized;
8573 else {
8574 auto *ND = cast<NamedDecl>(SpecializedContext);
8575 int Diag = diag::err_template_spec_redecl_out_of_scope;
8576 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8577 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8578 S.Diag(Loc, Diag) << EntityKind << Specialized
8579 << ND << isa<CXXRecordDecl>(ND);
8580 }
8581
8582 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8583
8584 // Don't allow specializing in the wrong class during error recovery.
8585 // Otherwise, things can go horribly wrong.
8586 if (DC->isRecord())
8587 return true;
8588 }
8589
8590 return false;
8591}
8592
8594 if (!E->isTypeDependent())
8595 return SourceLocation();
8596 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8597 Checker.TraverseStmt(E);
8598 if (Checker.MatchLoc.isInvalid())
8599 return E->getSourceRange();
8600 return Checker.MatchLoc;
8601}
8602
8603static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8604 if (!TL.getType()->isDependentType())
8605 return SourceLocation();
8606 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8607 Checker.TraverseTypeLoc(TL);
8608 if (Checker.MatchLoc.isInvalid())
8609 return TL.getSourceRange();
8610 return Checker.MatchLoc;
8611}
8612
8613/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8614/// that checks non-type template partial specialization arguments.
8616 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8617 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8618 bool HasError = false;
8619 for (unsigned I = 0; I != NumArgs; ++I) {
8620 if (Args[I].getKind() == TemplateArgument::Pack) {
8622 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8623 Args[I].pack_size(), IsDefaultArgument))
8624 return true;
8625
8626 continue;
8627 }
8628
8629 if (Args[I].getKind() != TemplateArgument::Expression)
8630 continue;
8631
8632 Expr *ArgExpr = Args[I].getAsExpr();
8633 if (ArgExpr->containsErrors()) {
8634 HasError = true;
8635 continue;
8636 }
8637
8638 // We can have a pack expansion of any of the bullets below.
8639 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8640 ArgExpr = Expansion->getPattern();
8641
8642 // Strip off any implicit casts we added as part of type checking.
8643 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8644 ArgExpr = ICE->getSubExpr();
8645
8646 // C++ [temp.class.spec]p8:
8647 // A non-type argument is non-specialized if it is the name of a
8648 // non-type parameter. All other non-type arguments are
8649 // specialized.
8650 //
8651 // Below, we check the two conditions that only apply to
8652 // specialized non-type arguments, so skip any non-specialized
8653 // arguments.
8654 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8655 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8656 continue;
8657
8658 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8659 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8660 continue;
8661 }
8662
8663 // C++ [temp.class.spec]p9:
8664 // Within the argument list of a class template partial
8665 // specialization, the following restrictions apply:
8666 // -- A partially specialized non-type argument expression
8667 // shall not involve a template parameter of the partial
8668 // specialization except when the argument expression is a
8669 // simple identifier.
8670 // -- The type of a template parameter corresponding to a
8671 // specialized non-type argument shall not be dependent on a
8672 // parameter of the specialization.
8673 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8674 // We implement a compromise between the original rules and DR1315:
8675 // -- A specialized non-type template argument shall not be
8676 // type-dependent and the corresponding template parameter
8677 // shall have a non-dependent type.
8678 SourceRange ParamUseRange =
8679 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8680 if (ParamUseRange.isValid()) {
8681 if (IsDefaultArgument) {
8682 S.Diag(TemplateNameLoc,
8683 diag::err_dependent_non_type_arg_in_partial_spec);
8684 S.Diag(ParamUseRange.getBegin(),
8685 diag::note_dependent_non_type_default_arg_in_partial_spec)
8686 << ParamUseRange;
8687 } else {
8688 S.Diag(ParamUseRange.getBegin(),
8689 diag::err_dependent_non_type_arg_in_partial_spec)
8690 << ParamUseRange;
8691 }
8692 return true;
8693 }
8694
8695 ParamUseRange = findTemplateParameter(
8696 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8697 if (ParamUseRange.isValid()) {
8698 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8699 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8700 << Param->getType();
8702 return true;
8703 }
8704 }
8705
8706 return HasError;
8707}
8708
8710 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8711 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8712 // We have to be conservative when checking a template in a dependent
8713 // context.
8714 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8715 return false;
8716
8717 TemplateParameterList *TemplateParams =
8718 PrimaryTemplate->getTemplateParameters();
8719 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8721 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8722 if (!Param)
8723 continue;
8724
8725 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8726 Param, &TemplateArgs[I],
8727 1, I >= NumExplicit))
8728 return true;
8729 }
8730
8731 return false;
8732}
8733
8735 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8736 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8738 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8739 assert(TUK != TagUseKind::Reference && "References are not specializations");
8740
8741 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8742 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8743 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8744
8745 // Find the class template we're specializing
8746 TemplateName Name = TemplateId.Template.get();
8748 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8749
8750 if (!ClassTemplate) {
8751 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8752 << (Name.getAsTemplateDecl() &&
8754 return true;
8755 }
8756
8757 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8758 auto Message = DSA->getMessage();
8759 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8760 << ClassTemplate << !Message.empty() << Message;
8761 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8762 }
8763
8764 if (S->isTemplateParamScope())
8765 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8766
8767 DeclContext *DC = ClassTemplate->getDeclContext();
8768
8769 bool isMemberSpecialization = false;
8770 bool isPartialSpecialization = false;
8771
8772 if (SS.isSet()) {
8773 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8774 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8775 TemplateNameLoc, &TemplateId,
8776 /*IsMemberSpecialization=*/false))
8777 return true;
8778 }
8779
8780 // Check the validity of the template headers that introduce this
8781 // template.
8782 // FIXME: We probably shouldn't complain about these headers for
8783 // friend declarations.
8784 bool Invalid = false;
8785 TemplateParameterList *TemplateParams =
8787 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8788 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8789 if (Invalid)
8790 return true;
8791
8792 // Check that we can declare a template specialization here.
8793 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8794 return true;
8795
8796 if (TemplateParams && DC->isDependentContext()) {
8797 ContextRAII SavedContext(*this, DC);
8799 return true;
8800 }
8801
8802 if (TemplateParams && TemplateParams->size() > 0) {
8803 isPartialSpecialization = true;
8804
8805 if (TUK == TagUseKind::Friend) {
8806 Diag(KWLoc, diag::err_partial_specialization_friend)
8807 << SourceRange(LAngleLoc, RAngleLoc);
8808 return true;
8809 }
8810
8811 // C++ [temp.class.spec]p10:
8812 // The template parameter list of a specialization shall not
8813 // contain default template argument values.
8814 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8815 Decl *Param = TemplateParams->getParam(I);
8816 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8817 if (TTP->hasDefaultArgument()) {
8818 Diag(TTP->getDefaultArgumentLoc(),
8819 diag::err_default_arg_in_partial_spec);
8820 TTP->removeDefaultArgument();
8821 }
8822 } else if (NonTypeTemplateParmDecl *NTTP
8823 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8824 if (NTTP->hasDefaultArgument()) {
8825 Diag(NTTP->getDefaultArgumentLoc(),
8826 diag::err_default_arg_in_partial_spec)
8827 << NTTP->getDefaultArgument().getSourceRange();
8828 NTTP->removeDefaultArgument();
8829 }
8830 } else {
8832 if (TTP->hasDefaultArgument()) {
8834 diag::err_default_arg_in_partial_spec)
8836 TTP->removeDefaultArgument();
8837 }
8838 }
8839 }
8840 } else if (TemplateParams) {
8841 if (TUK == TagUseKind::Friend)
8842 Diag(KWLoc, diag::err_template_spec_friend)
8844 SourceRange(TemplateParams->getTemplateLoc(),
8845 TemplateParams->getRAngleLoc()))
8846 << SourceRange(LAngleLoc, RAngleLoc);
8847 } else {
8848 assert(TUK == TagUseKind::Friend &&
8849 "should have a 'template<>' for this decl");
8850 }
8851
8852 // Check that the specialization uses the same tag kind as the
8853 // original template.
8855 assert(Kind != TagTypeKind::Enum &&
8856 "Invalid enum tag in class template spec!");
8857 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8858 TUK == TagUseKind::Definition, KWLoc,
8859 ClassTemplate->getIdentifier())) {
8860 Diag(KWLoc, diag::err_use_with_wrong_tag)
8861 << ClassTemplate
8863 ClassTemplate->getTemplatedDecl()->getKindName());
8864 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8865 diag::note_previous_use);
8866 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8867 }
8868
8869 // Translate the parser's template argument list in our AST format.
8870 TemplateArgumentListInfo TemplateArgs =
8871 makeTemplateArgumentListInfo(*this, TemplateId);
8872
8873 // Check for unexpanded parameter packs in any of the template arguments.
8874 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8875 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8876 isPartialSpecialization
8879 return true;
8880
8881 // Check that the template argument list is well-formed for this
8882 // template.
8884 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8885 /*DefaultArgs=*/{},
8886 /*PartialTemplateArgs=*/false, CTAI,
8887 /*UpdateArgsWithConversions=*/true))
8888 return true;
8889
8890 // Find the class template (partial) specialization declaration that
8891 // corresponds to these arguments.
8892 if (isPartialSpecialization) {
8894 TemplateArgs.size(),
8895 CTAI.CanonicalConverted))
8896 return true;
8897
8898 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8899 // also do it during instantiation.
8900 if (!Name.isDependent() &&
8901 !TemplateSpecializationType::anyDependentTemplateArguments(
8902 TemplateArgs, CTAI.CanonicalConverted)) {
8903 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8904 << ClassTemplate->getDeclName();
8905 isPartialSpecialization = false;
8906 Invalid = true;
8907 }
8908 }
8909
8910 void *InsertPos = nullptr;
8911 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8912
8913 if (isPartialSpecialization)
8914 PrevDecl = ClassTemplate->findPartialSpecialization(
8915 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8916 else
8917 PrevDecl =
8918 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8919
8921
8922 // Check whether we can declare a class template specialization in
8923 // the current scope.
8924 if (TUK != TagUseKind::Friend &&
8926 TemplateNameLoc,
8927 isPartialSpecialization))
8928 return true;
8929
8930 if (!isPartialSpecialization) {
8931 // Create a new class template specialization declaration node for
8932 // this explicit specialization or friend declaration.
8934 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8935 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8936 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8938 if (TemplateParameterLists.size() > 0) {
8939 Specialization->setTemplateParameterListsInfo(Context,
8940 TemplateParameterLists);
8941 }
8942
8943 if (!PrevDecl)
8944 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8945 } else {
8947 Context.getCanonicalTemplateSpecializationType(
8949 TemplateName(ClassTemplate->getCanonicalDecl()),
8950 CTAI.CanonicalConverted));
8951 if (Context.hasSameType(
8952 CanonType,
8953 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8954 (!Context.getLangOpts().CPlusPlus20 ||
8955 !TemplateParams->hasAssociatedConstraints())) {
8956 // C++ [temp.class.spec]p9b3:
8957 //
8958 // -- The argument list of the specialization shall not be identical
8959 // to the implicit argument list of the primary template.
8960 //
8961 // This rule has since been removed, because it's redundant given DR1495,
8962 // but we keep it because it produces better diagnostics and recovery.
8963 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8964 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8965 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8966 return CheckClassTemplate(
8967 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8968 TemplateNameLoc, Attr, TemplateParams, AS_none,
8969 /*ModulePrivateLoc=*/SourceLocation(),
8970 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8971 TemplateParameterLists.data());
8972 }
8973
8974 // Create a new class template partial specialization declaration node.
8976 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8979 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8980 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8981 Partial->setTemplateArgsAsWritten(TemplateArgs);
8982 SetNestedNameSpecifier(*this, Partial, SS);
8983 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8985 Context, TemplateParameterLists.drop_back(1));
8986 }
8987
8988 if (!PrevPartial)
8989 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8990 Specialization = Partial;
8991
8992 // If we are providing an explicit specialization of a member class
8993 // template specialization, make a note of that.
8994 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8995 PrevPartial->setMemberSpecialization();
8996
8998 }
8999
9000 // C++ [temp.expl.spec]p6:
9001 // If a template, a member template or the member of a class template is
9002 // explicitly specialized then that specialization shall be declared
9003 // before the first use of that specialization that would cause an implicit
9004 // instantiation to take place, in every translation unit in which such a
9005 // use occurs; no diagnostic is required.
9006 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9007 bool Okay = false;
9008 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9009 // Is there any previous explicit specialization declaration?
9011 Okay = true;
9012 break;
9013 }
9014 }
9015
9016 if (!Okay) {
9017 SourceRange Range(TemplateNameLoc, RAngleLoc);
9018 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9019 << Context.getCanonicalTagType(Specialization) << Range;
9020
9021 Diag(PrevDecl->getPointOfInstantiation(),
9022 diag::note_instantiation_required_here)
9023 << (PrevDecl->getTemplateSpecializationKind()
9025 return true;
9026 }
9027 }
9028
9029 // If this is not a friend, note that this is an explicit specialization.
9030 if (TUK != TagUseKind::Friend)
9031 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9032
9033 // Check that this isn't a redefinition of this specialization.
9034 if (TUK == TagUseKind::Definition) {
9035 RecordDecl *Def = Specialization->getDefinition();
9036 NamedDecl *Hidden = nullptr;
9037 bool HiddenDefVisible = false;
9038 if (Def && SkipBody &&
9039 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9040 SkipBody->ShouldSkip = true;
9041 SkipBody->Previous = Def;
9042 if (!HiddenDefVisible && Hidden)
9044 } else if (Def) {
9045 SourceRange Range(TemplateNameLoc, RAngleLoc);
9046 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9047 Diag(Def->getLocation(), diag::note_previous_definition);
9048 Specialization->setInvalidDecl();
9049 return true;
9050 }
9051 }
9052
9055
9056 // Add alignment attributes if necessary; these attributes are checked when
9057 // the ASTContext lays out the structure.
9058 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9059 if (LangOpts.HLSL)
9060 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9063 }
9064
9065 if (ModulePrivateLoc.isValid())
9066 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9067 << (isPartialSpecialization? 1 : 0)
9068 << FixItHint::CreateRemoval(ModulePrivateLoc);
9069
9070 // C++ [temp.expl.spec]p9:
9071 // A template explicit specialization is in the scope of the
9072 // namespace in which the template was defined.
9073 //
9074 // We actually implement this paragraph where we set the semantic
9075 // context (in the creation of the ClassTemplateSpecializationDecl),
9076 // but we also maintain the lexical context where the actual
9077 // definition occurs.
9078 Specialization->setLexicalDeclContext(CurContext);
9079
9080 // We may be starting the definition of this specialization.
9081 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9082 Specialization->startDefinition();
9083
9084 if (TUK == TagUseKind::Friend) {
9085 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9086 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9087 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9089 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9090 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9091
9092 // Build the fully-sugared type for this class template
9093 // specialization as the user wrote in the specialization
9094 // itself. This means that we'll pretty-print the type retrieved
9095 // from the specialization's declaration the way that the user
9096 // actually wrote the specialization, rather than formatting the
9097 // name based on the "canonical" representation used to store the
9098 // template arguments in the specialization.
9100 TemplateNameLoc,
9101 WrittenTy,
9102 /*FIXME:*/KWLoc);
9103 Friend->setAccess(AS_public);
9104 CurContext->addDecl(Friend);
9105 } else {
9106 // Add the specialization into its lexical context, so that it can
9107 // be seen when iterating through the list of declarations in that
9108 // context. However, specializations are not found by name lookup.
9109 CurContext->addDecl(Specialization);
9110 }
9111
9112 if (SkipBody && SkipBody->ShouldSkip)
9113 return SkipBody->Previous;
9114
9115 Specialization->setInvalidDecl(Invalid);
9117 return Specialization;
9118}
9119
9121 MultiTemplateParamsArg TemplateParameterLists,
9122 Declarator &D) {
9123 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9124 ActOnDocumentableDecl(NewDecl);
9125 return NewDecl;
9126}
9127
9129 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9130 const IdentifierInfo *Name, SourceLocation NameLoc) {
9131 DeclContext *DC = CurContext;
9132
9133 if (!DC->getRedeclContext()->isFileContext()) {
9134 Diag(NameLoc,
9135 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9136 return nullptr;
9137 }
9138
9139 if (TemplateParameterLists.size() > 1) {
9140 Diag(NameLoc, diag::err_concept_extra_headers);
9141 return nullptr;
9142 }
9143
9144 TemplateParameterList *Params = TemplateParameterLists.front();
9145
9146 if (Params->size() == 0) {
9147 Diag(NameLoc, diag::err_concept_no_parameters);
9148 return nullptr;
9149 }
9150
9151 // Ensure that the parameter pack, if present, is the last parameter in the
9152 // template.
9153 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9154 ParamEnd = Params->end();
9155 ParamIt != ParamEnd; ++ParamIt) {
9156 Decl const *Param = *ParamIt;
9157 if (Param->isParameterPack()) {
9158 if (++ParamIt == ParamEnd)
9159 break;
9160 Diag(Param->getLocation(),
9161 diag::err_template_param_pack_must_be_last_template_parameter);
9162 return nullptr;
9163 }
9164 }
9165
9166 ConceptDecl *NewDecl =
9167 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9168
9169 if (NewDecl->hasAssociatedConstraints()) {
9170 // C++2a [temp.concept]p4:
9171 // A concept shall not have associated constraints.
9172 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9173 NewDecl->setInvalidDecl();
9174 }
9175
9176 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9177 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9179 LookupName(Previous, S);
9180 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9181 /*AllowInlineNamespace*/ false);
9182
9183 // We cannot properly handle redeclarations until we parse the constraint
9184 // expression, so only inject the name if we are sure we are not redeclaring a
9185 // symbol
9186 if (Previous.empty())
9187 PushOnScopeChains(NewDecl, S, true);
9188
9189 return NewDecl;
9190}
9191
9193 bool Found = false;
9195 while (F.hasNext()) {
9196 NamedDecl *D = F.next();
9197 if (D == C) {
9198 F.erase();
9199 Found = true;
9200 break;
9201 }
9202 }
9203 F.done();
9204 return Found;
9205}
9206
9209 Expr *ConstraintExpr,
9210 const ParsedAttributesView &Attrs) {
9211 assert(!C->hasDefinition() && "Concept already defined");
9212 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9213 C->setInvalidDecl();
9214 return nullptr;
9215 }
9216 C->setDefinition(ConstraintExpr);
9217 ProcessDeclAttributeList(S, C, Attrs);
9218
9219 // Check for conflicting previous declaration.
9220 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9221 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9223 LookupName(Previous, S);
9224 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9225 /*AllowInlineNamespace*/ false);
9226 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9227 bool AddToScope = true;
9228 CheckConceptRedefinition(C, Previous, AddToScope);
9229
9231 if (!WasAlreadyAdded && AddToScope)
9232 PushOnScopeChains(C, S);
9233
9234 return C;
9235}
9236
9238 LookupResult &Previous, bool &AddToScope) {
9239 AddToScope = true;
9240
9241 if (Previous.empty())
9242 return;
9243
9244 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9245 if (!OldConcept) {
9246 auto *Old = Previous.getRepresentativeDecl();
9247 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9248 << NewDecl->getDeclName();
9249 notePreviousDefinition(Old, NewDecl->getLocation());
9250 AddToScope = false;
9251 return;
9252 }
9253 // Check if we can merge with a concept declaration.
9254 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9255 if (!IsSame) {
9256 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9257 << NewDecl->getDeclName();
9258 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9259 AddToScope = false;
9260 return;
9261 }
9262 if (hasReachableDefinition(OldConcept) &&
9263 IsRedefinitionInModule(NewDecl, OldConcept)) {
9264 Diag(NewDecl->getLocation(), diag::err_redefinition)
9265 << NewDecl->getDeclName();
9266 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9267 AddToScope = false;
9268 return;
9269 }
9270 if (!Previous.isSingleResult()) {
9271 // FIXME: we should produce an error in case of ambig and failed lookups.
9272 // Other decls (e.g. namespaces) also have this shortcoming.
9273 return;
9274 }
9275 // We unwrap canonical decl late to check for module visibility.
9276 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9277}
9278
9280 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9281 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9282 Diag(Loc, diag::err_recursive_concept) << CE;
9283 Diag(CE->getLocation(), diag::note_declared_at);
9284 return true;
9285 }
9286 // Concept template parameters don't have a definition and can't
9287 // be defined recursively.
9288 return false;
9289}
9290
9291/// \brief Strips various properties off an implicit instantiation
9292/// that has just been explicitly specialized.
9293static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9294 if (MinGW || (isa<FunctionDecl>(D) &&
9295 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9296 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9297
9298 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9299 FD->setInlineSpecified(false);
9300}
9301
9302/// Compute the diagnostic location for an explicit instantiation
9303// declaration or definition.
9305 NamedDecl* D, SourceLocation PointOfInstantiation) {
9306 // Explicit instantiations following a specialization have no effect and
9307 // hence no PointOfInstantiation. In that case, walk decl backwards
9308 // until a valid name loc is found.
9309 SourceLocation PrevDiagLoc = PointOfInstantiation;
9310 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9311 Prev = Prev->getPreviousDecl()) {
9312 PrevDiagLoc = Prev->getLocation();
9313 }
9314 assert(PrevDiagLoc.isValid() &&
9315 "Explicit instantiation without point of instantiation?");
9316 return PrevDiagLoc;
9317}
9318
9319bool
9322 NamedDecl *PrevDecl,
9324 SourceLocation PrevPointOfInstantiation,
9325 bool &HasNoEffect) {
9326 HasNoEffect = false;
9327
9328 switch (NewTSK) {
9329 case TSK_Undeclared:
9331 assert(
9332 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9333 "previous declaration must be implicit!");
9334 return false;
9335
9337 switch (PrevTSK) {
9338 case TSK_Undeclared:
9340 // Okay, we're just specializing something that is either already
9341 // explicitly specialized or has merely been mentioned without any
9342 // instantiation.
9343 return false;
9344
9346 if (PrevPointOfInstantiation.isInvalid()) {
9347 // The declaration itself has not actually been instantiated, so it is
9348 // still okay to specialize it.
9350 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9351 return false;
9352 }
9353 // Fall through
9354 [[fallthrough]];
9355
9358 assert((PrevTSK == TSK_ImplicitInstantiation ||
9359 PrevPointOfInstantiation.isValid()) &&
9360 "Explicit instantiation without point of instantiation?");
9361
9362 // C++ [temp.expl.spec]p6:
9363 // If a template, a member template or the member of a class template
9364 // is explicitly specialized then that specialization shall be declared
9365 // before the first use of that specialization that would cause an
9366 // implicit instantiation to take place, in every translation unit in
9367 // which such a use occurs; no diagnostic is required.
9368 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9369 // Is there any previous explicit specialization declaration?
9371 return false;
9372 }
9373
9374 Diag(NewLoc, diag::err_specialization_after_instantiation)
9375 << PrevDecl;
9376 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9377 << (PrevTSK != TSK_ImplicitInstantiation);
9378
9379 return true;
9380 }
9381 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9382
9384 switch (PrevTSK) {
9386 // This explicit instantiation declaration is redundant (that's okay).
9387 HasNoEffect = true;
9388 return false;
9389
9390 case TSK_Undeclared:
9392 // We're explicitly instantiating something that may have already been
9393 // implicitly instantiated; that's fine.
9394 return false;
9395
9397 // C++0x [temp.explicit]p4:
9398 // For a given set of template parameters, if an explicit instantiation
9399 // of a template appears after a declaration of an explicit
9400 // specialization for that template, the explicit instantiation has no
9401 // effect.
9402 HasNoEffect = true;
9403 return false;
9404
9406 // C++0x [temp.explicit]p10:
9407 // If an entity is the subject of both an explicit instantiation
9408 // declaration and an explicit instantiation definition in the same
9409 // translation unit, the definition shall follow the declaration.
9410 Diag(NewLoc,
9411 diag::err_explicit_instantiation_declaration_after_definition);
9412
9413 // Explicit instantiations following a specialization have no effect and
9414 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9415 // until a valid name loc is found.
9416 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9417 diag::note_explicit_instantiation_definition_here);
9418 HasNoEffect = true;
9419 return false;
9420 }
9421 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9422
9424 switch (PrevTSK) {
9425 case TSK_Undeclared:
9427 // We're explicitly instantiating something that may have already been
9428 // implicitly instantiated; that's fine.
9429 return false;
9430
9432 // C++ DR 259, C++0x [temp.explicit]p4:
9433 // For a given set of template parameters, if an explicit
9434 // instantiation of a template appears after a declaration of
9435 // an explicit specialization for that template, the explicit
9436 // instantiation has no effect.
9437 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9438 << PrevDecl;
9439 Diag(PrevDecl->getLocation(),
9440 diag::note_previous_template_specialization);
9441 HasNoEffect = true;
9442 return false;
9443
9445 // We're explicitly instantiating a definition for something for which we
9446 // were previously asked to suppress instantiations. That's fine.
9447
9448 // C++0x [temp.explicit]p4:
9449 // For a given set of template parameters, if an explicit instantiation
9450 // of a template appears after a declaration of an explicit
9451 // specialization for that template, the explicit instantiation has no
9452 // effect.
9453 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9454 // Is there any previous explicit specialization declaration?
9456 HasNoEffect = true;
9457 break;
9458 }
9459 }
9460
9461 return false;
9462
9464 // C++0x [temp.spec]p5:
9465 // For a given template and a given set of template-arguments,
9466 // - an explicit instantiation definition shall appear at most once
9467 // in a program,
9468
9469 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9470 Diag(NewLoc, (getLangOpts().MSVCCompat)
9471 ? diag::ext_explicit_instantiation_duplicate
9472 : diag::err_explicit_instantiation_duplicate)
9473 << PrevDecl;
9474 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9475 diag::note_previous_explicit_instantiation);
9476 HasNoEffect = true;
9477 return false;
9478 }
9479 }
9480
9481 llvm_unreachable("Missing specialization/instantiation case?");
9482}
9483
9485 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9487 // Remove anything from Previous that isn't a function template in
9488 // the correct context.
9489 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9490 LookupResult::Filter F = Previous.makeFilter();
9491 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9492 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9493 while (F.hasNext()) {
9494 NamedDecl *D = F.next()->getUnderlyingDecl();
9495 if (!isa<FunctionTemplateDecl>(D)) {
9496 F.erase();
9497 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9498 continue;
9499 }
9500
9501 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9503 F.erase();
9504 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9505 continue;
9506 }
9507 }
9508 F.done();
9509
9510 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9511 if (Previous.empty()) {
9512 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9513 << IsFriend;
9514 for (auto &P : DiscardedCandidates)
9515 Diag(P.second->getLocation(),
9516 diag::note_dependent_function_template_spec_discard_reason)
9517 << P.first << IsFriend;
9518 return true;
9519 }
9520
9522 ExplicitTemplateArgs);
9523 return false;
9524}
9525
9527 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9528 LookupResult &Previous, bool QualifiedFriend) {
9529 // The set of function template specializations that could match this
9530 // explicit function template specialization.
9531 UnresolvedSet<8> Candidates;
9532 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9533 /*ForTakingAddress=*/false);
9534
9535 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9536 ConvertedTemplateArgs;
9537
9538 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9539 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9540 I != E; ++I) {
9541 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9542 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9543 // Only consider templates found within the same semantic lookup scope as
9544 // FD.
9545 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9547 continue;
9548
9549 QualType FT = FD->getType();
9550 // C++11 [dcl.constexpr]p8:
9551 // A constexpr specifier for a non-static member function that is not
9552 // a constructor declares that member function to be const.
9553 //
9554 // When matching a constexpr member function template specialization
9555 // against the primary template, we don't yet know whether the
9556 // specialization has an implicit 'const' (because we don't know whether
9557 // it will be a static member function until we know which template it
9558 // specializes). This rule was removed in C++14.
9559 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9560 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9562 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9563 if (OldMD && OldMD->isConst()) {
9564 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9566 EPI.TypeQuals.addConst();
9567 FT = Context.getFunctionType(FPT->getReturnType(),
9568 FPT->getParamTypes(), EPI);
9569 }
9570 }
9571
9573 if (ExplicitTemplateArgs)
9574 Args = *ExplicitTemplateArgs;
9575
9576 // C++ [temp.expl.spec]p11:
9577 // A trailing template-argument can be left unspecified in the
9578 // template-id naming an explicit function template specialization
9579 // provided it can be deduced from the function argument type.
9580 // Perform template argument deduction to determine whether we may be
9581 // specializing this template.
9582 // FIXME: It is somewhat wasteful to build
9583 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9584 FunctionDecl *Specialization = nullptr;
9586 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9587 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9589 // Template argument deduction failed; record why it failed, so
9590 // that we can provide nifty diagnostics.
9591 FailedCandidates.addCandidate().set(
9592 I.getPair(), FunTmpl->getTemplatedDecl(),
9593 MakeDeductionFailureInfo(Context, TDK, Info));
9594 (void)TDK;
9595 continue;
9596 }
9597
9598 // Target attributes are part of the cuda function signature, so
9599 // the deduced template's cuda target must match that of the
9600 // specialization. Given that C++ template deduction does not
9601 // take target attributes into account, we reject candidates
9602 // here that have a different target.
9603 if (LangOpts.CUDA &&
9604 CUDA().IdentifyTarget(Specialization,
9605 /* IgnoreImplicitHDAttr = */ true) !=
9606 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9607 FailedCandidates.addCandidate().set(
9608 I.getPair(), FunTmpl->getTemplatedDecl(),
9611 continue;
9612 }
9613
9614 // Record this candidate.
9615 if (ExplicitTemplateArgs)
9616 ConvertedTemplateArgs[Specialization] = std::move(Args);
9617 Candidates.addDecl(Specialization, I.getAccess());
9618 }
9619 }
9620
9621 // For a qualified friend declaration (with no explicit marker to indicate
9622 // that a template specialization was intended), note all (template and
9623 // non-template) candidates.
9624 if (QualifiedFriend && Candidates.empty()) {
9625 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9626 << FD->getDeclName() << FDLookupContext;
9627 // FIXME: We should form a single candidate list and diagnose all
9628 // candidates at once, to get proper sorting and limiting.
9629 for (auto *OldND : Previous) {
9630 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9631 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9632 }
9633 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9634 return true;
9635 }
9636
9637 // Find the most specialized function template.
9639 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9640 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9641 PDiag(diag::err_function_template_spec_ambiguous)
9642 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9643 PDiag(diag::note_function_template_spec_matched));
9644
9645 if (Result == Candidates.end())
9646 return true;
9647
9648 // Ignore access information; it doesn't figure into redeclaration checking.
9650
9651 if (const auto *PT = Specialization->getPrimaryTemplate();
9652 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9653 auto Message = DSA->getMessage();
9654 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9655 << PT << !Message.empty() << Message;
9656 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9657 }
9658
9659 // C++23 [except.spec]p13:
9660 // An exception specification is considered to be needed when:
9661 // - [...]
9662 // - the exception specification is compared to that of another declaration
9663 // (e.g., an explicit specialization or an overriding virtual function);
9664 // - [...]
9665 //
9666 // The exception specification of a defaulted function is evaluated as
9667 // described above only when needed; similarly, the noexcept-specifier of a
9668 // specialization of a function template or member function of a class
9669 // template is instantiated only when needed.
9670 //
9671 // The standard doesn't specify what the "comparison with another declaration"
9672 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9673 // not state which properties of an explicit specialization must match the
9674 // primary template.
9675 //
9676 // We assume that an explicit specialization must correspond with (per
9677 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9678 // the declaration produced by substitution into the function template.
9679 //
9680 // Since the determination whether two function declarations correspond does
9681 // not consider exception specification, we only need to instantiate it once
9682 // we determine the primary template when comparing types per
9683 // [basic.link]p11.1.
9684 auto *SpecializationFPT =
9685 Specialization->getType()->castAs<FunctionProtoType>();
9686 // If the function has a dependent exception specification, resolve it after
9687 // we have selected the primary template so we can check whether it matches.
9688 if (getLangOpts().CPlusPlus17 &&
9689 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9690 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9691 return true;
9692
9694 = Specialization->getTemplateSpecializationInfo();
9695 assert(SpecInfo && "Function template specialization info missing?");
9696
9697 // Note: do not overwrite location info if previous template
9698 // specialization kind was explicit.
9700 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9701 Specialization->setLocation(FD->getLocation());
9702 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9703 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9704 // function can differ from the template declaration with respect to
9705 // the constexpr specifier.
9706 // FIXME: We need an update record for this AST mutation.
9707 // FIXME: What if there are multiple such prior declarations (for instance,
9708 // from different modules)?
9709 Specialization->setConstexprKind(FD->getConstexprKind());
9710 }
9711
9712 // FIXME: Check if the prior specialization has a point of instantiation.
9713 // If so, we have run afoul of .
9714
9715 // If this is a friend declaration, then we're not really declaring
9716 // an explicit specialization.
9717 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9718
9719 // Check the scope of this explicit specialization.
9720 if (!isFriend &&
9722 Specialization->getPrimaryTemplate(),
9724 false))
9725 return true;
9726
9727 // C++ [temp.expl.spec]p6:
9728 // If a template, a member template or the member of a class template is
9729 // explicitly specialized then that specialization shall be declared
9730 // before the first use of that specialization that would cause an implicit
9731 // instantiation to take place, in every translation unit in which such a
9732 // use occurs; no diagnostic is required.
9733 bool HasNoEffect = false;
9734 if (!isFriend &&
9739 SpecInfo->getPointOfInstantiation(),
9740 HasNoEffect))
9741 return true;
9742
9743 // Mark the prior declaration as an explicit specialization, so that later
9744 // clients know that this is an explicit specialization.
9745 // A dependent friend specialization which has a definition should be treated
9746 // as explicit specialization, despite being invalid.
9747 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9748 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9749 // Since explicit specializations do not inherit '=delete' from their
9750 // primary function template - check if the 'specialization' that was
9751 // implicitly generated (during template argument deduction for partial
9752 // ordering) from the most specialized of all the function templates that
9753 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9754 // first check that it was implicitly generated during template argument
9755 // deduction by making sure it wasn't referenced, and then reset the deleted
9756 // flag to not-deleted, so that we can inherit that information from 'FD'.
9757 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9758 !Specialization->getCanonicalDecl()->isReferenced()) {
9759 // FIXME: This assert will not hold in the presence of modules.
9760 assert(
9761 Specialization->getCanonicalDecl() == Specialization &&
9762 "This must be the only existing declaration of this specialization");
9763 // FIXME: We need an update record for this AST mutation.
9764 Specialization->setDeletedAsWritten(false);
9765 }
9766 // FIXME: We need an update record for this AST mutation.
9769 }
9770
9771 // Turn the given function declaration into a function template
9772 // specialization, with the template arguments from the previous
9773 // specialization.
9774 // Take copies of (semantic and syntactic) template argument lists.
9776 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9777 FD->setFunctionTemplateSpecialization(
9778 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9780 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9781
9782 // A function template specialization inherits the target attributes
9783 // of its template. (We require the attributes explicitly in the
9784 // code to match, but a template may have implicit attributes by
9785 // virtue e.g. of being constexpr, and it passes these implicit
9786 // attributes on to its specializations.)
9787 if (LangOpts.CUDA)
9788 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9789
9790 // The "previous declaration" for this function template specialization is
9791 // the prior function template specialization.
9792 Previous.clear();
9793 Previous.addDecl(Specialization);
9794 return false;
9795}
9796
9797bool
9799 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9800 "Only for non-template members");
9801
9802 // Try to find the member we are instantiating.
9803 NamedDecl *FoundInstantiation = nullptr;
9804 NamedDecl *Instantiation = nullptr;
9805 NamedDecl *InstantiatedFrom = nullptr;
9806 MemberSpecializationInfo *MSInfo = nullptr;
9807
9808 if (Previous.empty()) {
9809 // Nowhere to look anyway.
9810 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9811 UnresolvedSet<8> Candidates;
9812 for (NamedDecl *Candidate : Previous) {
9813 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9814 // Ignore any candidates that aren't member functions.
9815 if (!Method)
9816 continue;
9817
9818 QualType Adjusted = Function->getType();
9819 if (!hasExplicitCallingConv(Adjusted))
9820 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9821 // Ignore any candidates with the wrong type.
9822 // This doesn't handle deduced return types, but both function
9823 // declarations should be undeduced at this point.
9824 // FIXME: The exception specification should probably be ignored when
9825 // comparing the types.
9826 if (!Context.hasSameType(Adjusted, Method->getType()))
9827 continue;
9828
9829 // Ignore any candidates with unsatisfied constraints.
9830 if (ConstraintSatisfaction Satisfaction;
9831 Method->getTrailingRequiresClause() &&
9832 (CheckFunctionConstraints(Method, Satisfaction,
9833 /*UsageLoc=*/Member->getLocation(),
9834 /*ForOverloadResolution=*/true) ||
9835 !Satisfaction.IsSatisfied))
9836 continue;
9837
9838 Candidates.addDecl(Candidate);
9839 }
9840
9841 // If we have no viable candidates left after filtering, we are done.
9842 if (Candidates.empty())
9843 return false;
9844
9845 // Find the function that is more constrained than every other function it
9846 // has been compared to.
9847 UnresolvedSetIterator Best = Candidates.begin();
9848 CXXMethodDecl *BestMethod = nullptr;
9849 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9850 I != E; ++I) {
9851 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9852 if (I == Best ||
9853 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9854 Best = I;
9855 BestMethod = Method;
9856 }
9857 }
9858
9859 FoundInstantiation = *Best;
9860 Instantiation = BestMethod;
9861 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9862 MSInfo = BestMethod->getMemberSpecializationInfo();
9863
9864 // Make sure the best candidate is more constrained than all of the others.
9865 bool Ambiguous = false;
9866 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9867 I != E; ++I) {
9868 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9869 if (I != Best &&
9870 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9871 Ambiguous = true;
9872 break;
9873 }
9874 }
9875
9876 if (Ambiguous) {
9877 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9878 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9879 for (NamedDecl *Candidate : Candidates) {
9880 Candidate = Candidate->getUnderlyingDecl();
9881 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9882 << Candidate;
9883 }
9884 return true;
9885 }
9886 } else if (isa<VarDecl>(Member)) {
9887 VarDecl *PrevVar;
9888 if (Previous.isSingleResult() &&
9889 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9890 if (PrevVar->isStaticDataMember()) {
9891 FoundInstantiation = Previous.getRepresentativeDecl();
9892 Instantiation = PrevVar;
9893 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9894 MSInfo = PrevVar->getMemberSpecializationInfo();
9895 }
9896 } else if (isa<RecordDecl>(Member)) {
9897 CXXRecordDecl *PrevRecord;
9898 if (Previous.isSingleResult() &&
9899 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9900 FoundInstantiation = Previous.getRepresentativeDecl();
9901 Instantiation = PrevRecord;
9902 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9903 MSInfo = PrevRecord->getMemberSpecializationInfo();
9904 }
9905 } else if (isa<EnumDecl>(Member)) {
9906 EnumDecl *PrevEnum;
9907 if (Previous.isSingleResult() &&
9908 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9909 FoundInstantiation = Previous.getRepresentativeDecl();
9910 Instantiation = PrevEnum;
9911 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9912 MSInfo = PrevEnum->getMemberSpecializationInfo();
9913 }
9914 }
9915
9916 if (!Instantiation) {
9917 // There is no previous declaration that matches. Since member
9918 // specializations are always out-of-line, the caller will complain about
9919 // this mismatch later.
9920 return false;
9921 }
9922
9923 // A member specialization in a friend declaration isn't really declaring
9924 // an explicit specialization, just identifying a specific (possibly implicit)
9925 // specialization. Don't change the template specialization kind.
9926 //
9927 // FIXME: Is this really valid? Other compilers reject.
9928 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9929 // Preserve instantiation information.
9930 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9931 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9932 cast<CXXMethodDecl>(InstantiatedFrom),
9934 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9935 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9936 cast<CXXRecordDecl>(InstantiatedFrom),
9938 }
9939
9940 Previous.clear();
9941 Previous.addDecl(FoundInstantiation);
9942 return false;
9943 }
9944
9945 // Make sure that this is a specialization of a member.
9946 if (!InstantiatedFrom) {
9947 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9948 << Member;
9949 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9950 return true;
9951 }
9952
9953 // C++ [temp.expl.spec]p6:
9954 // If a template, a member template or the member of a class template is
9955 // explicitly specialized then that specialization shall be declared
9956 // before the first use of that specialization that would cause an implicit
9957 // instantiation to take place, in every translation unit in which such a
9958 // use occurs; no diagnostic is required.
9959 assert(MSInfo && "Member specialization info missing?");
9960
9961 bool HasNoEffect = false;
9964 Instantiation,
9966 MSInfo->getPointOfInstantiation(),
9967 HasNoEffect))
9968 return true;
9969
9970 // Check the scope of this explicit specialization.
9972 InstantiatedFrom,
9973 Instantiation, Member->getLocation(),
9974 false))
9975 return true;
9976
9977 // Note that this member specialization is an "instantiation of" the
9978 // corresponding member of the original template.
9979 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9980 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9981 if (InstantiationFunction->getTemplateSpecializationKind() ==
9983 // Explicit specializations of member functions of class templates do not
9984 // inherit '=delete' from the member function they are specializing.
9985 if (InstantiationFunction->isDeleted()) {
9986 // FIXME: This assert will not hold in the presence of modules.
9987 assert(InstantiationFunction->getCanonicalDecl() ==
9988 InstantiationFunction);
9989 // FIXME: We need an update record for this AST mutation.
9990 InstantiationFunction->setDeletedAsWritten(false);
9991 }
9992 }
9993
9994 MemberFunction->setInstantiationOfMemberFunction(
9996 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9997 MemberVar->setInstantiationOfStaticDataMember(
9998 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9999 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10000 MemberClass->setInstantiationOfMemberClass(
10002 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10003 MemberEnum->setInstantiationOfMemberEnum(
10004 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10005 } else {
10006 llvm_unreachable("unknown member specialization kind");
10007 }
10008
10009 // Save the caller the trouble of having to figure out which declaration
10010 // this specialization matches.
10011 Previous.clear();
10012 Previous.addDecl(FoundInstantiation);
10013 return false;
10014}
10015
10016/// Complete the explicit specialization of a member of a class template by
10017/// updating the instantiated member to be marked as an explicit specialization.
10018///
10019/// \param OrigD The member declaration instantiated from the template.
10020/// \param Loc The location of the explicit specialization of the member.
10021template<typename DeclT>
10022static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10023 SourceLocation Loc) {
10024 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10025 return;
10026
10027 // FIXME: Inform AST mutation listeners of this AST mutation.
10028 // FIXME: If there are multiple in-class declarations of the member (from
10029 // multiple modules, or a declaration and later definition of a member type),
10030 // should we update all of them?
10031 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10032 OrigD->setLocation(Loc);
10033}
10034
10037 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10038 if (Instantiation == Member)
10039 return;
10040
10041 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10042 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10043 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10044 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10045 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10046 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10047 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10048 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10049 else
10050 llvm_unreachable("unknown member specialization kind");
10051}
10052
10053/// Check the scope of an explicit instantiation.
10054///
10055/// \returns true if a serious error occurs, false otherwise.
10057 SourceLocation InstLoc,
10058 bool WasQualifiedName) {
10060 DeclContext *CurContext = S.CurContext->getRedeclContext();
10061
10062 if (CurContext->isRecord()) {
10063 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10064 << D;
10065 return true;
10066 }
10067
10068 // C++11 [temp.explicit]p3:
10069 // An explicit instantiation shall appear in an enclosing namespace of its
10070 // template. If the name declared in the explicit instantiation is an
10071 // unqualified name, the explicit instantiation shall appear in the
10072 // namespace where its template is declared or, if that namespace is inline
10073 // (7.3.1), any namespace from its enclosing namespace set.
10074 //
10075 // This is DR275, which we do not retroactively apply to C++98/03.
10076 if (WasQualifiedName) {
10077 if (CurContext->Encloses(OrigContext))
10078 return false;
10079 } else {
10080 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10081 return false;
10082 }
10083
10084 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10085 if (WasQualifiedName)
10086 S.Diag(InstLoc,
10087 S.getLangOpts().CPlusPlus11?
10088 diag::err_explicit_instantiation_out_of_scope :
10089 diag::warn_explicit_instantiation_out_of_scope_0x)
10090 << D << NS;
10091 else
10092 S.Diag(InstLoc,
10093 S.getLangOpts().CPlusPlus11?
10094 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10095 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10096 << D << NS;
10097 } else
10098 S.Diag(InstLoc,
10099 S.getLangOpts().CPlusPlus11?
10100 diag::err_explicit_instantiation_must_be_global :
10101 diag::warn_explicit_instantiation_must_be_global_0x)
10102 << D;
10103 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10104 return false;
10105}
10106
10107/// Common checks for whether an explicit instantiation of \p D is valid.
10109 SourceLocation InstLoc,
10110 bool WasQualifiedName,
10112 // C++ [temp.explicit]p13:
10113 // An explicit instantiation declaration shall not name a specialization of
10114 // a template with internal linkage.
10117 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10118 return true;
10119 }
10120
10121 // C++11 [temp.explicit]p3: [DR 275]
10122 // An explicit instantiation shall appear in an enclosing namespace of its
10123 // template.
10124 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10125 return true;
10126
10127 return false;
10128}
10129
10130/// Determine whether the given scope specifier has a template-id in it.
10132 // C++11 [temp.explicit]p3:
10133 // If the explicit instantiation is for a member function, a member class
10134 // or a static data member of a class template specialization, the name of
10135 // the class template specialization in the qualified-id for the member
10136 // name shall be a simple-template-id.
10137 //
10138 // C++98 has the same restriction, just worded differently.
10139 for (NestedNameSpecifier NNS = SS.getScopeRep();
10141 /**/) {
10142 const Type *T = NNS.getAsType();
10144 return true;
10145 NNS = T->getPrefix();
10146 }
10147 return false;
10148}
10149
10150/// Make a dllexport or dllimport attr on a class template specialization take
10151/// effect.
10154 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10155 assert(A && "dllExportImportClassTemplateSpecialization called "
10156 "on Def without dllexport or dllimport");
10157
10158 // We reject explicit instantiations in class scope, so there should
10159 // never be any delayed exported classes to worry about.
10160 assert(S.DelayedDllExportClasses.empty() &&
10161 "delayed exports present at explicit instantiation");
10163
10164 // Propagate attribute to base class templates.
10165 for (auto &B : Def->bases()) {
10166 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10167 B.getType()->getAsCXXRecordDecl()))
10169 }
10170
10172}
10173
10175 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10176 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10177 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10178 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10179 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10180 // Find the class template we're specializing
10181 TemplateName Name = TemplateD.get();
10182 TemplateDecl *TD = Name.getAsTemplateDecl();
10183 // Check that the specialization uses the same tag kind as the
10184 // original template.
10186 assert(Kind != TagTypeKind::Enum &&
10187 "Invalid enum tag in class template explicit instantiation!");
10188
10189 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10190
10191 if (!ClassTemplate) {
10192 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10193 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10194 Diag(TD->getLocation(), diag::note_previous_use);
10195 return true;
10196 }
10197
10198 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10199 Kind, /*isDefinition*/false, KWLoc,
10200 ClassTemplate->getIdentifier())) {
10201 Diag(KWLoc, diag::err_use_with_wrong_tag)
10202 << ClassTemplate
10204 ClassTemplate->getTemplatedDecl()->getKindName());
10205 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10206 diag::note_previous_use);
10207 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10208 }
10209
10210 // C++0x [temp.explicit]p2:
10211 // There are two forms of explicit instantiation: an explicit instantiation
10212 // definition and an explicit instantiation declaration. An explicit
10213 // instantiation declaration begins with the extern keyword. [...]
10214 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10217
10219 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10220 // Check for dllexport class template instantiation declarations,
10221 // except for MinGW mode.
10222 for (const ParsedAttr &AL : Attr) {
10223 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10224 Diag(ExternLoc,
10225 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10226 Diag(AL.getLoc(), diag::note_attribute);
10227 break;
10228 }
10229 }
10230
10231 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10232 Diag(ExternLoc,
10233 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10234 Diag(A->getLocation(), diag::note_attribute);
10235 }
10236 }
10237
10238 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10239 // instantiation declarations for most purposes.
10240 bool DLLImportExplicitInstantiationDef = false;
10242 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10243 // Check for dllimport class template instantiation definitions.
10244 bool DLLImport =
10245 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10246 for (const ParsedAttr &AL : Attr) {
10247 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10248 DLLImport = true;
10249 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10250 // dllexport trumps dllimport here.
10251 DLLImport = false;
10252 break;
10253 }
10254 }
10255 if (DLLImport) {
10257 DLLImportExplicitInstantiationDef = true;
10258 }
10259 }
10260
10261 // Translate the parser's template argument list in our AST format.
10262 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10263 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10264
10265 // Check that the template argument list is well-formed for this
10266 // template.
10268 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10269 /*DefaultArgs=*/{}, false, CTAI,
10270 /*UpdateArgsWithConversions=*/true,
10271 /*ConstraintsNotSatisfied=*/nullptr))
10272 return true;
10273
10274 // Find the class template specialization declaration that
10275 // corresponds to these arguments.
10276 void *InsertPos = nullptr;
10278 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10279
10280 TemplateSpecializationKind PrevDecl_TSK
10281 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10282
10283 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10284 Context.getTargetInfo().getTriple().isOSCygMing()) {
10285 // Check for dllexport class template instantiation definitions in MinGW
10286 // mode, if a previous declaration of the instantiation was seen.
10287 for (const ParsedAttr &AL : Attr) {
10288 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10289 Diag(AL.getLoc(),
10290 diag::warn_attribute_dllexport_explicit_instantiation_def);
10291 break;
10292 }
10293 }
10294 }
10295
10296 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10297 SS.isSet(), TSK))
10298 return true;
10299
10301
10302 bool HasNoEffect = false;
10303 if (PrevDecl) {
10304 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10305 PrevDecl, PrevDecl_TSK,
10306 PrevDecl->getPointOfInstantiation(),
10307 HasNoEffect))
10308 return PrevDecl;
10309
10310 // Even though HasNoEffect == true means that this explicit instantiation
10311 // has no effect on semantics, we go on to put its syntax in the AST.
10312
10313 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10314 PrevDecl_TSK == TSK_Undeclared) {
10315 // Since the only prior class template specialization with these
10316 // arguments was referenced but not declared, reuse that
10317 // declaration node as our own, updating the source location
10318 // for the template name to reflect our new declaration.
10319 // (Other source locations will be updated later.)
10320 Specialization = PrevDecl;
10321 Specialization->setLocation(TemplateNameLoc);
10322 PrevDecl = nullptr;
10323 }
10324
10325 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10326 DLLImportExplicitInstantiationDef) {
10327 // The new specialization might add a dllimport attribute.
10328 HasNoEffect = false;
10329 }
10330 }
10331
10332 if (!Specialization) {
10333 // Create a new class template specialization declaration node for
10334 // this explicit specialization.
10336 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10337 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10339
10340 // A MSInheritanceAttr attached to the previous declaration must be
10341 // propagated to the new node prior to instantiation.
10342 if (PrevDecl) {
10343 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10344 auto *Clone = A->clone(getASTContext());
10345 Clone->setInherited(true);
10346 Specialization->addAttr(Clone);
10347 Consumer.AssignInheritanceModel(Specialization);
10348 }
10349 }
10350
10351 if (!HasNoEffect && !PrevDecl) {
10352 // Insert the new specialization.
10353 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10354 }
10355 }
10356
10357 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10358
10359 // Set source locations for keywords.
10360 Specialization->setExternKeywordLoc(ExternLoc);
10361 Specialization->setTemplateKeywordLoc(TemplateLoc);
10362 Specialization->setBraceRange(SourceRange());
10363
10364 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10367
10368 // Add the explicit instantiation into its lexical context. However,
10369 // since explicit instantiations are never found by name lookup, we
10370 // just put it into the declaration context directly.
10371 Specialization->setLexicalDeclContext(CurContext);
10372 CurContext->addDecl(Specialization);
10373
10374 // Syntax is now OK, so return if it has no other effect on semantics.
10375 if (HasNoEffect) {
10376 // Set the template specialization kind.
10377 Specialization->setTemplateSpecializationKind(TSK);
10378 return Specialization;
10379 }
10380
10381 // C++ [temp.explicit]p3:
10382 // A definition of a class template or class member template
10383 // shall be in scope at the point of the explicit instantiation of
10384 // the class template or class member template.
10385 //
10386 // This check comes when we actually try to perform the
10387 // instantiation.
10389 = cast_or_null<ClassTemplateSpecializationDecl>(
10390 Specialization->getDefinition());
10391 if (!Def)
10393 /*Complain=*/true,
10394 CTAI.StrictPackMatch);
10395 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10396 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10397 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10398 }
10399
10400 // Instantiate the members of this class template specialization.
10401 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10402 Specialization->getDefinition());
10403 if (Def) {
10405 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10406 // TSK_ExplicitInstantiationDefinition
10407 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10409 DLLImportExplicitInstantiationDef)) {
10410 // FIXME: Need to notify the ASTMutationListener that we did this.
10412
10413 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10414 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10415 // An explicit instantiation definition can add a dll attribute to a
10416 // template with a previous instantiation declaration. MinGW doesn't
10417 // allow this.
10418 auto *A = cast<InheritableAttr>(
10420 A->setInherited(true);
10421 Def->addAttr(A);
10423 }
10424 }
10425
10426 // Fix a TSK_ImplicitInstantiation followed by a
10427 // TSK_ExplicitInstantiationDefinition
10428 bool NewlyDLLExported =
10429 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10430 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10431 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10432 // An explicit instantiation definition can add a dll attribute to a
10433 // template with a previous implicit instantiation. MinGW doesn't allow
10434 // this. We limit clang to only adding dllexport, to avoid potentially
10435 // strange codegen behavior. For example, if we extend this conditional
10436 // to dllimport, and we have a source file calling a method on an
10437 // implicitly instantiated template class instance and then declaring a
10438 // dllimport explicit instantiation definition for the same template
10439 // class, the codegen for the method call will not respect the dllimport,
10440 // while it will with cl. The Def will already have the DLL attribute,
10441 // since the Def and Specialization will be the same in the case of
10442 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10443 // attribute to the Specialization; we just need to make it take effect.
10444 assert(Def == Specialization &&
10445 "Def and Specialization should match for implicit instantiation");
10447 }
10448
10449 // In MinGW mode, export the template instantiation if the declaration
10450 // was marked dllexport.
10451 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10452 Context.getTargetInfo().getTriple().isOSCygMing() &&
10453 PrevDecl->hasAttr<DLLExportAttr>()) {
10455 }
10456
10457 // Set the template specialization kind. Make sure it is set before
10458 // instantiating the members which will trigger ASTConsumer callbacks.
10459 Specialization->setTemplateSpecializationKind(TSK);
10460 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10461 } else {
10462
10463 // Set the template specialization kind.
10464 Specialization->setTemplateSpecializationKind(TSK);
10465 }
10466
10467 return Specialization;
10468}
10469
10472 SourceLocation TemplateLoc, unsigned TagSpec,
10473 SourceLocation KWLoc, CXXScopeSpec &SS,
10474 IdentifierInfo *Name, SourceLocation NameLoc,
10475 const ParsedAttributesView &Attr) {
10476
10477 bool Owned = false;
10478 bool IsDependent = false;
10479 Decl *TagD =
10480 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10481 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10482 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10483 false, TypeResult(), /*IsTypeSpecifier*/ false,
10484 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10485 .get();
10486 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10487
10488 if (!TagD)
10489 return true;
10490
10491 TagDecl *Tag = cast<TagDecl>(TagD);
10492 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10493
10494 if (Tag->isInvalidDecl())
10495 return true;
10496
10498 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10499 if (!Pattern) {
10500 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10501 << Context.getCanonicalTagType(Record);
10502 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10503 return true;
10504 }
10505
10506 // C++0x [temp.explicit]p2:
10507 // If the explicit instantiation is for a class or member class, the
10508 // elaborated-type-specifier in the declaration shall include a
10509 // simple-template-id.
10510 //
10511 // C++98 has the same restriction, just worded differently.
10513 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10514 << Record << SS.getRange();
10515
10516 // C++0x [temp.explicit]p2:
10517 // There are two forms of explicit instantiation: an explicit instantiation
10518 // definition and an explicit instantiation declaration. An explicit
10519 // instantiation declaration begins with the extern keyword. [...]
10523
10524 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10525
10526 // Verify that it is okay to explicitly instantiate here.
10527 CXXRecordDecl *PrevDecl
10528 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10529 if (!PrevDecl && Record->getDefinition())
10530 PrevDecl = Record;
10531 if (PrevDecl) {
10533 bool HasNoEffect = false;
10534 assert(MSInfo && "No member specialization information?");
10535 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10536 PrevDecl,
10538 MSInfo->getPointOfInstantiation(),
10539 HasNoEffect))
10540 return true;
10541 if (HasNoEffect)
10542 return TagD;
10543 }
10544
10545 CXXRecordDecl *RecordDef
10546 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10547 if (!RecordDef) {
10548 // C++ [temp.explicit]p3:
10549 // A definition of a member class of a class template shall be in scope
10550 // at the point of an explicit instantiation of the member class.
10551 CXXRecordDecl *Def
10552 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10553 if (!Def) {
10554 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10555 << 0 << Record->getDeclName() << Record->getDeclContext();
10556 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10557 << Pattern;
10558 return true;
10559 } else {
10560 if (InstantiateClass(NameLoc, Record, Def,
10562 TSK))
10563 return true;
10564
10565 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10566 if (!RecordDef)
10567 return true;
10568 }
10569 }
10570
10571 // Instantiate all of the members of the class.
10572 InstantiateClassMembers(NameLoc, RecordDef,
10574
10576 MarkVTableUsed(NameLoc, RecordDef, true);
10577
10578 // FIXME: We don't have any representation for explicit instantiations of
10579 // member classes. Such a representation is not needed for compilation, but it
10580 // should be available for clients that want to see all of the declarations in
10581 // the source code.
10582 return TagD;
10583}
10584
10586 SourceLocation ExternLoc,
10587 SourceLocation TemplateLoc,
10588 Declarator &D) {
10589 // Explicit instantiations always require a name.
10590 // TODO: check if/when DNInfo should replace Name.
10592 DeclarationName Name = NameInfo.getName();
10593 if (!Name) {
10594 if (!D.isInvalidType())
10596 diag::err_explicit_instantiation_requires_name)
10598
10599 return true;
10600 }
10601
10602 // Get the innermost enclosing declaration scope.
10603 S = S->getDeclParent();
10604
10605 // Determine the type of the declaration.
10607 QualType R = T->getType();
10608 if (R.isNull())
10609 return true;
10610
10611 // C++ [dcl.stc]p1:
10612 // A storage-class-specifier shall not be specified in [...] an explicit
10613 // instantiation (14.7.2) directive.
10615 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10616 << Name;
10617 return true;
10618 } else if (D.getDeclSpec().getStorageClassSpec()
10620 // Complain about then remove the storage class specifier.
10621 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10623
10625 }
10626
10627 // C++0x [temp.explicit]p1:
10628 // [...] An explicit instantiation of a function template shall not use the
10629 // inline or constexpr specifiers.
10630 // Presumably, this also applies to member functions of class templates as
10631 // well.
10635 diag::err_explicit_instantiation_inline :
10636 diag::warn_explicit_instantiation_inline_0x)
10639 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10640 // not already specified.
10642 diag::err_explicit_instantiation_constexpr);
10643
10644 // A deduction guide is not on the list of entities that can be explicitly
10645 // instantiated.
10647 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10648 << /*explicit instantiation*/ 0;
10649 return true;
10650 }
10651
10652 // C++0x [temp.explicit]p2:
10653 // There are two forms of explicit instantiation: an explicit instantiation
10654 // definition and an explicit instantiation declaration. An explicit
10655 // instantiation declaration begins with the extern keyword. [...]
10659
10660 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10662 /*ObjectType=*/QualType());
10663
10664 if (!R->isFunctionType()) {
10665 // C++ [temp.explicit]p1:
10666 // A [...] static data member of a class template can be explicitly
10667 // instantiated from the member definition associated with its class
10668 // template.
10669 // C++1y [temp.explicit]p1:
10670 // A [...] variable [...] template specialization can be explicitly
10671 // instantiated from its template.
10672 if (Previous.isAmbiguous())
10673 return true;
10674
10675 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10676 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10677
10678 if (!PrevTemplate) {
10679 if (!Prev || !Prev->isStaticDataMember()) {
10680 // We expect to see a static data member here.
10681 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10682 << Name;
10683 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10684 P != PEnd; ++P)
10685 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10686 return true;
10687 }
10688
10690 // FIXME: Check for explicit specialization?
10692 diag::err_explicit_instantiation_data_member_not_instantiated)
10693 << Prev;
10694 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10695 // FIXME: Can we provide a note showing where this was declared?
10696 return true;
10697 }
10698 } else {
10699 // Explicitly instantiate a variable template.
10700
10701 // C++1y [dcl.spec.auto]p6:
10702 // ... A program that uses auto or decltype(auto) in a context not
10703 // explicitly allowed in this section is ill-formed.
10704 //
10705 // This includes auto-typed variable template instantiations.
10706 if (R->isUndeducedType()) {
10707 Diag(T->getTypeLoc().getBeginLoc(),
10708 diag::err_auto_not_allowed_var_inst);
10709 return true;
10710 }
10711
10713 // C++1y [temp.explicit]p3:
10714 // If the explicit instantiation is for a variable, the unqualified-id
10715 // in the declaration shall be a template-id.
10717 diag::err_explicit_instantiation_without_template_id)
10718 << PrevTemplate;
10719 Diag(PrevTemplate->getLocation(),
10720 diag::note_explicit_instantiation_here);
10721 return true;
10722 }
10723
10724 // Translate the parser's template argument list into our AST format.
10725 TemplateArgumentListInfo TemplateArgs =
10727
10728 DeclResult Res =
10729 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10730 TemplateArgs, /*SetWrittenArgs=*/true);
10731 if (Res.isInvalid())
10732 return true;
10733
10734 if (!Res.isUsable()) {
10735 // We somehow specified dependent template arguments in an explicit
10736 // instantiation. This should probably only happen during error
10737 // recovery.
10738 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10739 return true;
10740 }
10741
10742 // Ignore access control bits, we don't need them for redeclaration
10743 // checking.
10744 Prev = cast<VarDecl>(Res.get());
10745 }
10746
10747 // C++0x [temp.explicit]p2:
10748 // If the explicit instantiation is for a member function, a member class
10749 // or a static data member of a class template specialization, the name of
10750 // the class template specialization in the qualified-id for the member
10751 // name shall be a simple-template-id.
10752 //
10753 // C++98 has the same restriction, just worded differently.
10754 //
10755 // This does not apply to variable template specializations, where the
10756 // template-id is in the unqualified-id instead.
10757 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10759 diag::ext_explicit_instantiation_without_qualified_id)
10760 << Prev << D.getCXXScopeSpec().getRange();
10761
10762 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10763
10764 // Verify that it is okay to explicitly instantiate here.
10767 bool HasNoEffect = false;
10769 PrevTSK, POI, HasNoEffect))
10770 return true;
10771
10772 if (!HasNoEffect) {
10773 // Instantiate static data member or variable template.
10775 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10776 VTSD->setExternKeywordLoc(ExternLoc);
10777 VTSD->setTemplateKeywordLoc(TemplateLoc);
10778 }
10779
10780 // Merge attributes.
10782 if (PrevTemplate)
10783 ProcessAPINotes(Prev);
10784
10787 }
10788
10789 // Check the new variable specialization against the parsed input.
10790 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10791 Diag(T->getTypeLoc().getBeginLoc(),
10792 diag::err_invalid_var_template_spec_type)
10793 << 0 << PrevTemplate << R << Prev->getType();
10794 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10795 << 2 << PrevTemplate->getDeclName();
10796 return true;
10797 }
10798
10799 // FIXME: Create an ExplicitInstantiation node?
10800 return (Decl*) nullptr;
10801 }
10802
10803 // If the declarator is a template-id, translate the parser's template
10804 // argument list into our AST format.
10805 bool HasExplicitTemplateArgs = false;
10806 TemplateArgumentListInfo TemplateArgs;
10808 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10809 HasExplicitTemplateArgs = true;
10810 }
10811
10812 // C++ [temp.explicit]p1:
10813 // A [...] function [...] can be explicitly instantiated from its template.
10814 // A member function [...] of a class template can be explicitly
10815 // instantiated from the member definition associated with its class
10816 // template.
10817 UnresolvedSet<8> TemplateMatches;
10818 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10820 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10821 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10822 P != PEnd; ++P) {
10823 NamedDecl *Prev = *P;
10824 if (!HasExplicitTemplateArgs) {
10825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10826 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10827 /*AdjustExceptionSpec*/true);
10828 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10829 if (Method->getPrimaryTemplate()) {
10830 TemplateMatches.addDecl(Method, P.getAccess());
10831 } else {
10832 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10833 C.FoundDecl = P.getPair();
10834 C.Function = Method;
10835 C.Viable = true;
10837 if (Method->getTrailingRequiresClause() &&
10839 /*ForOverloadResolution=*/true) ||
10840 !S.IsSatisfied)) {
10841 C.Viable = false;
10843 }
10844 }
10845 }
10846 }
10847 }
10848
10849 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10850 if (!FunTmpl)
10851 continue;
10852
10853 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10854 FunctionDecl *Specialization = nullptr;
10856 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10857 Specialization, Info);
10859 // Keep track of almost-matches.
10860 FailedTemplateCandidates.addCandidate().set(
10861 P.getPair(), FunTmpl->getTemplatedDecl(),
10862 MakeDeductionFailureInfo(Context, TDK, Info));
10863 (void)TDK;
10864 continue;
10865 }
10866
10867 // Target attributes are part of the cuda function signature, so
10868 // the cuda target of the instantiated function must match that of its
10869 // template. Given that C++ template deduction does not take
10870 // target attributes into account, we reject candidates here that
10871 // have a different target.
10872 if (LangOpts.CUDA &&
10873 CUDA().IdentifyTarget(Specialization,
10874 /* IgnoreImplicitHDAttr = */ true) !=
10875 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10876 FailedTemplateCandidates.addCandidate().set(
10877 P.getPair(), FunTmpl->getTemplatedDecl(),
10880 continue;
10881 }
10882
10883 TemplateMatches.addDecl(Specialization, P.getAccess());
10884 }
10885
10886 FunctionDecl *Specialization = nullptr;
10887 if (!NonTemplateMatches.empty()) {
10888 unsigned Msg = 0;
10889 OverloadCandidateDisplayKind DisplayKind;
10891 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10892 Best)) {
10893 case OR_Success:
10894 case OR_Deleted:
10895 Specialization = cast<FunctionDecl>(Best->Function);
10896 break;
10897 case OR_Ambiguous:
10898 Msg = diag::err_explicit_instantiation_ambiguous;
10899 DisplayKind = OCD_AmbiguousCandidates;
10900 break;
10902 Msg = diag::err_explicit_instantiation_no_candidate;
10903 DisplayKind = OCD_AllCandidates;
10904 break;
10905 }
10906 if (Msg) {
10907 PartialDiagnostic Diag = PDiag(Msg) << Name;
10908 NonTemplateMatches.NoteCandidates(
10909 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10910 {});
10911 return true;
10912 }
10913 }
10914
10915 if (!Specialization) {
10916 // Find the most specialized function template specialization.
10918 TemplateMatches.begin(), TemplateMatches.end(),
10919 FailedTemplateCandidates, D.getIdentifierLoc(),
10920 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10921 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10922 PDiag(diag::note_explicit_instantiation_candidate));
10923
10924 if (Result == TemplateMatches.end())
10925 return true;
10926
10927 // Ignore access control bits, we don't need them for redeclaration checking.
10929 }
10930
10931 // C++11 [except.spec]p4
10932 // In an explicit instantiation an exception-specification may be specified,
10933 // but is not required.
10934 // If an exception-specification is specified in an explicit instantiation
10935 // directive, it shall be compatible with the exception-specifications of
10936 // other declarations of that function.
10937 if (auto *FPT = R->getAs<FunctionProtoType>())
10938 if (FPT->hasExceptionSpec()) {
10939 unsigned DiagID =
10940 diag::err_mismatched_exception_spec_explicit_instantiation;
10941 if (getLangOpts().MicrosoftExt)
10942 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10944 PDiag(DiagID) << Specialization->getType(),
10945 PDiag(diag::note_explicit_instantiation_here),
10946 Specialization->getType()->getAs<FunctionProtoType>(),
10947 Specialization->getLocation(), FPT, D.getBeginLoc());
10948 // In Microsoft mode, mismatching exception specifications just cause a
10949 // warning.
10950 if (!getLangOpts().MicrosoftExt && Result)
10951 return true;
10952 }
10953
10954 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10956 diag::err_explicit_instantiation_member_function_not_instantiated)
10958 << (Specialization->getTemplateSpecializationKind() ==
10960 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10961 return true;
10962 }
10963
10964 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10965 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10966 PrevDecl = Specialization;
10967
10968 if (PrevDecl) {
10969 bool HasNoEffect = false;
10971 PrevDecl,
10973 PrevDecl->getPointOfInstantiation(),
10974 HasNoEffect))
10975 return true;
10976
10977 // FIXME: We may still want to build some representation of this
10978 // explicit specialization.
10979 if (HasNoEffect)
10980 return (Decl*) nullptr;
10981 }
10982
10983 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10984 // functions
10985 // valarray<size_t>::valarray(size_t) and
10986 // valarray<size_t>::~valarray()
10987 // that it declared to have internal linkage with the internal_linkage
10988 // attribute. Ignore the explicit instantiation declaration in this case.
10989 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10991 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10992 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10993 RD->isInStdNamespace())
10994 return (Decl*) nullptr;
10995 }
10996
10999
11000 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11001 // instantiation declarations.
11003 Specialization->hasAttr<DLLImportAttr>() &&
11004 Context.getTargetInfo().getCXXABI().isMicrosoft())
11006
11007 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11008
11009 if (Specialization->isDefined()) {
11010 // Let the ASTConsumer know that this function has been explicitly
11011 // instantiated now, and its linkage might have changed.
11012 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11013 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11015
11016 // C++0x [temp.explicit]p2:
11017 // If the explicit instantiation is for a member function, a member class
11018 // or a static data member of a class template specialization, the name of
11019 // the class template specialization in the qualified-id for the member
11020 // name shall be a simple-template-id.
11021 //
11022 // C++98 has the same restriction, just worded differently.
11023 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11024 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11025 D.getCXXScopeSpec().isSet() &&
11028 diag::ext_explicit_instantiation_without_qualified_id)
11030
11032 *this,
11033 FunTmpl ? (NamedDecl *)FunTmpl
11034 : Specialization->getInstantiatedFromMemberFunction(),
11035 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11036
11037 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11038 return (Decl*) nullptr;
11039}
11040
11042 const CXXScopeSpec &SS,
11043 const IdentifierInfo *Name,
11044 SourceLocation TagLoc,
11045 SourceLocation NameLoc) {
11046 // This has to hold, because SS is expected to be defined.
11047 assert(Name && "Expected a name in a dependent tag");
11048
11050 if (!NNS)
11051 return true;
11052
11054
11055 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11056 Diag(NameLoc, diag::err_dependent_tag_decl)
11057 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11058 return true;
11059 }
11060
11061 // Create the resulting type.
11063 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11064
11065 // Create type-source location information for this type.
11066 TypeLocBuilder TLB;
11068 TL.setElaboratedKeywordLoc(TagLoc);
11070 TL.setNameLoc(NameLoc);
11072}
11073
11075 const CXXScopeSpec &SS,
11076 const IdentifierInfo &II,
11077 SourceLocation IdLoc,
11078 ImplicitTypenameContext IsImplicitTypename) {
11079 if (SS.isInvalid())
11080 return true;
11081
11082 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11083 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11084 << FixItHint::CreateRemoval(TypenameLoc);
11085
11087 TypeSourceInfo *TSI = nullptr;
11088 QualType T =
11091 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11092 /*DeducedTSTContext=*/true);
11093 if (T.isNull())
11094 return true;
11095 return CreateParsedType(T, TSI);
11096}
11097
11100 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11101 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11102 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11103 ASTTemplateArgsPtr TemplateArgsIn,
11104 SourceLocation RAngleLoc) {
11105 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11106 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11107 ? diag::compat_cxx11_typename_outside_of_template
11108 : diag::compat_pre_cxx11_typename_outside_of_template)
11109 << FixItHint::CreateRemoval(TypenameLoc);
11110
11111 // Strangely, non-type results are not ignored by this lookup, so the
11112 // program is ill-formed if it finds an injected-class-name.
11113 if (TypenameLoc.isValid()) {
11114 auto *LookupRD =
11115 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11116 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11117 Diag(TemplateIILoc,
11118 diag::ext_out_of_line_qualified_id_type_names_constructor)
11119 << TemplateII << 0 /*injected-class-name used as template name*/
11120 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11121 }
11122 }
11123
11124 // Translate the parser's template argument list in our AST format.
11125 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11126 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11127
11131 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11132 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11133 if (T.isNull())
11134 return true;
11135
11136 // Provide source-location information for the template specialization type.
11137 TypeLocBuilder Builder;
11139 = Builder.push<TemplateSpecializationTypeLoc>(T);
11140 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11141 TemplateIILoc, TemplateArgs);
11142 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11143 return CreateParsedType(T, TSI);
11144}
11145
11146/// Determine whether this failed name lookup should be treated as being
11147/// disabled by a usage of std::enable_if.
11149 SourceRange &CondRange, Expr *&Cond) {
11150 // We must be looking for a ::type...
11151 if (!II.isStr("type"))
11152 return false;
11153
11154 // ... within an explicitly-written template specialization...
11156 return false;
11157
11158 // FIXME: Look through sugar.
11159 auto EnableIfTSTLoc =
11161 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11162 return false;
11163 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11164
11165 // ... which names a complete class template declaration...
11166 const TemplateDecl *EnableIfDecl =
11167 EnableIfTST->getTemplateName().getAsTemplateDecl();
11168 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11169 return false;
11170
11171 // ... called "enable_if".
11172 const IdentifierInfo *EnableIfII =
11173 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11174 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11175 return false;
11176
11177 // Assume the first template argument is the condition.
11178 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11179
11180 // Dig out the condition.
11181 Cond = nullptr;
11182 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11184 return true;
11185
11186 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11187
11188 // Ignore Boolean literals; they add no value.
11189 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11190 Cond = nullptr;
11191
11192 return true;
11193}
11194
11197 SourceLocation KeywordLoc,
11198 NestedNameSpecifierLoc QualifierLoc,
11199 const IdentifierInfo &II,
11200 SourceLocation IILoc,
11201 TypeSourceInfo **TSI,
11202 bool DeducedTSTContext) {
11203 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11204 DeducedTSTContext);
11205 if (T.isNull())
11206 return QualType();
11207
11208 TypeLocBuilder TLB;
11210 auto TL = TLB.push<DependentNameTypeLoc>(T);
11211 TL.setElaboratedKeywordLoc(KeywordLoc);
11212 TL.setQualifierLoc(QualifierLoc);
11213 TL.setNameLoc(IILoc);
11216 TL.setElaboratedKeywordLoc(KeywordLoc);
11217 TL.setQualifierLoc(QualifierLoc);
11218 TL.setNameLoc(IILoc);
11219 } else if (isa<TemplateTypeParmType>(T)) {
11220 // FIXME: There might be a 'typename' keyword here, but we just drop it
11221 // as it can't be represented.
11222 assert(!QualifierLoc);
11223 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11224 } else if (isa<TagType>(T)) {
11225 auto TL = TLB.push<TagTypeLoc>(T);
11226 TL.setElaboratedKeywordLoc(KeywordLoc);
11227 TL.setQualifierLoc(QualifierLoc);
11228 TL.setNameLoc(IILoc);
11229 } else if (isa<TypedefType>(T)) {
11230 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11231 } else {
11232 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11233 }
11234 *TSI = TLB.getTypeSourceInfo(Context, T);
11235 return T;
11236}
11237
11238/// Build the type that describes a C++ typename specifier,
11239/// e.g., "typename T::type".
11242 SourceLocation KeywordLoc,
11243 NestedNameSpecifierLoc QualifierLoc,
11244 const IdentifierInfo &II,
11245 SourceLocation IILoc, bool DeducedTSTContext) {
11246 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11247
11248 CXXScopeSpec SS;
11249 SS.Adopt(QualifierLoc);
11250
11251 DeclContext *Ctx = nullptr;
11252 if (QualifierLoc) {
11253 Ctx = computeDeclContext(SS);
11254 if (!Ctx) {
11255 // If the nested-name-specifier is dependent and couldn't be
11256 // resolved to a type, build a typename type.
11257 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11258 return Context.getDependentNameType(Keyword,
11259 QualifierLoc.getNestedNameSpecifier(),
11260 &II);
11261 }
11262
11263 // If the nested-name-specifier refers to the current instantiation,
11264 // the "typename" keyword itself is superfluous. In C++03, the
11265 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11266 // allows such extraneous "typename" keywords, and we retroactively
11267 // apply this DR to C++03 code with only a warning. In any case we continue.
11268
11269 if (RequireCompleteDeclContext(SS, Ctx))
11270 return QualType();
11271 }
11272
11273 DeclarationName Name(&II);
11274 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11275 if (Ctx)
11276 LookupQualifiedName(Result, Ctx, SS);
11277 else
11278 LookupName(Result, CurScope);
11279 unsigned DiagID = 0;
11280 Decl *Referenced = nullptr;
11281 switch (Result.getResultKind()) {
11283 // If we're looking up 'type' within a template named 'enable_if', produce
11284 // a more specific diagnostic.
11285 SourceRange CondRange;
11286 Expr *Cond = nullptr;
11287 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11288 // If we have a condition, narrow it down to the specific failed
11289 // condition.
11290 if (Cond) {
11291 Expr *FailedCond;
11292 std::string FailedDescription;
11293 std::tie(FailedCond, FailedDescription) =
11295
11296 Diag(FailedCond->getExprLoc(),
11297 diag::err_typename_nested_not_found_requirement)
11298 << FailedDescription
11299 << FailedCond->getSourceRange();
11300 return QualType();
11301 }
11302
11303 Diag(CondRange.getBegin(),
11304 diag::err_typename_nested_not_found_enable_if)
11305 << Ctx << CondRange;
11306 return QualType();
11307 }
11308
11309 DiagID = Ctx ? diag::err_typename_nested_not_found
11310 : diag::err_unknown_typename;
11311 break;
11312 }
11313
11315 // We found a using declaration that is a value. Most likely, the using
11316 // declaration itself is meant to have the 'typename' keyword.
11317 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11318 IILoc);
11319 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11320 << Name << Ctx << FullRange;
11321 if (UnresolvedUsingValueDecl *Using
11322 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11323 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11324 Diag(Loc, diag::note_using_value_decl_missing_typename)
11325 << FixItHint::CreateInsertion(Loc, "typename ");
11326 }
11327 }
11328 // Fall through to create a dependent typename type, from which we can
11329 // recover better.
11330 [[fallthrough]];
11331
11333 // Okay, it's a member of an unknown instantiation.
11334 return Context.getDependentNameType(Keyword,
11335 QualifierLoc.getNestedNameSpecifier(),
11336 &II);
11337
11339 // FXIME: Missing support for UsingShadowDecl on this path?
11340 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11341 // C++ [class.qual]p2:
11342 // In a lookup in which function names are not ignored and the
11343 // nested-name-specifier nominates a class C, if the name specified
11344 // after the nested-name-specifier, when looked up in C, is the
11345 // injected-class-name of C [...] then the name is instead considered
11346 // to name the constructor of class C.
11347 //
11348 // Unlike in an elaborated-type-specifier, function names are not ignored
11349 // in typename-specifier lookup. However, they are ignored in all the
11350 // contexts where we form a typename type with no keyword (that is, in
11351 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11352 //
11353 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11354 // ignore functions, but that appears to be an oversight.
11359 Type, IILoc);
11360 // FIXME: This appears to be the only case where a template type parameter
11361 // can have an elaborated keyword. We should preserve it somehow.
11364 assert(!QualifierLoc);
11366 }
11367 return Context.getTypeDeclType(
11368 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11369 }
11370
11371 // C++ [dcl.type.simple]p2:
11372 // A type-specifier of the form
11373 // typename[opt] nested-name-specifier[opt] template-name
11374 // is a placeholder for a deduced class type [...].
11375 if (getLangOpts().CPlusPlus17) {
11376 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11377 if (!DeducedTSTContext) {
11378 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11379 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11380 Diag(IILoc, diag::err_dependent_deduced_tst)
11382 << QualType(Qualifier.getAsType(), 0);
11383 else
11384 Diag(IILoc, diag::err_deduced_tst)
11387 return QualType();
11388 }
11389 TemplateName Name = Context.getQualifiedTemplateName(
11390 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11391 TemplateName(TD));
11392 return Context.getDeducedTemplateSpecializationType(
11393 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11394 }
11395 }
11396
11397 DiagID = Ctx ? diag::err_typename_nested_not_type
11398 : diag::err_typename_not_type;
11399 Referenced = Result.getFoundDecl();
11400 break;
11401
11403 DiagID = Ctx ? diag::err_typename_nested_not_type
11404 : diag::err_typename_not_type;
11405 Referenced = *Result.begin();
11406 break;
11407
11409 return QualType();
11410 }
11411
11412 // If we get here, it's because name lookup did not find a
11413 // type. Emit an appropriate diagnostic and return an error.
11414 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11415 IILoc);
11416 if (Ctx)
11417 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11418 else
11419 Diag(IILoc, DiagID) << FullRange << Name;
11420 if (Referenced)
11421 Diag(Referenced->getLocation(),
11422 Ctx ? diag::note_typename_member_refers_here
11423 : diag::note_typename_refers_here)
11424 << Name;
11425 return QualType();
11426}
11427
11428namespace {
11429 // See Sema::RebuildTypeInCurrentInstantiation
11430 class CurrentInstantiationRebuilder
11431 : public TreeTransform<CurrentInstantiationRebuilder> {
11432 SourceLocation Loc;
11433 DeclarationName Entity;
11434
11435 public:
11437
11438 CurrentInstantiationRebuilder(Sema &SemaRef,
11439 SourceLocation Loc,
11440 DeclarationName Entity)
11441 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11442 Loc(Loc), Entity(Entity) { }
11443
11444 /// Determine whether the given type \p T has already been
11445 /// transformed.
11446 ///
11447 /// For the purposes of type reconstruction, a type has already been
11448 /// transformed if it is NULL or if it is not dependent.
11449 bool AlreadyTransformed(QualType T) {
11450 return T.isNull() || !T->isInstantiationDependentType();
11451 }
11452
11453 /// Returns the location of the entity whose type is being
11454 /// rebuilt.
11455 SourceLocation getBaseLocation() { return Loc; }
11456
11457 /// Returns the name of the entity whose type is being rebuilt.
11458 DeclarationName getBaseEntity() { return Entity; }
11459
11460 /// Sets the "base" location and entity when that
11461 /// information is known based on another transformation.
11462 void setBase(SourceLocation Loc, DeclarationName Entity) {
11463 this->Loc = Loc;
11464 this->Entity = Entity;
11465 }
11466
11467 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11468 // Lambdas never need to be transformed.
11469 return E;
11470 }
11471 };
11472} // end anonymous namespace
11473
11475 SourceLocation Loc,
11476 DeclarationName Name) {
11477 if (!T || !T->getType()->isInstantiationDependentType())
11478 return T;
11479
11480 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11481 return Rebuilder.TransformType(T);
11482}
11483
11485 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11486 DeclarationName());
11487 return Rebuilder.TransformExpr(E);
11488}
11489
11491 if (SS.isInvalid())
11492 return true;
11493
11495 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11496 DeclarationName());
11498 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11499 if (!Rebuilt)
11500 return true;
11501
11502 SS.Adopt(Rebuilt);
11503 return false;
11504}
11505
11507 TemplateParameterList *Params) {
11508 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11509 Decl *Param = Params->getParam(I);
11510
11511 // There is nothing to rebuild in a type parameter.
11512 if (isa<TemplateTypeParmDecl>(Param))
11513 continue;
11514
11515 // Rebuild the template parameter list of a template template parameter.
11517 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11519 TTP->getTemplateParameters()))
11520 return true;
11521
11522 continue;
11523 }
11524
11525 // Rebuild the type of a non-type template parameter.
11527 TypeSourceInfo *NewTSI
11529 NTTP->getLocation(),
11530 NTTP->getDeclName());
11531 if (!NewTSI)
11532 return true;
11533
11534 if (NewTSI->getType()->isUndeducedType()) {
11535 // C++17 [temp.dep.expr]p3:
11536 // An id-expression is type-dependent if it contains
11537 // - an identifier associated by name lookup with a non-type
11538 // template-parameter declared with a type that contains a
11539 // placeholder type (7.1.7.4),
11540 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11541 }
11542
11543 if (NewTSI != NTTP->getTypeSourceInfo()) {
11544 NTTP->setTypeSourceInfo(NewTSI);
11545 NTTP->setType(NewTSI->getType());
11546 }
11547 }
11548
11549 return false;
11550}
11551
11552std::string
11554 const TemplateArgumentList &Args) {
11555 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11556}
11557
11558std::string
11560 const TemplateArgument *Args,
11561 unsigned NumArgs) {
11562 SmallString<128> Str;
11563 llvm::raw_svector_ostream Out(Str);
11564
11565 if (!Params || Params->size() == 0 || NumArgs == 0)
11566 return std::string();
11567
11568 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11569 if (I >= NumArgs)
11570 break;
11571
11572 if (I == 0)
11573 Out << "[with ";
11574 else
11575 Out << ", ";
11576
11577 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11578 Out << Id->getName();
11579 } else {
11580 Out << '$' << I;
11581 }
11582
11583 Out << " = ";
11584 Args[I].print(getPrintingPolicy(), Out,
11586 getPrintingPolicy(), Params, I));
11587 }
11588
11589 Out << ']';
11590 return std::string(Out.str());
11591}
11592
11594 CachedTokens &Toks) {
11595 if (!FD)
11596 return;
11597
11598 auto LPT = std::make_unique<LateParsedTemplate>();
11599
11600 // Take tokens to avoid allocations
11601 LPT->Toks.swap(Toks);
11602 LPT->D = FnD;
11603 LPT->FPO = getCurFPFeatures();
11604 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11605
11606 FD->setLateTemplateParsed(true);
11607}
11608
11610 if (!FD)
11611 return;
11612 FD->setLateTemplateParsed(false);
11613}
11614
11616 DeclContext *DC = CurContext;
11617
11618 while (DC) {
11619 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11620 const FunctionDecl *FD = RD->isLocalClass();
11621 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11622 } else if (DC->isTranslationUnit() || DC->isNamespace())
11623 return false;
11624
11625 DC = DC->getParent();
11626 }
11627 return false;
11628}
11629
11630namespace {
11631/// Walk the path from which a declaration was instantiated, and check
11632/// that every explicit specialization along that path is visible. This enforces
11633/// C++ [temp.expl.spec]/6:
11634///
11635/// If a template, a member template or a member of a class template is
11636/// explicitly specialized then that specialization shall be declared before
11637/// the first use of that specialization that would cause an implicit
11638/// instantiation to take place, in every translation unit in which such a
11639/// use occurs; no diagnostic is required.
11640///
11641/// and also C++ [temp.class.spec]/1:
11642///
11643/// A partial specialization shall be declared before the first use of a
11644/// class template specialization that would make use of the partial
11645/// specialization as the result of an implicit or explicit instantiation
11646/// in every translation unit in which such a use occurs; no diagnostic is
11647/// required.
11648class ExplicitSpecializationVisibilityChecker {
11649 Sema &S;
11650 SourceLocation Loc;
11653
11654public:
11655 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11657 : S(S), Loc(Loc), Kind(Kind) {}
11658
11659 void check(NamedDecl *ND) {
11660 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11661 return checkImpl(FD);
11662 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11663 return checkImpl(RD);
11664 if (auto *VD = dyn_cast<VarDecl>(ND))
11665 return checkImpl(VD);
11666 if (auto *ED = dyn_cast<EnumDecl>(ND))
11667 return checkImpl(ED);
11668 }
11669
11670private:
11671 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11672 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11673 : Sema::MissingImportKind::ExplicitSpecialization;
11674 const bool Recover = true;
11675
11676 // If we got a custom set of modules (because only a subset of the
11677 // declarations are interesting), use them, otherwise let
11678 // diagnoseMissingImport intelligently pick some.
11679 if (Modules.empty())
11680 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11681 else
11682 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11683 }
11684
11685 bool CheckMemberSpecialization(const NamedDecl *D) {
11686 return Kind == Sema::AcceptableKind::Visible
11689 }
11690
11691 bool CheckExplicitSpecialization(const NamedDecl *D) {
11692 return Kind == Sema::AcceptableKind::Visible
11695 }
11696
11697 bool CheckDeclaration(const NamedDecl *D) {
11698 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11700 }
11701
11702 // Check a specific declaration. There are three problematic cases:
11703 //
11704 // 1) The declaration is an explicit specialization of a template
11705 // specialization.
11706 // 2) The declaration is an explicit specialization of a member of an
11707 // templated class.
11708 // 3) The declaration is an instantiation of a template, and that template
11709 // is an explicit specialization of a member of a templated class.
11710 //
11711 // We don't need to go any deeper than that, as the instantiation of the
11712 // surrounding class / etc is not triggered by whatever triggered this
11713 // instantiation, and thus should be checked elsewhere.
11714 template<typename SpecDecl>
11715 void checkImpl(SpecDecl *Spec) {
11716 bool IsHiddenExplicitSpecialization = false;
11717 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11718 // Some invalid friend declarations are written as specializations but are
11719 // instantiated implicitly.
11720 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11721 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11722 if (SpecKind == TSK_ExplicitSpecialization) {
11723 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11724 ? !CheckMemberSpecialization(Spec)
11725 : !CheckExplicitSpecialization(Spec);
11726 } else {
11727 checkInstantiated(Spec);
11728 }
11729
11730 if (IsHiddenExplicitSpecialization)
11731 diagnose(Spec->getMostRecentDecl(), false);
11732 }
11733
11734 void checkInstantiated(FunctionDecl *FD) {
11735 if (auto *TD = FD->getPrimaryTemplate())
11736 checkTemplate(TD);
11737 }
11738
11739 void checkInstantiated(CXXRecordDecl *RD) {
11740 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11741 if (!SD)
11742 return;
11743
11744 auto From = SD->getSpecializedTemplateOrPartial();
11745 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11746 checkTemplate(TD);
11747 else if (auto *TD =
11748 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11749 if (!CheckDeclaration(TD))
11750 diagnose(TD, true);
11751 checkTemplate(TD);
11752 }
11753 }
11754
11755 void checkInstantiated(VarDecl *RD) {
11756 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11757 if (!SD)
11758 return;
11759
11760 auto From = SD->getSpecializedTemplateOrPartial();
11761 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11762 checkTemplate(TD);
11763 else if (auto *TD =
11764 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11765 if (!CheckDeclaration(TD))
11766 diagnose(TD, true);
11767 checkTemplate(TD);
11768 }
11769 }
11770
11771 void checkInstantiated(EnumDecl *FD) {}
11772
11773 template<typename TemplDecl>
11774 void checkTemplate(TemplDecl *TD) {
11775 if (TD->isMemberSpecialization()) {
11776 if (!CheckMemberSpecialization(TD))
11777 diagnose(TD->getMostRecentDecl(), false);
11778 }
11779 }
11780};
11781} // end anonymous namespace
11782
11784 if (!getLangOpts().Modules)
11785 return;
11786
11787 ExplicitSpecializationVisibilityChecker(*this, Loc,
11789 .check(Spec);
11790}
11791
11793 NamedDecl *Spec) {
11794 if (!getLangOpts().CPlusPlusModules)
11795 return checkSpecializationVisibility(Loc, Spec);
11796
11797 ExplicitSpecializationVisibilityChecker(*this, Loc,
11799 .check(Spec);
11800}
11801
11804 return N->getLocation();
11805 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11807 return FD->getLocation();
11810 return N->getLocation();
11811 }
11812 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11813 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11814 continue;
11815 return CSC.PointOfInstantiation;
11816 }
11817 return N->getLocation();
11818}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
APSInt & getComplexIntImag()
Definition APValue.h:527
ValueKind getKind() const
Definition APValue.h:461
APFixedPoint & getFixedPoint()
Definition APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isMemberPointer() const
Definition APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isNullPointer() const
Definition APValue.cpp:1019
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3892
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition Attr.h:44
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2373
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2391
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2441
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2434
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2409
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2415
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2421
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8142
Pointer to a block type.
Definition TypeBase.h:3542
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2099
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:735
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3872
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2020
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2061
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2198
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1371
ValueDecl * getDecl()
Definition Expr.h:1338
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2700
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
bool hasEllipsis() const
Definition DeclSpec.h:2699
bool isInvalidType() const
Definition DeclSpec.h:2688
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4061
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3512
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4011
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4101
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4432
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4227
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4270
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5080
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3090
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3085
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:827
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3065
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4042
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents a member of a struct/union/class.
Definition Decl.h:3160
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:2000
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4193
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4502
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4301
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4160
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3735
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2540
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4132
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition Decl.cpp:4366
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2362
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4405
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4153
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4844
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5551
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
QualType getReturnType() const
Definition TypeBase.h:4802
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3909
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
Describes an C or C++ initializer list.
Definition Expr.h:5233
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3617
Represents a linkage specification.
Definition DeclCXX.h:3015
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4398
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3653
QualType getPointeeType() const
Definition TypeBase.h:3671
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:264
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7852
Represents a pointer to an Objective C object.
Definition TypeBase.h:7908
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1416
bool isVarDeclReference() const
Definition ExprCXX.h:3304
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3320
bool isConceptReference() const
Definition ExprCXX.h:3293
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3339
A structure for storing the information associated with an overloaded template name.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4365
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:290
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8108
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8379
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3556
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8290
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8475
QualType getCanonicalType() const
Definition TypeBase.h:8342
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8384
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3549
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3635
Represents a struct/union/class.
Definition Decl.h:4312
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4496
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5312
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3573
QualType getPointeeType() const
Definition TypeBase.h:3591
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13549
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
Whether and why a template name is required in this lookup.
Definition Sema.h:11346
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11354
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12389
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12422
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7676
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13483
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12981
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9287
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9291
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9299
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9294
ExprResult ActOnConstantExpression(ExprResult Res)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, TemplateIdAnnotation *TemplateId, bool IsMemberSpecialization)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition Sema.h:9601
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
void NoteAllFoundTemplates(TemplateName Name)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition Sema.h:1445
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4134
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2049
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition Sema.h:11317
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:11915
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11918
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11922
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1283
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:925
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition Sema.h:11307
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12095
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12113
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12103
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12123
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
AssumedTemplateKind
Definition Sema.h:11367
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11374
@ None
This is not assumed to be a template name.
Definition Sema.h:11369
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11371
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition Sema.h:11300
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:920
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14326
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14314
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14323
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14317
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14341
const LangOptions & getLangOpts() const
Definition Sema.h:918
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1282
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition Sema.h:1281
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1418
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15322
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ASTConsumer & Consumer
Definition Sema.h:1284
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4630
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6696
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6675
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
bool inParameterMappingSubstitution() const
Definition Sema.h:13854
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11344
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:509
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11527
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11537
@ TPC_FriendFunctionTemplate
Definition Sema.h:11535
@ TPC_ClassTemplateMember
Definition Sema.h:11533
@ TPC_FunctionTemplate
Definition Sema.h:11532
@ TPC_FriendClassTemplate
Definition Sema.h:11534
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11536
friend class InitializationSequence
Definition Sema.h:1560
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6246
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6383
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1275
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3469
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11309
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:143
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9610
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12824
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:322
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8609
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4666
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
StringRef getKindName() const
Definition Decl.h:3907
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4894
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:4968
TagKind getTagKind() const
Definition Decl.h:3911
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:678
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3688
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3513
const Type * getTypeForDecl() const
Definition Decl.h:3538
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3547
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:913
bool isNull() const
Definition TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition TypeBase.h:6177
A container of type source information.
Definition TypeBase.h:8261
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8272
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isBooleanType() const
Definition TypeBase.h:9013
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2225
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2273
bool isRValueReferenceType() const
Definition TypeBase.h:8559
bool isVoidPointerType() const
Definition Type.cpp:712
bool isArrayType() const
Definition TypeBase.h:8626
bool isPointerType() const
Definition TypeBase.h:8527
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9170
bool isReferenceType() const
Definition TypeBase.h:8551
bool isEnumeralType() const
Definition TypeBase.h:8658
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9001
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8704
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2899
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isLValueReferenceType() const
Definition TypeBase.h:8555
bool isBitIntType() const
Definition TypeBase.h:8792
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8650
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2056
bool isMemberPointerType() const
Definition TypeBase.h:8608
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9019
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition Type.cpp:4898
bool isPointerOrReferenceType() const
Definition TypeBase.h:8531
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
bool isFunctionType() const
Definition TypeBase.h:8523
bool isVectorType() const
Definition TypeBase.h:8666
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2411
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9103
bool isNullPtrType() const
Definition TypeBase.h:8920
bool isRecordType() const
Definition TypeBase.h:8654
QualType getUnderlyingType() const
Definition Decl.h:3617
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
QualType desugar() const
Definition Type.cpp:4041
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1210
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:787
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5982
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3940
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3399
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3463
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2907
VarDecl * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2800
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Represents a GCC generic vector type.
Definition TypeBase.h:4175
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Extern
Definition Specifiers.h:251
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:449
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5890
@ Enum
The "enum" keyword.
Definition TypeBase.h:5904
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:560
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:415
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:419
@ Success
Template argument deduction was successful.
Definition Sema.h:369
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:421
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5865
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5886
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5883
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2247
CharacterLiteralKind
Definition Expr.h:1603
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5351
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3259
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3276
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3241
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:11953
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11949
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11942
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11939
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11939
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12998
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13105
A stack object to be created when performing template instantiation.
Definition Sema.h:13194
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13354
NamedDecl * Previous
Definition Sema.h:354
Location information for a TemplateArgument.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition DeclSpec.h:1009