clang 24.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"
16#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
23#include "clang/AST/Type.h"
32#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/Overload.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/SemaCUDA.h"
41#include "clang/Sema/Template.h"
43#include "llvm/ADT/SmallBitVector.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/SaveAndRestore.h"
47
48#include <optional>
49using namespace clang;
50using namespace sema;
51
52// Exported for use by Parser.
55 unsigned N) {
56 if (!N) return SourceRange();
57 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
58}
59
60unsigned Sema::getTemplateDepth(Scope *S) const {
61 unsigned Depth = 0;
62
63 // Each template parameter scope represents one level of template parameter
64 // depth.
65 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
66 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
67 ++Depth;
68 }
69
70 // Note that there are template parameters with the given depth.
71 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
72
73 // Look for parameters of an enclosing generic lambda. We don't create a
74 // template parameter scope for these.
76 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
77 if (!LSI->TemplateParams.empty()) {
78 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
79 break;
80 }
81 if (LSI->GLTemplateParameterList) {
82 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
83 break;
84 }
85 }
86 }
87
88 // Look for parameters of an enclosing terse function template. We don't
89 // create a template parameter scope for these either.
90 for (const InventedTemplateParameterInfo &Info :
92 if (!Info.TemplateParams.empty()) {
93 ParamsAtDepth(Info.AutoTemplateParameterDepth);
94 break;
95 }
96 }
97
98 return Depth;
99}
100
101/// \brief Determine whether the declaration found is acceptable as the name
102/// of a template and, if so, return that template declaration. Otherwise,
103/// returns null.
104///
105/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
106/// is true. In all other cases it will return a TemplateDecl (or null).
108 bool AllowFunctionTemplates,
109 bool AllowDependent) {
110 D = D->getUnderlyingDecl();
111
112 if (isa<TemplateDecl>(D)) {
113 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
114 return nullptr;
115
116 return D;
117 }
118
119 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
120 // C++ [temp.local]p1:
121 // Like normal (non-template) classes, class templates have an
122 // injected-class-name (Clause 9). The injected-class-name
123 // can be used with or without a template-argument-list. When
124 // it is used without a template-argument-list, it is
125 // equivalent to the injected-class-name followed by the
126 // template-parameters of the class template enclosed in
127 // <>. When it is used with a template-argument-list, it
128 // refers to the specified class template specialization,
129 // which could be the current specialization or another
130 // specialization.
131 if (Record->isInjectedClassName()) {
132 Record = cast<CXXRecordDecl>(Record->getDeclContext());
133 if (Record->getDescribedClassTemplate())
134 return Record->getDescribedClassTemplate();
135
136 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
137 return Spec->getSpecializedTemplate();
138 }
139
140 return nullptr;
141 }
142
143 // 'using Dependent::foo;' can resolve to a template name.
144 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
145 // injected-class-name).
146 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
147 return D;
148
149 return nullptr;
150}
151
153 bool AllowFunctionTemplates,
154 bool AllowDependent) {
155 LookupResult::Filter filter = R.makeFilter();
156 while (filter.hasNext()) {
157 NamedDecl *Orig = filter.next();
158 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
159 filter.erase();
160 }
161 filter.done();
162}
163
165 bool AllowFunctionTemplates,
166 bool AllowDependent,
167 bool AllowNonTemplateFunctions) {
168 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
169 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
170 return true;
171 if (AllowNonTemplateFunctions &&
172 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
173 return true;
174 }
175
176 return false;
177}
178
180Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
181 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
182 bool EnteringContext, TemplateTy &TemplateResult,
183 bool &MemberOfUnknownSpecialization,
184 bool AllowTypoCorrection) {
185 assert(getLangOpts().CPlusPlus && "No template names in C!");
186
187 DeclarationName TName;
188 MemberOfUnknownSpecialization = false;
189
190 switch (Name.getKind()) {
192 TName = DeclarationName(Name.Identifier);
193 break;
194
196 TName = Context.DeclarationNames.getCXXOperatorName(
198 break;
199
201 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
202 break;
203
204 default:
205 return TNK_Non_template;
206 }
207
208 QualType ObjectType = ObjectTypePtr.get();
209
210 AssumedTemplateKind AssumedTemplate;
211 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
212 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
213 /*RequiredTemplate=*/SourceLocation(),
214 &AssumedTemplate, AllowTypoCorrection))
215 return TNK_Non_template;
216 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
217
218 if (AssumedTemplate != AssumedTemplateKind::None) {
219 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
220 // Let the parser know whether we found nothing or found functions; if we
221 // found nothing, we want to more carefully check whether this is actually
222 // a function template name versus some other kind of undeclared identifier.
223 return AssumedTemplate == AssumedTemplateKind::FoundNothing
226 }
227
228 if (R.empty())
229 return TNK_Non_template;
230
231 NamedDecl *D = nullptr;
232 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
233 if (R.isAmbiguous()) {
234 // If we got an ambiguity involving a non-function template, treat this
235 // as a template name, and pick an arbitrary template for error recovery.
236 bool AnyFunctionTemplates = false;
237 for (NamedDecl *FoundD : R) {
238 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
239 if (isa<FunctionTemplateDecl>(FoundTemplate))
240 AnyFunctionTemplates = true;
241 else {
242 D = FoundTemplate;
243 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
244 break;
245 }
246 }
247 }
248
249 // If we didn't find any templates at all, this isn't a template name.
250 // Leave the ambiguity for a later lookup to diagnose.
251 if (!D && !AnyFunctionTemplates) {
252 R.suppressDiagnostics();
253 return TNK_Non_template;
254 }
255
256 // If the only templates were function templates, filter out the rest.
257 // We'll diagnose the ambiguity later.
258 if (!D)
260 }
261
262 // At this point, we have either picked a single template name declaration D
263 // or we have a non-empty set of results R containing either one template name
264 // declaration or a set of function templates.
265
267 TemplateNameKind TemplateKind;
268
269 unsigned ResultCount = R.end() - R.begin();
270 if (!D && ResultCount > 1) {
271 // We assume that we'll preserve the qualifier from a function
272 // template name in other ways.
273 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
274 TemplateKind = TNK_Function_template;
275
276 // We'll do this lookup again later.
277 R.suppressDiagnostics();
278 } else {
279 if (!D) {
280 D = getAsTemplateNameDecl(*R.begin());
281 assert(D && "unambiguous result is not a template name");
282 }
283
285 // We don't yet know whether this is a template-name or not.
286 MemberOfUnknownSpecialization = true;
287 return TNK_Non_template;
288 }
289
291 Template =
292 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
293 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
294 if (!SS.isInvalid()) {
295 NestedNameSpecifier Qualifier = SS.getScopeRep();
296 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
297 Template);
298 }
299
301 TemplateKind = TNK_Function_template;
302
303 // We'll do this lookup again later.
304 R.suppressDiagnostics();
305 } else {
309 TemplateKind =
311 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
315 }
316 }
317
319 S->getTemplateParamParent() == nullptr)
320 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
321 // Recover by returning the template, even though we would never be able to
322 // substitute it.
323
324 TemplateResult = TemplateTy::make(Template);
325 return TemplateKind;
326}
327
329 SourceLocation NameLoc, CXXScopeSpec &SS,
330 ParsedTemplateTy *Template /*=nullptr*/) {
331 // We could use redeclaration lookup here, but we don't need to: the
332 // syntactic form of a deduction guide is enough to identify it even
333 // if we can't look up the template name at all.
334 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
335 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
336 /*EnteringContext*/ false))
337 return false;
338
339 if (R.empty()) return false;
340 if (R.isAmbiguous()) {
341 // FIXME: Diagnose an ambiguity if we find at least one template.
342 R.suppressDiagnostics();
343 return false;
344 }
345
346 // We only treat template-names that name type templates as valid deduction
347 // guide names.
348 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
349 if (!TD || !getAsTypeTemplateDecl(TD))
350 return false;
351
352 if (Template) {
353 TemplateName Name = Context.getQualifiedTemplateName(
354 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
355 *Template = TemplateTy::make(Name);
356 }
357 return true;
358}
359
361 SourceLocation IILoc,
362 Scope *S,
363 const CXXScopeSpec *SS,
364 TemplateTy &SuggestedTemplate,
365 TemplateNameKind &SuggestedKind) {
366 // We can't recover unless there's a dependent scope specifier preceding the
367 // template name.
368 // FIXME: Typo correction?
369 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
371 return false;
372
373 // The code is missing a 'template' keyword prior to the dependent template
374 // name.
375 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
376 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
377 Diag(IILoc, diag::err_template_kw_missing)
378 << SuggestedTemplate.get()
379 << FixItHint::CreateInsertion(IILoc, "template ");
380 SuggestedKind = TNK_Dependent_template_name;
381 return true;
382}
383
385 QualType ObjectType, bool EnteringContext,
386 RequiredTemplateKind RequiredTemplate,
388 bool AllowTypoCorrection) {
389 if (ATK)
391
392 if (SS.isInvalid())
393 return true;
394
395 Found.setTemplateNameLookup(true);
396
397 // Determine where to perform name lookup
398 DeclContext *LookupCtx = nullptr;
399 bool IsDependent = false;
400 if (!ObjectType.isNull()) {
401 // This nested-name-specifier occurs in a member access expression, e.g.,
402 // x->B::f, and we are looking into the type of the object.
403 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
404 LookupCtx = computeDeclContext(ObjectType);
405 IsDependent = !LookupCtx && ObjectType->isDependentType();
406 assert((IsDependent || !ObjectType->isIncompleteType() ||
407 !ObjectType->getAs<TagType>() ||
408 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
409 "Caller should have completed object type");
410
411 // Template names cannot appear inside an Objective-C class or object type
412 // or a vector type.
413 //
414 // FIXME: This is wrong. For example:
415 //
416 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
417 // Vec<int> vi;
418 // vi.Vec<int>::~Vec<int>();
419 //
420 // ... should be accepted but we will not treat 'Vec' as a template name
421 // here. The right thing to do would be to check if the name is a valid
422 // vector component name, and look up a template name if not. And similarly
423 // for lookups into Objective-C class and object types, where the same
424 // problem can arise.
425 if (ObjectType->isObjCObjectOrInterfaceType() ||
426 ObjectType->isVectorType()) {
427 Found.clear();
428 return false;
429 }
430 } else if (SS.isNotEmpty()) {
431 // This nested-name-specifier occurs after another nested-name-specifier,
432 // so long into the context associated with the prior nested-name-specifier.
433 LookupCtx = computeDeclContext(SS, EnteringContext);
434 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
435
436 // The declaration context must be complete.
437 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
438 return true;
439 }
440
441 bool ObjectTypeSearchedInScope = false;
442 bool AllowFunctionTemplatesInLookup = true;
443 if (LookupCtx) {
444 // Perform "qualified" name lookup into the declaration context we
445 // computed, which is either the type of the base of a member access
446 // expression or the declaration context associated with a prior
447 // nested-name-specifier.
448 LookupQualifiedName(Found, LookupCtx);
449
450 // FIXME: The C++ standard does not clearly specify what happens in the
451 // case where the object type is dependent, and implementations vary. In
452 // Clang, we treat a name after a . or -> as a template-name if lookup
453 // finds a non-dependent member or member of the current instantiation that
454 // is a type template, or finds no such members and lookup in the context
455 // of the postfix-expression finds a type template. In the latter case, the
456 // name is nonetheless dependent, and we may resolve it to a member of an
457 // unknown specialization when we come to instantiate the template.
458 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
459 }
460
461 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
462 // C++ [basic.lookup.classref]p1:
463 // In a class member access expression (5.2.5), if the . or -> token is
464 // immediately followed by an identifier followed by a <, the
465 // identifier must be looked up to determine whether the < is the
466 // beginning of a template argument list (14.2) or a less-than operator.
467 // The identifier is first looked up in the class of the object
468 // expression. If the identifier is not found, it is then looked up in
469 // the context of the entire postfix-expression and shall name a class
470 // template.
471 if (S)
472 LookupName(Found, S);
473
474 if (!ObjectType.isNull()) {
475 // FIXME: We should filter out all non-type templates here, particularly
476 // variable templates and concepts. But the exclusion of alias templates
477 // and template template parameters is a wording defect.
478 AllowFunctionTemplatesInLookup = false;
479 ObjectTypeSearchedInScope = true;
480 }
481
482 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
483 }
484
485 if (Found.isAmbiguous())
486 return false;
487
488 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
489 !RequiredTemplate.hasTemplateKeyword()) {
490 // C++2a [temp.names]p2:
491 // A name is also considered to refer to a template if it is an
492 // unqualified-id followed by a < and name lookup finds either one or more
493 // functions or finds nothing.
494 //
495 // To keep our behavior consistent, we apply the "finds nothing" part in
496 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
497 // successfully form a call to an undeclared template-id.
498 bool AllFunctions =
499 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
501 });
502 if (AllFunctions || (Found.empty() && !IsDependent)) {
503 // If lookup found any functions, or if this is a name that can only be
504 // used for a function, then strongly assume this is a function
505 // template-id.
506 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
509 Found.clear();
510 return false;
511 }
512 }
513
514 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
515 // If we did not find any names, and this is not a disambiguation, attempt
516 // to correct any typos.
517 DeclarationName Name = Found.getLookupName();
518 Found.clear();
519
520 class TemplateNameLookupValidatorCCC final
522 public:
524
525 bool ValidateCandidate(const TypoCorrection &Candidate) final {
526 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
527 !ND || !isa<TemplateDecl>(ND))
528 return false;
530 }
531
532 std::unique_ptr<CorrectionCandidateCallback> clone() final {
533 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
534 }
535 };
536
537 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
538 FilterCCC.WantTypeSpecifiers = false;
539 FilterCCC.WantExpressionKeywords = false;
540 FilterCCC.WantRemainingKeywords = false;
541 FilterCCC.WantCXXNamedCasts = true;
542 if (TypoCorrection Corrected = CorrectTypo(
543 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
544 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
545 if (auto *ND = Corrected.getFoundDecl())
546 Found.addDecl(ND);
548 if (Found.isAmbiguous()) {
549 Found.clear();
550 } else if (!Found.empty()) {
551 // Do not erase the typo-corrected result to avoid duplicated
552 // diagnostics.
553 AllowFunctionTemplatesInLookup = true;
554 Found.setLookupName(Corrected.getCorrection());
555 if (LookupCtx) {
556 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
557 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
558 Name.getAsString() == CorrectedStr;
559 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
560 << Name << LookupCtx << DroppedSpecifier
561 << SS.getRange());
562 } else {
563 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
564 }
565
566 if (Corrected.WillReplaceSpecifier()) {
567 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
568 // In order to be valid, a non-empty CXXScopeSpec needs a source
569 // range.
570 SS.MakeTrivial(Context, NNS,
571 NNS ? Found.getNameLoc() : SourceRange());
572 }
573 }
574 }
575 }
576
577 NamedDecl *ExampleLookupResult =
578 Found.empty() ? nullptr : Found.getRepresentativeDecl();
579 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
580 if (Found.empty()) {
581 if (IsDependent) {
582 Found.setNotFoundInCurrentInstantiation();
583 return false;
584 }
585
586 // If a 'template' keyword was used, a lookup that finds only non-template
587 // names is an error.
588 if (ExampleLookupResult && RequiredTemplate) {
589 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
590 << Found.getLookupName() << SS.getRange()
591 << RequiredTemplate.hasTemplateKeyword()
592 << RequiredTemplate.getTemplateKeywordLoc();
593 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
594 diag::note_template_kw_refers_to_non_template)
595 << Found.getLookupName();
596 return true;
597 }
598
599 return false;
600 }
601
602 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
604 // C++03 [basic.lookup.classref]p1:
605 // [...] If the lookup in the class of the object expression finds a
606 // template, the name is also looked up in the context of the entire
607 // postfix-expression and [...]
608 //
609 // Note: C++11 does not perform this second lookup.
610 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
612 FoundOuter.setTemplateNameLookup(true);
613 LookupName(FoundOuter, S);
614 // FIXME: We silently accept an ambiguous lookup here, in violation of
615 // [basic.lookup]/1.
616 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
617
618 NamedDecl *OuterTemplate;
619 if (FoundOuter.empty()) {
620 // - if the name is not found, the name found in the class of the
621 // object expression is used, otherwise
622 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
623 !(OuterTemplate =
624 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
625 // - if the name is found in the context of the entire
626 // postfix-expression and does not name a class template, the name
627 // found in the class of the object expression is used, otherwise
628 FoundOuter.clear();
629 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
630 // - if the name found is a class template, it must refer to the same
631 // entity as the one found in the class of the object expression,
632 // otherwise the program is ill-formed.
633 if (!Found.isSingleResult() ||
634 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
635 OuterTemplate->getCanonicalDecl()) {
636 Diag(Found.getNameLoc(),
637 diag::ext_nested_name_member_ref_lookup_ambiguous)
638 << Found.getLookupName()
639 << ObjectType;
640 Diag(Found.getRepresentativeDecl()->getLocation(),
641 diag::note_ambig_member_ref_object_type)
642 << ObjectType;
643 Diag(FoundOuter.getFoundDecl()->getLocation(),
644 diag::note_ambig_member_ref_scope);
645
646 // Recover by taking the template that we found in the object
647 // expression's type.
648 }
649 }
650 }
651
652 return false;
653}
654
658 if (TemplateName.isInvalid())
659 return;
660
661 DeclarationNameInfo NameInfo;
662 CXXScopeSpec SS;
663 LookupNameKind LookupKind;
664
665 DeclContext *LookupCtx = nullptr;
666 NamedDecl *Found = nullptr;
667 bool MissingTemplateKeyword = false;
668
669 // Figure out what name we looked up.
670 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
671 NameInfo = DRE->getNameInfo();
672 SS.Adopt(DRE->getQualifierLoc());
673 LookupKind = LookupOrdinaryName;
674 Found = DRE->getFoundDecl();
675 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
676 NameInfo = ME->getMemberNameInfo();
677 SS.Adopt(ME->getQualifierLoc());
678 LookupKind = LookupMemberName;
679 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
680 Found = ME->getMemberDecl();
681 } else if (auto *DSDRE =
682 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
683 NameInfo = DSDRE->getNameInfo();
684 SS.Adopt(DSDRE->getQualifierLoc());
685 MissingTemplateKeyword = true;
686 } else if (auto *DSME =
687 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
688 NameInfo = DSME->getMemberNameInfo();
689 SS.Adopt(DSME->getQualifierLoc());
690 MissingTemplateKeyword = true;
691 } else {
692 llvm_unreachable("unexpected kind of potential template name");
693 }
694
695 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
696 // was missing.
697 if (MissingTemplateKeyword) {
698 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
699 << NameInfo.getName() << SourceRange(Less, Greater);
700 return;
701 }
702
703 // Try to correct the name by looking for templates and C++ named casts.
704 struct TemplateCandidateFilter : CorrectionCandidateCallback {
705 Sema &S;
706 TemplateCandidateFilter(Sema &S) : S(S) {
707 WantTypeSpecifiers = false;
708 WantExpressionKeywords = false;
709 WantRemainingKeywords = false;
710 WantCXXNamedCasts = true;
711 };
712 bool ValidateCandidate(const TypoCorrection &Candidate) override {
713 if (auto *ND = Candidate.getCorrectionDecl())
714 return S.getAsTemplateNameDecl(ND);
715 return Candidate.isKeyword();
716 }
717
718 std::unique_ptr<CorrectionCandidateCallback> clone() override {
719 return std::make_unique<TemplateCandidateFilter>(*this);
720 }
721 };
722
723 DeclarationName Name = NameInfo.getName();
724 TemplateCandidateFilter CCC(*this);
725 if (TypoCorrection Corrected =
726 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
727 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
728 auto *ND = Corrected.getFoundDecl();
729 if (ND)
730 ND = getAsTemplateNameDecl(ND);
731 if (ND || Corrected.isKeyword()) {
732 if (LookupCtx) {
733 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
734 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
735 Name.getAsString() == CorrectedStr;
736 diagnoseTypo(Corrected,
737 PDiag(diag::err_non_template_in_member_template_id_suggest)
738 << Name << LookupCtx << DroppedSpecifier
739 << SS.getRange(), false);
740 } else {
741 diagnoseTypo(Corrected,
742 PDiag(diag::err_non_template_in_template_id_suggest)
743 << Name, false);
744 }
745 if (Found)
746 Diag(Found->getLocation(),
747 diag::note_non_template_in_template_id_found);
748 return;
749 }
750 }
751
752 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
753 << Name << SourceRange(Less, Greater);
754 if (Found)
755 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
756}
757
760 SourceLocation TemplateKWLoc,
761 const DeclarationNameInfo &NameInfo,
762 bool isAddressOfOperand,
763 const TemplateArgumentListInfo *TemplateArgs) {
764 if (SS.isEmpty()) {
765 // FIXME: This codepath is only used by dependent unqualified names
766 // (e.g. a dependent conversion-function-id, or operator= once we support
767 // it). It doesn't quite do the right thing, and it will silently fail if
768 // getCurrentThisType() returns null.
769 QualType ThisType = getCurrentThisType();
770 if (ThisType.isNull())
771 return ExprError();
772
774 Context, /*Base=*/nullptr, ThisType,
775 /*IsArrow=*/!Context.getLangOpts().HLSL,
776 /*OperatorLoc=*/SourceLocation(),
777 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
778 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
779 }
780 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
781}
782
785 SourceLocation TemplateKWLoc,
786 const DeclarationNameInfo &NameInfo,
787 const TemplateArgumentListInfo *TemplateArgs) {
788 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
789 if (!SS.isValid())
790 return CreateRecoveryExpr(
791 SS.getBeginLoc(),
792 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
793
795 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
796 TemplateArgs);
797}
798
800Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
801 QualType ParamType, SourceLocation Loc,
803 UnsignedOrNone PackIndex, bool Final) {
804 // The template argument itself might be an expression, in which case we just
805 // return that expression. This happens when substituting into an alias
806 // template.
807 Expr *Replacement;
809 Replacement = Arg.getAsExpr();
810 } else {
811 ExprResult result =
812 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
813 if (result.isInvalid())
814 return ExprError();
815 Replacement = result.get();
816 }
817 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
818 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
819 AssociatedDecl, ParamType, Index, PackIndex, Final);
820}
821
823 NamedDecl *Instantiation,
824 bool InstantiatedFromMember,
825 const NamedDecl *Pattern,
826 const NamedDecl *PatternDef,
828 bool Complain, bool *Unreachable) {
829 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
830 isa<VarDecl>(Instantiation));
831
832 bool IsEntityBeingDefined = false;
833 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
834 IsEntityBeingDefined = TD->isBeingDefined();
835
836 if (PatternDef && !IsEntityBeingDefined) {
837 NamedDecl *SuggestedDef = nullptr;
838 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
839 &SuggestedDef,
840 /*OnlyNeedComplete*/ false)) {
841 if (Unreachable)
842 *Unreachable = true;
843 // If we're allowed to diagnose this and recover, do so.
844 bool Recover = Complain && !isSFINAEContext();
845 if (Complain)
846 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
848 return !Recover;
849 }
850 return false;
851 }
852
853 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
854 return true;
855
856 CanQualType InstantiationTy;
857 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
858 InstantiationTy = Context.getCanonicalTagType(TD);
859 if (PatternDef) {
860 Diag(PointOfInstantiation,
861 diag::err_template_instantiate_within_definition)
862 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
863 << InstantiationTy;
864 // Not much point in noting the template declaration here, since
865 // we're lexically inside it.
866 Instantiation->setInvalidDecl();
867 } else if (InstantiatedFromMember) {
868 if (isa<FunctionDecl>(Instantiation)) {
869 Diag(PointOfInstantiation,
870 diag::err_explicit_instantiation_undefined_member)
871 << /*member function*/ 1 << Instantiation->getDeclName()
872 << Instantiation->getDeclContext();
873 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
874 } else {
875 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
876 Diag(PointOfInstantiation,
877 diag::err_implicit_instantiate_member_undefined)
878 << InstantiationTy;
879 Diag(Pattern->getLocation(), diag::note_member_declared_at);
880 }
881 } else {
882 if (isa<FunctionDecl>(Instantiation)) {
883 Diag(PointOfInstantiation,
884 diag::err_explicit_instantiation_undefined_func_template)
885 << Pattern;
886 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
887 } else if (isa<TagDecl>(Instantiation)) {
888 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
889 << (TSK != TSK_ImplicitInstantiation)
890 << InstantiationTy;
891 NoteTemplateLocation(*Pattern);
892 } else {
893 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
894 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
895 Diag(PointOfInstantiation,
896 diag::err_explicit_instantiation_undefined_var_template)
897 << Instantiation;
898 Instantiation->setInvalidDecl();
899 } else
900 Diag(PointOfInstantiation,
901 diag::err_explicit_instantiation_undefined_member)
902 << /*static data member*/ 2 << Instantiation->getDeclName()
903 << Instantiation->getDeclContext();
904 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
905 }
906 }
907
908 // In general, Instantiation isn't marked invalid to get more than one
909 // error for multiple undefined instantiations. But the code that does
910 // explicit declaration -> explicit definition conversion can't handle
911 // invalid declarations, so mark as invalid in that case.
913 Instantiation->setInvalidDecl();
914 return true;
915}
916
918 bool SupportedForCompatibility) {
919 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
920
921 // C++23 [temp.local]p6:
922 // The name of a template-parameter shall not be bound to any following.
923 // declaration whose locus is contained by the scope to which the
924 // template-parameter belongs.
925 //
926 // When MSVC compatibility is enabled, the diagnostic is always a warning
927 // by default. Otherwise, it an error unless SupportedForCompatibility is
928 // true, in which case it is a default-to-error warning.
929 unsigned DiagId =
930 getLangOpts().MSVCCompat
931 ? diag::ext_template_param_shadow
932 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
933 : diag::err_template_param_shadow);
934 const auto *ND = cast<NamedDecl>(PrevDecl);
935 Diag(Loc, DiagId) << ND->getDeclName();
937}
938
940 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
941 D = Temp->getTemplatedDecl();
942 return Temp;
943 }
944 return nullptr;
945}
946
948 SourceLocation EllipsisLoc) const {
949 assert(Kind == Template &&
950 "Only template template arguments can be pack expansions here");
951 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
952 "Template template argument pack expansion without packs");
954 Result.EllipsisLoc = EllipsisLoc;
955 return Result;
956}
957
959 const ParsedTemplateArgument &Arg) {
960
961 switch (Arg.getKind()) {
963 TypeSourceInfo *TSI;
964 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
965 if (!TSI)
966 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
968 }
969
971 Expr *E = Arg.getAsExpr();
972 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
973 }
974
977 TemplateArgument TArg;
978 if (Arg.getEllipsisLoc().isValid())
979 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
980 else
981 TArg = Template;
982 return TemplateArgumentLoc(
983 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
985 Arg.getNameLoc(), Arg.getEllipsisLoc());
986 }
987 }
988
989 llvm_unreachable("Unhandled parsed template argument");
990}
991
993 TemplateArgumentListInfo &TemplateArgs) {
994 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
995 TemplateArgs.addArgument(translateTemplateArgument(*this,
996 TemplateArgsIn[I]));
997}
998
1000 SourceLocation Loc,
1001 const IdentifierInfo *Name) {
1002 NamedDecl *PrevDecl =
1003 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1005 if (PrevDecl && PrevDecl->isTemplateParameter())
1006 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1007}
1008
1010 TypeSourceInfo *TInfo;
1011 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1012 if (T.isNull())
1013 return ParsedTemplateArgument();
1014 assert(TInfo && "template argument with no location");
1015
1016 // If we might have formed a deduced template specialization type, convert
1017 // it to a template template argument.
1018 if (getLangOpts().CPlusPlus17) {
1019 TypeLoc TL = TInfo->getTypeLoc();
1020 SourceLocation EllipsisLoc;
1021 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1022 EllipsisLoc = PET.getEllipsisLoc();
1023 TL = PET.getPatternLoc();
1024 }
1025
1026 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1027 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1028 CXXScopeSpec SS;
1029 SS.Adopt(DTST.getQualifierLoc());
1030 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1031 TemplateTy::make(Name),
1032 DTST.getTemplateNameLoc());
1033 if (EllipsisLoc.isValid())
1034 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1035 return Result;
1036 }
1037 }
1038
1039 // This is a normal type template argument. Note, if the type template
1040 // argument is an injected-class-name for a template, it has a dual nature
1041 // and can be used as either a type or a template. We handle that in
1042 // convertTypeTemplateArgumentToTemplate.
1044 ParsedType.get().getAsOpaquePtr(),
1045 TInfo->getTypeLoc().getBeginLoc());
1046}
1047
1049 SourceLocation EllipsisLoc,
1050 SourceLocation KeyLoc,
1051 IdentifierInfo *ParamName,
1052 SourceLocation ParamNameLoc,
1053 unsigned Depth, unsigned Position,
1054 SourceLocation EqualLoc,
1055 ParsedType DefaultArg,
1056 bool HasTypeConstraint) {
1057 assert(S->isTemplateParamScope() &&
1058 "Template type parameter not in template parameter scope!");
1059
1060 bool IsParameterPack = EllipsisLoc.isValid();
1062 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1063 KeyLoc, ParamNameLoc, Depth, Position,
1064 ParamName, Typename, IsParameterPack,
1065 HasTypeConstraint);
1066 Param->setAccess(AS_public);
1067
1068 if (Param->isParameterPack())
1069 if (auto *CSI = getEnclosingLambdaOrBlock())
1070 CSI->LocalPacks.push_back(Param);
1071
1072 if (ParamName) {
1073 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1074
1075 // Add the template parameter into the current scope.
1076 S->AddDecl(Param);
1077 IdResolver.AddDecl(Param);
1078 }
1079
1080 // C++0x [temp.param]p9:
1081 // A default template-argument may be specified for any kind of
1082 // template-parameter that is not a template parameter pack.
1083 if (DefaultArg && IsParameterPack) {
1084 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1085 DefaultArg = nullptr;
1086 }
1087
1088 // Handle the default argument, if provided.
1089 if (DefaultArg) {
1090 TypeSourceInfo *DefaultTInfo;
1091 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1092
1093 assert(DefaultTInfo && "expected source information for type");
1094
1095 // Check for unexpanded parameter packs.
1096 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1098 return Param;
1099
1100 // Check the template argument itself.
1101 if (CheckTemplateArgument(DefaultTInfo)) {
1102 Param->setInvalidDecl();
1103 return Param;
1104 }
1105
1106 Param->setDefaultArgument(
1107 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1108 }
1109
1110 return Param;
1111}
1112
1113/// Convert the parser's template argument list representation into our form.
1116 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1117 TemplateId.RAngleLoc);
1118 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1119 TemplateId.NumArgs);
1120 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1121 return TemplateArgs;
1122}
1123
1125
1126 TemplateName TN = TypeConstr->Template.get();
1127 NamedDecl *CD = nullptr;
1128 bool IsTypeConcept = false;
1129 bool RequiresArguments = false;
1130 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1131 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1132 RequiresArguments =
1133 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1134 CD = TTP;
1135 } else {
1136 CD = TN.getAsTemplateDecl();
1137 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1138 RequiresArguments = cast<ConceptDecl>(CD)
1139 ->getTemplateParameters()
1140 ->getMinRequiredArguments() > 1;
1141 }
1142
1143 // C++2a [temp.param]p4:
1144 // [...] The concept designated by a type-constraint shall be a type
1145 // concept ([temp.concept]).
1146 if (!IsTypeConcept) {
1147 Diag(TypeConstr->TemplateNameLoc,
1148 diag::err_type_constraint_non_type_concept);
1149 return true;
1150 }
1151
1152 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1153 return true;
1154
1155 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1156
1157 if (!WereArgsSpecified && RequiresArguments) {
1158 Diag(TypeConstr->TemplateNameLoc,
1159 diag::err_type_constraint_missing_arguments)
1160 << CD;
1161 return true;
1162 }
1163 return false;
1164}
1165
1167 TemplateIdAnnotation *TypeConstr,
1168 TemplateTypeParmDecl *ConstrainedParameter,
1169 SourceLocation EllipsisLoc) {
1170 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1171 false);
1172}
1173
1175 TemplateIdAnnotation *TypeConstr,
1176 TemplateTypeParmDecl *ConstrainedParameter,
1177 SourceLocation EllipsisLoc,
1178 bool AllowUnexpandedPack) {
1179
1180 if (CheckTypeConstraint(TypeConstr))
1181 return true;
1182
1183 TemplateName TN = TypeConstr->Template.get();
1186
1187 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1188 TypeConstr->TemplateNameLoc);
1189
1190 TemplateArgumentListInfo TemplateArgs;
1191 if (TypeConstr->LAngleLoc.isValid()) {
1192 TemplateArgs =
1193 makeTemplateArgumentListInfo(*this, *TypeConstr);
1194
1195 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1196 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1198 return true;
1199 }
1200 }
1201 }
1202 return AttachTypeConstraint(
1204 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1205 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1206 ConstrainedParameter, EllipsisLoc);
1207}
1208
1209template <typename ArgumentLocAppender>
1212 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1213 SourceLocation RAngleLoc, QualType ConstrainedType,
1214 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1215 SourceLocation EllipsisLoc) {
1216
1217 TemplateArgumentListInfo ConstraintArgs;
1218 ConstraintArgs.addArgument(
1220 /*NTTPType=*/QualType(), ParamNameLoc));
1221
1222 ConstraintArgs.setRAngleLoc(RAngleLoc);
1223 ConstraintArgs.setLAngleLoc(LAngleLoc);
1224 Appender(ConstraintArgs);
1225
1226 // C++2a [temp.param]p4:
1227 // [...] This constraint-expression E is called the immediately-declared
1228 // constraint of T. [...]
1229 CXXScopeSpec SS;
1230 SS.Adopt(NS);
1231 ExprResult ImmediatelyDeclaredConstraint;
1232 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1233 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1234 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1235 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1236 /*DoCheckConstraintSatisfaction=*/
1238 }
1239 // We have a template template parameter
1240 else {
1241 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1242 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1243 ImmediatelyDeclaredConstraint =
1244 S.CheckVarOrConceptTemplateTemplateId(NameInfo, CDT, &ConstraintArgs);
1245 }
1246 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1247 return ImmediatelyDeclaredConstraint;
1248
1249 // C++2a [temp.param]p4:
1250 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1251 //
1252 // We have the following case:
1253 //
1254 // template<typename T> concept C1 = true;
1255 // template<C1... T> struct s1;
1256 //
1257 // The constraint: (C1<T> && ...)
1258 //
1259 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1260 // any unqualified lookups for 'operator&&' here.
1261 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1262 /*LParenLoc=*/SourceLocation(),
1263 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1264 EllipsisLoc, /*RHS=*/nullptr,
1265 /*RParenLoc=*/SourceLocation(),
1266 /*NumExpansions=*/std::nullopt);
1267}
1268
1270 DeclarationNameInfo NameInfo,
1271 TemplateDecl *NamedConcept,
1272 NamedDecl *FoundDecl,
1273 const TemplateArgumentListInfo *TemplateArgs,
1274 TemplateTypeParmDecl *ConstrainedParameter,
1275 SourceLocation EllipsisLoc) {
1276 // C++2a [temp.param]p4:
1277 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1278 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1279 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1281 *TemplateArgs) : nullptr;
1282
1283 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1284
1285 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1286 *this, NS, NameInfo, NamedConcept, FoundDecl,
1287 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1288 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1289 ParamAsArgument, ConstrainedParameter->getLocation(),
1290 [&](TemplateArgumentListInfo &ConstraintArgs) {
1291 if (TemplateArgs)
1292 for (const auto &ArgLoc : TemplateArgs->arguments())
1293 ConstraintArgs.addArgument(ArgLoc);
1294 },
1295 EllipsisLoc);
1296 if (ImmediatelyDeclaredConstraint.isInvalid())
1297 return true;
1298
1299 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1300 /*TemplateKWLoc=*/SourceLocation{},
1301 /*ConceptNameInfo=*/NameInfo,
1302 /*FoundDecl=*/FoundDecl,
1303 /*NamedConcept=*/NamedConcept,
1304 /*ArgsWritten=*/ArgsAsWritten);
1305 ConstrainedParameter->setTypeConstraint(
1306 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1307 return false;
1308}
1309
1311 NonTypeTemplateParmDecl *NewConstrainedParm,
1312 NonTypeTemplateParmDecl *OrigConstrainedParm,
1313 SourceLocation EllipsisLoc) {
1314 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1316 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1317 diag::err_unsupported_placeholder_constraint)
1318 << NewConstrainedParm->getTypeSourceInfo()
1319 ->getTypeLoc()
1320 .getSourceRange();
1321 NewConstrainedParm->setType(TL.getType());
1322 return true;
1323 }
1324 // FIXME: Concepts: This should be the type of the placeholder, but this is
1325 // unclear in the wording right now.
1326 DeclRefExpr *Ref =
1327 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1328 VK_PRValue, OrigConstrainedParm->getLocation());
1329 if (!Ref)
1330 return true;
1331 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1333 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1335 OrigConstrainedParm->getLocation(),
1336 [&](TemplateArgumentListInfo &ConstraintArgs) {
1337 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1338 ConstraintArgs.addArgument(TL.getArgLoc(I));
1339 },
1340 EllipsisLoc);
1341 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1342 !ImmediatelyDeclaredConstraint.isUsable())
1343 return true;
1344
1345 NewConstrainedParm->setPlaceholderTypeConstraint(
1346 ImmediatelyDeclaredConstraint.get());
1347 return false;
1348}
1349
1351 SourceLocation Loc) {
1352 if (TSI->getType()->isUndeducedType()) {
1353 // C++17 [temp.dep.expr]p3:
1354 // An id-expression is type-dependent if it contains
1355 // - an identifier associated by name lookup with a non-type
1356 // template-parameter declared with a type that contains a
1357 // placeholder type (7.1.7.4),
1359 if (!NewTSI)
1360 return QualType();
1361 TSI = NewTSI;
1362 }
1363
1364 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1365}
1366
1368 if (T->isDependentType())
1369 return false;
1370
1371 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1372 return true;
1373
1374 if (T->isStructuralType())
1375 return false;
1376
1377 // Structural types are required to be object types or lvalue references.
1378 if (T->isRValueReferenceType()) {
1379 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1380 return true;
1381 }
1382
1383 // Don't mention structural types in our diagnostic prior to C++20. Also,
1384 // there's not much more we can say about non-scalar non-class types --
1385 // because we can't see functions or arrays here, those can only be language
1386 // extensions.
1387 if (!getLangOpts().CPlusPlus20 ||
1388 (!T->isScalarType() && !T->isRecordType())) {
1389 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1390 return true;
1391 }
1392
1393 // Structural types are required to be literal types.
1394 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1395 return true;
1396
1397 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1398
1399 // Drill down into the reason why the class is non-structural.
1400 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1401 // All members are required to be public and non-mutable, and can't be of
1402 // rvalue reference type. Check these conditions first to prefer a "local"
1403 // reason over a more distant one.
1404 for (const FieldDecl *FD : RD->fields()) {
1405 if (FD->getAccess() != AS_public) {
1406 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1407 return true;
1408 }
1409 if (FD->isMutable()) {
1410 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1411 return true;
1412 }
1413 if (FD->getType()->isRValueReferenceType()) {
1414 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1415 << T;
1416 return true;
1417 }
1418 }
1419
1420 // All bases are required to be public.
1421 for (const auto &BaseSpec : RD->bases()) {
1422 if (BaseSpec.getAccessSpecifier() != AS_public) {
1423 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1424 << T << 1;
1425 return true;
1426 }
1427 }
1428
1429 // All subobjects are required to be of structural types.
1430 SourceLocation SubLoc;
1431 QualType SubType;
1432 int Kind = -1;
1433
1434 for (const FieldDecl *FD : RD->fields()) {
1435 QualType T = Context.getBaseElementType(FD->getType());
1436 if (!T->isStructuralType()) {
1437 SubLoc = FD->getLocation();
1438 SubType = T;
1439 Kind = 0;
1440 break;
1441 }
1442 }
1443
1444 if (Kind == -1) {
1445 for (const auto &BaseSpec : RD->bases()) {
1446 QualType T = BaseSpec.getType();
1447 if (!T->isStructuralType()) {
1448 SubLoc = BaseSpec.getBaseTypeLoc();
1449 SubType = T;
1450 Kind = 1;
1451 break;
1452 }
1453 }
1454 }
1455
1456 assert(Kind != -1 && "couldn't find reason why type is not structural");
1457 Diag(SubLoc, diag::note_not_structural_subobject)
1458 << T << Kind << SubType;
1459 T = SubType;
1460 RD = T->getAsCXXRecordDecl();
1461 }
1462
1463 return true;
1464}
1465
1467 SourceLocation Loc) {
1468 // We don't allow variably-modified types as the type of non-type template
1469 // parameters.
1470 if (T->isVariablyModifiedType()) {
1471 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1472 << T;
1473 return QualType();
1474 }
1475
1476 if (T->isBlockPointerType()) {
1477 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1478 return QualType();
1479 }
1480
1481 // C++ [temp.param]p4:
1482 //
1483 // A non-type template-parameter shall have one of the following
1484 // (optionally cv-qualified) types:
1485 //
1486 // -- integral or enumeration type,
1487 if (T->isIntegralOrEnumerationType() ||
1488 // -- pointer to object or pointer to function,
1489 T->isPointerType() ||
1490 // -- lvalue reference to object or lvalue reference to function,
1491 T->isLValueReferenceType() ||
1492 // -- pointer to member,
1493 T->isMemberPointerType() ||
1494 // -- std::nullptr_t, or
1495 T->isNullPtrType() ||
1496 // -- a type that contains a placeholder type.
1497 T->isUndeducedType()) {
1498 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1499 // are ignored when determining its type.
1500 return T.getUnqualifiedType();
1501 }
1502
1503 // C++ [temp.param]p8:
1504 //
1505 // A non-type template-parameter of type "array of T" or
1506 // "function returning T" is adjusted to be of type "pointer to
1507 // T" or "pointer to function returning T", respectively.
1508 if (T->isArrayType() || T->isFunctionType())
1509 return Context.getDecayedType(T);
1510
1511 // If T is a dependent type, we can't do the check now, so we
1512 // assume that it is well-formed. Note that stripping off the
1513 // qualifiers here is not really correct if T turns out to be
1514 // an array type, but we'll recompute the type everywhere it's
1515 // used during instantiation, so that should be OK. (Using the
1516 // qualified type is equally wrong.)
1517 if (T->isDependentType())
1518 return T.getUnqualifiedType();
1519
1520 // C++20 [temp.param]p6:
1521 // -- a structural type
1522 if (RequireStructuralType(T, Loc))
1523 return QualType();
1524
1525 if (!getLangOpts().CPlusPlus20) {
1526 // FIXME: Consider allowing structural types as an extension in C++17. (In
1527 // earlier language modes, the template argument evaluation rules are too
1528 // inflexible.)
1529 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1530 return QualType();
1531 }
1532
1533 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1534 return T.getUnqualifiedType();
1535}
1536
1538 unsigned Depth,
1539 unsigned Position,
1540 SourceLocation EqualLoc,
1541 Expr *Default) {
1543
1544 // Check that we have valid decl-specifiers specified.
1545 auto CheckValidDeclSpecifiers = [this, &D] {
1546 // C++ [temp.param]
1547 // p1
1548 // template-parameter:
1549 // ...
1550 // parameter-declaration
1551 // p2
1552 // ... A storage class shall not be specified in a template-parameter
1553 // declaration.
1554 // [dcl.typedef]p1:
1555 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1556 // of a parameter-declaration
1557 const DeclSpec &DS = D.getDeclSpec();
1558 auto EmitDiag = [this](SourceLocation Loc) {
1559 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1561 };
1563 EmitDiag(DS.getStorageClassSpecLoc());
1564
1566 EmitDiag(DS.getThreadStorageClassSpecLoc());
1567
1568 // [dcl.inline]p1:
1569 // The inline specifier can be applied only to the declaration or
1570 // definition of a variable or function.
1571
1572 if (DS.isInlineSpecified())
1573 EmitDiag(DS.getInlineSpecLoc());
1574
1575 // [dcl.constexpr]p1:
1576 // The constexpr specifier shall be applied only to the definition of a
1577 // variable or variable template or the declaration of a function or
1578 // function template.
1579
1580 if (DS.hasConstexprSpecifier())
1581 EmitDiag(DS.getConstexprSpecLoc());
1582
1583 // [dcl.fct.spec]p1:
1584 // Function-specifiers can be used only in function declarations.
1585
1586 if (DS.isVirtualSpecified())
1587 EmitDiag(DS.getVirtualSpecLoc());
1588
1589 if (DS.hasExplicitSpecifier())
1590 EmitDiag(DS.getExplicitSpecLoc());
1591
1592 if (DS.isNoreturnSpecified())
1593 EmitDiag(DS.getNoreturnSpecLoc());
1594 };
1595
1596 CheckValidDeclSpecifiers();
1597
1598 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1599 if (isa<AutoType>(T))
1601 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1602 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1603
1604 assert(S->isTemplateParamScope() &&
1605 "Non-type template parameter not in template parameter scope!");
1606 bool Invalid = false;
1607
1609 if (T.isNull()) {
1610 T = Context.IntTy; // Recover with an 'int' type.
1611 Invalid = true;
1612 }
1613
1615
1616 const IdentifierInfo *ParamName = D.getIdentifier();
1617 bool IsParameterPack = D.hasEllipsis();
1619 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1620 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1621 TInfo);
1622 Param->setAccess(AS_public);
1623
1625 if (TL.isConstrained()) {
1626 if (D.getEllipsisLoc().isInvalid() &&
1627 T->containsUnexpandedParameterPack()) {
1628 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1629 for (auto &Loc :
1630 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1633 }
1634 if (!Invalid &&
1635 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1636 Invalid = true;
1637 }
1638
1639 if (Invalid)
1640 Param->setInvalidDecl();
1641
1642 if (Param->isParameterPack())
1643 if (auto *CSI = getEnclosingLambdaOrBlock())
1644 CSI->LocalPacks.push_back(Param);
1645
1646 if (ParamName) {
1648 ParamName);
1649
1650 // Add the template parameter into the current scope.
1651 S->AddDecl(Param);
1652 IdResolver.AddDecl(Param);
1653 }
1654
1655 // C++0x [temp.param]p9:
1656 // A default template-argument may be specified for any kind of
1657 // template-parameter that is not a template parameter pack.
1658 if (Default && IsParameterPack) {
1659 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1660 Default = nullptr;
1661 }
1662
1663 // Check the well-formedness of the default template argument, if provided.
1664 if (Default) {
1665 // Check for unexpanded parameter packs.
1667 return Param;
1668
1669 Param->setDefaultArgument(
1671 TemplateArgument(Default, /*IsCanonical=*/false),
1672 QualType(), SourceLocation()));
1673 }
1674
1675 return Param;
1676}
1677
1678/// ActOnTemplateTemplateParameter - Called when a C++ template template
1679/// parameter (e.g. T in template <template <typename> class T> class array)
1680/// has been parsed. S is the current scope.
1682 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1683 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1684 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1685 unsigned Position, SourceLocation EqualLoc,
1687 assert(S->isTemplateParamScope() &&
1688 "Template template parameter not in template parameter scope!");
1689
1690 bool IsParameterPack = EllipsisLoc.isValid();
1691
1692 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1693 if (Params->size() == 0) {
1694 Diag(Loc, diag::err_template_template_parm_no_parms)
1695 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1696
1697 // Recover as if there was a type template parameter pack.
1698 SmallVector<NamedDecl *, 4> ParamDecls;
1699 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1700 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1701 Depth + 1, 0, /*Id=*/nullptr,
1702 /*Typename=*/false, /*ParameterPack=*/true));
1704 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1705 Params->getRAngleLoc(), Params->getRequiresClause());
1706 }
1707
1708 bool Invalid = false;
1710 Params,
1711 /*OldParams=*/nullptr,
1712 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1713 Invalid = true;
1714
1715 // Construct the parameter object.
1717 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1718 IsParameterPack, Name, Kind, Typename, Params);
1719 Param->setAccess(AS_public);
1720
1721 if (Param->isParameterPack())
1722 if (auto *LSI = getEnclosingLambdaOrBlock())
1723 LSI->LocalPacks.push_back(Param);
1724
1725 // If the template template parameter has a name, then link the identifier
1726 // into the scope and lookup mechanisms.
1727 if (Name) {
1728 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1729
1730 S->AddDecl(Param);
1731 IdResolver.AddDecl(Param);
1732 }
1733
1734 if (Invalid)
1735 Param->setInvalidDecl();
1736
1737 // C++0x [temp.param]p9:
1738 // A default template-argument may be specified for any kind of
1739 // template-parameter that is not a template parameter pack.
1740 if (IsParameterPack && !Default.isInvalid()) {
1741 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1743 }
1744
1745 if (!Default.isInvalid()) {
1746 // Check only that we have a template template argument. We don't want to
1747 // try to check well-formedness now, because our template template parameter
1748 // might have dependent types in its template parameters, which we wouldn't
1749 // be able to match now.
1750 //
1751 // If none of the template template parameter's template arguments mention
1752 // other template parameters, we could actually perform more checking here.
1753 // However, it isn't worth doing.
1755 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1756 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1757 << DefaultArg.getSourceRange();
1758 return Param;
1759 }
1760
1761 TemplateName Name =
1764 if (Template &&
1766 return Param;
1767 }
1768
1769 // Check for unexpanded parameter packs.
1771 DefaultArg.getArgument().getAsTemplate(),
1773 return Param;
1774
1775 Param->setDefaultArgument(Context, DefaultArg);
1776 }
1777
1778 return Param;
1779}
1780
1781namespace {
1782class ConstraintRefersToContainingTemplateChecker
1784 using inherited = ConstDynamicRecursiveASTVisitor;
1785 bool Result = false;
1786 const FunctionDecl *Friend = nullptr;
1787 unsigned TemplateDepth = 0;
1788
1789 // Check a record-decl that we've seen to see if it is a lexical parent of the
1790 // Friend, likely because it was referred to without its template arguments.
1791 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1792 CheckingRD = CheckingRD->getMostRecentDecl();
1793 if (!CheckingRD->isTemplated())
1794 return true;
1795
1796 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1797 DC && !DC->isFileContext(); DC = DC->getParent())
1798 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1799 if (CheckingRD == RD->getMostRecentDecl()) {
1800 Result = true;
1801 return false;
1802 }
1803
1804 return true;
1805 }
1806
1807 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1808 if (D->getDepth() < TemplateDepth)
1809 Result = true;
1810
1811 // Necessary because the type of the NTTP might be what refers to the parent
1812 // constriant.
1813 return TraverseType(D->getType());
1814 }
1815
1816public:
1817 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1818 unsigned TemplateDepth)
1819 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1820
1821 bool getResult() const { return Result; }
1822
1823 // This should be the only template parm type that we have to deal with.
1824 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1825 // FunctionParmPackExpr are all partially substituted, which cannot happen
1826 // with concepts at this point in translation.
1827 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1828 if (Type->getDecl()->getDepth() < TemplateDepth) {
1829 Result = true;
1830 return false;
1831 }
1832 return true;
1833 }
1834
1835 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1836 return TraverseDecl(E->getDecl());
1837 }
1838
1839 bool TraverseTypedefType(const TypedefType *TT,
1840 bool /*TraverseQualifier*/) override {
1841 return TraverseType(TT->desugar());
1842 }
1843
1844 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1845 // We don't care about TypeLocs. So traverse Types instead.
1846 return TraverseType(TL.getType(), TraverseQualifier);
1847 }
1848
1849 bool VisitTagType(const TagType *T) override {
1850 return TraverseDecl(T->getDecl());
1851 }
1852
1853 bool TraverseDecl(const Decl *D) override {
1854 assert(D);
1855 // FIXME : This is possibly an incomplete list, but it is unclear what other
1856 // Decl kinds could be used to refer to the template parameters. This is a
1857 // best guess so far based on examples currently available, but the
1858 // unreachable should catch future instances/cases.
1859 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1860 return TraverseType(TD->getUnderlyingType());
1861 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1862 return CheckNonTypeTemplateParmDecl(NTTPD);
1863 if (auto *VD = dyn_cast<ValueDecl>(D))
1864 return TraverseType(VD->getType());
1865 if (isa<TemplateDecl>(D))
1866 return true;
1867 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1868 return CheckIfContainingRecord(RD);
1869
1871 // No direct types to visit here I believe.
1872 } else
1873 llvm_unreachable("Don't know how to handle this declaration type yet");
1874 return true;
1875 }
1876};
1877} // namespace
1878
1880 const FunctionDecl *Friend, unsigned TemplateDepth,
1881 const Expr *Constraint) {
1882 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1883 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1884 Checker.TraverseStmt(Constraint);
1885 return Checker.getResult();
1886}
1887
1890 SourceLocation ExportLoc,
1891 SourceLocation TemplateLoc,
1892 SourceLocation LAngleLoc,
1893 ArrayRef<NamedDecl *> Params,
1894 SourceLocation RAngleLoc,
1895 Expr *RequiresClause) {
1896 if (ExportLoc.isValid())
1897 Diag(ExportLoc, diag::warn_template_export_unsupported);
1898
1899 for (NamedDecl *P : Params)
1901
1902 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1903 llvm::ArrayRef(Params), RAngleLoc,
1904 RequiresClause);
1905}
1906
1908 const CXXScopeSpec &SS) {
1909 if (SS.isSet())
1910 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1911}
1912
1913// Returns the template parameter list with all default template argument
1914// information.
1916 // Make sure we get the template parameter list from the most
1917 // recent declaration, since that is the only one that is guaranteed to
1918 // have all the default template argument information.
1919 Decl *D = TD->getMostRecentDecl();
1920 // C++11 N3337 [temp.param]p12:
1921 // A default template argument shall not be specified in a friend class
1922 // template declaration.
1923 //
1924 // Skip past friend *declarations* because they are not supposed to contain
1925 // default template arguments. Moreover, these declarations may introduce
1926 // template parameters living in different template depths than the
1927 // corresponding template parameters in TD, causing unmatched constraint
1928 // substitution.
1929 //
1930 // FIXME: Diagnose such cases within a class template:
1931 // template <class T>
1932 // struct S {
1933 // template <class = void> friend struct C;
1934 // };
1935 // template struct S<int>;
1937 D->getPreviousDecl())
1938 D = D->getPreviousDecl();
1939 return cast<TemplateDecl>(D)->getTemplateParameters();
1940}
1941
1943 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1944 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1945 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1946 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1947 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1948 TemplateParameterList **OuterTemplateParamLists,
1949 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1950 assert(TemplateParams && TemplateParams->size() > 0 &&
1951 "No template parameters");
1952 assert(TUK != TagUseKind::Reference &&
1953 "Can only declare or define class templates");
1954 bool Invalid = false;
1955
1956 // Check that we can declare a template here.
1957 if (CheckTemplateDeclScope(S, TemplateParams))
1958 return true;
1959
1961 assert(Kind != TagTypeKind::Enum &&
1962 "can't build template of enumerated type");
1963
1964 // There is no such thing as an unnamed class template.
1965 if (!Name) {
1966 Diag(KWLoc, diag::err_template_unnamed_class);
1967 return true;
1968 }
1969
1970 // Find any previous declaration with this name. For a friend with no
1971 // scope explicitly specified, we only look for tag declarations (per
1972 // C++11 [basic.lookup.elab]p2).
1973 DeclContext *SemanticContext;
1974 LookupResult Previous(*this, Name, NameLoc,
1975 (SS.isEmpty() && TUK == TagUseKind::Friend)
1979 if (SS.isNotEmpty() && !SS.isInvalid()) {
1980 SemanticContext = computeDeclContext(SS, true);
1981 if (!SemanticContext) {
1982 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
1983 << SS.getScopeRep() << SS.getRange();
1984 return true;
1985 }
1986
1987 if (RequireCompleteDeclContext(SS, SemanticContext))
1988 return true;
1989
1990 // If we're adding a template to a dependent context, we may need to
1991 // rebuilding some of the types used within the template parameter list,
1992 // now that we know what the current instantiation is.
1993 if (SemanticContext->isDependentContext()) {
1994 ContextRAII SavedContext(*this, SemanticContext);
1996 Invalid = true;
1997 }
1998
1999 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2000 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2001 /*TemplateId=*/nullptr,
2002 IsMemberSpecialization))
2003 return true;
2004
2005 LookupQualifiedName(Previous, SemanticContext);
2006 } else {
2007 SemanticContext = CurContext;
2008
2009 // C++14 [class.mem]p14:
2010 // If T is the name of a class, then each of the following shall have a
2011 // name different from T:
2012 // -- every member template of class T
2013 if (TUK != TagUseKind::Friend &&
2014 DiagnoseClassNameShadow(SemanticContext,
2015 DeclarationNameInfo(Name, NameLoc)))
2016 return true;
2017
2018 LookupName(Previous, S);
2019 }
2020
2021 if (Previous.isAmbiguous())
2022 return true;
2023
2024 // Let the template parameter scope enter the lookup chain of the current
2025 // class template. For example, given
2026 //
2027 // namespace ns {
2028 // template <class> bool Param = false;
2029 // template <class T> struct N;
2030 // }
2031 //
2032 // template <class Param> struct ns::N { void foo(Param); };
2033 //
2034 // When we reference Param inside the function parameter list, our name lookup
2035 // chain for it should be like:
2036 // FunctionScope foo
2037 // -> RecordScope N
2038 // -> TemplateParamScope (where we will find Param)
2039 // -> NamespaceScope ns
2040 //
2041 // See also CppLookupName().
2042 if (S->isTemplateParamScope())
2043 EnterTemplatedContext(S, SemanticContext);
2044
2045 NamedDecl *PrevDecl = nullptr;
2046 if (Previous.begin() != Previous.end())
2047 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2048
2049 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2050 // Maybe we will complain about the shadowed template parameter.
2051 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2052 // Just pretend that we didn't see the previous declaration.
2053 PrevDecl = nullptr;
2054 }
2055
2056 // If there is a previous declaration with the same name, check
2057 // whether this is a valid redeclaration.
2058 ClassTemplateDecl *PrevClassTemplate =
2059 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2060
2061 // We may have found the injected-class-name of a class template,
2062 // class template partial specialization, or class template specialization.
2063 // In these cases, grab the template that is being defined or specialized.
2064 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2065 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2066 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2067 PrevClassTemplate
2068 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2069 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2070 PrevClassTemplate
2072 ->getSpecializedTemplate();
2073 }
2074 }
2075
2076 if (TUK == TagUseKind::Friend) {
2077 // C++ [namespace.memdef]p3:
2078 // [...] When looking for a prior declaration of a class or a function
2079 // declared as a friend, and when the name of the friend class or
2080 // function is neither a qualified name nor a template-id, scopes outside
2081 // the innermost enclosing namespace scope are not considered.
2082 if (!SS.isSet()) {
2083 DeclContext *OutermostContext = CurContext;
2084 while (!OutermostContext->isFileContext())
2085 OutermostContext = OutermostContext->getLookupParent();
2086
2087 if (PrevDecl &&
2088 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2089 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2090 SemanticContext = PrevDecl->getDeclContext();
2091 } else {
2092 // Declarations in outer scopes don't matter. However, the outermost
2093 // context we computed is the semantic context for our new
2094 // declaration.
2095 PrevDecl = PrevClassTemplate = nullptr;
2096 SemanticContext = OutermostContext;
2097
2098 // Check that the chosen semantic context doesn't already contain a
2099 // declaration of this name as a non-tag type.
2101 DeclContext *LookupContext = SemanticContext;
2102 while (LookupContext->isTransparentContext())
2103 LookupContext = LookupContext->getLookupParent();
2104 LookupQualifiedName(Previous, LookupContext);
2105
2106 if (Previous.isAmbiguous())
2107 return true;
2108
2109 if (Previous.begin() != Previous.end())
2110 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2111 }
2112 }
2113 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2114 SemanticContext, S, SS.isValid()))
2115 PrevDecl = PrevClassTemplate = nullptr;
2116
2117 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2118 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2119 if (SS.isEmpty() &&
2120 !(PrevClassTemplate &&
2121 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2122 SemanticContext->getRedeclContext()))) {
2123 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2124 Diag(Shadow->getTargetDecl()->getLocation(),
2125 diag::note_using_decl_target);
2126 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2127 // Recover by ignoring the old declaration.
2128 PrevDecl = PrevClassTemplate = nullptr;
2129 }
2130 }
2131
2132 if (PrevClassTemplate) {
2133 // Ensure that the template parameter lists are compatible. Skip this check
2134 // for a friend in a dependent context: the template parameter list itself
2135 // could be dependent.
2136 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2138 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2139 : CurContext,
2140 CurContext, KWLoc),
2141 TemplateParams, PrevClassTemplate,
2142 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2144 return true;
2145
2146 // C++ [temp.class]p4:
2147 // In a redeclaration, partial specialization, explicit
2148 // specialization or explicit instantiation of a class template,
2149 // the class-key shall agree in kind with the original class
2150 // template declaration (7.1.5.3).
2151 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2153 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2154 Diag(KWLoc, diag::err_use_with_wrong_tag)
2155 << Name
2156 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2157 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2158 Kind = PrevRecordDecl->getTagKind();
2159 }
2160
2161 // Check for redefinition of this class template.
2162 if (TUK == TagUseKind::Definition) {
2163 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2164 // If we have a prior definition that is not visible, treat this as
2165 // simply making that previous definition visible.
2166 NamedDecl *Hidden = nullptr;
2167 bool HiddenDefVisible = false;
2168 if (SkipBody &&
2169 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2170 SkipBody->ShouldSkip = true;
2171 SkipBody->Previous = Def;
2172 if (!HiddenDefVisible && Hidden) {
2173 auto *Tmpl =
2174 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2175 assert(Tmpl && "original definition of a class template is not a "
2176 "class template?");
2179 }
2180 } else {
2181 Diag(NameLoc, diag::err_redefinition) << Name;
2182 Diag(Def->getLocation(), diag::note_previous_definition);
2183 // FIXME: Would it make sense to try to "forget" the previous
2184 // definition, as part of error recovery?
2185 return true;
2186 }
2187 }
2188 }
2189 } else if (PrevDecl) {
2190 // C++ [temp]p5:
2191 // A class template shall not have the same name as any other
2192 // template, class, function, object, enumeration, enumerator,
2193 // namespace, or type in the same scope (3.3), except as specified
2194 // in (14.5.4).
2195 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2196 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2197 return true;
2198 }
2199
2200 // Check the template parameter list of this declaration, possibly
2201 // merging in the template parameter list from the previous class
2202 // template declaration. Skip this check for a friend in a dependent
2203 // context, because the template parameter list might be dependent.
2204 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2206 TemplateParams,
2207 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2208 : nullptr,
2209 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2210 SemanticContext->isDependentContext())
2213 : TPC_Other,
2214 SkipBody))
2215 Invalid = true;
2216
2217 if (SS.isSet()) {
2218 // If the name of the template was qualified, we must be defining the
2219 // template out-of-line.
2220 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2221 return Diag(NameLoc, TUK == TagUseKind::Friend
2222 ? diag::err_friend_decl_does_not_match
2223 : diag::err_member_decl_does_not_match)
2224 << Name << SemanticContext << /*IsDefinition*/ true
2225 << SS.getRange();
2226 }
2227
2228 // If this is a templated friend in a dependent context we should not put it
2229 // on the redecl chain. In some cases, the templated friend can be the most
2230 // recent declaration tricking the template instantiator to make substitutions
2231 // there.
2232 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2233 bool ShouldAddRedecl =
2234 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2235
2237 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2238 PrevClassTemplate && ShouldAddRedecl
2239 ? PrevClassTemplate->getTemplatedDecl()
2240 : nullptr);
2241 SetNestedNameSpecifier(*this, NewClass, SS);
2242 if (NumOuterTemplateParamLists > 0)
2244 Context,
2245 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2246
2247 // Add alignment attributes if necessary; these attributes are checked when
2248 // the ASTContext lays out the structure.
2249 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2250 if (LangOpts.HLSL)
2251 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2254 }
2255
2256 ClassTemplateDecl *NewTemplate
2257 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2258 DeclarationName(Name), TemplateParams,
2259 NewClass);
2260
2261 if (ShouldAddRedecl)
2262 NewTemplate->setPreviousDecl(PrevClassTemplate);
2263
2264 NewClass->setDescribedClassTemplate(NewTemplate);
2265
2266 if (ModulePrivateLoc.isValid())
2267 NewTemplate->setModulePrivate();
2268
2269 if (IsMemberSpecialization) {
2270 assert(PrevClassTemplate &&
2271 "Member specialization without a primary template?");
2272 NewTemplate->setMemberSpecialization();
2273 }
2274
2275 // Set the access specifier.
2276 if (!Invalid && TUK != TagUseKind::Friend &&
2277 NewTemplate->getDeclContext()->isRecord())
2278 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2279
2280 // Set the lexical context of these templates
2282 NewTemplate->setLexicalDeclContext(CurContext);
2283
2284 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2285 NewClass->startDefinition();
2286
2287 ProcessDeclAttributeList(S, NewClass, Attr);
2288
2289 if (PrevClassTemplate) {
2290 mergeDeclAttributes(NewTemplate, PrevClassTemplate);
2291 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2292 }
2293
2297
2298 if (TUK != TagUseKind::Friend) {
2299 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2300 Scope *Outer = S;
2301 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2302 Outer = Outer->getParent();
2303 PushOnScopeChains(NewTemplate, Outer);
2304 } else {
2305 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2306 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2307 NewClass->setAccess(PrevClassTemplate->getAccess());
2308 }
2309
2310 NewTemplate->setObjectOfFriendDecl();
2311
2312 // Friend templates are visible in fairly strange ways.
2313 if (!CurContext->isDependentContext()) {
2314 DeclContext *DC = SemanticContext->getRedeclContext();
2315 DC->makeDeclVisibleInContext(NewTemplate);
2316 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2317 PushOnScopeChains(NewTemplate, EnclosingScope,
2318 /* AddToContext = */ false);
2319 }
2320
2322 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2323 Friend->setAccess(AS_public);
2324 CurContext->addDecl(Friend);
2325 }
2326
2327 if (PrevClassTemplate)
2328 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2329
2330 if (Invalid) {
2331 NewTemplate->setInvalidDecl();
2332 NewClass->setInvalidDecl();
2333 }
2334
2335 ActOnDocumentableDecl(NewTemplate);
2336
2337 if (SkipBody && SkipBody->ShouldSkip)
2338 return SkipBody->Previous;
2339
2340 return NewTemplate;
2341}
2342
2343/// Diagnose the presence of a default template argument on a
2344/// template parameter, which is ill-formed in certain contexts.
2345///
2346/// \returns true if the default template argument should be dropped.
2349 SourceLocation ParamLoc,
2350 SourceRange DefArgRange) {
2351 switch (TPC) {
2352 case Sema::TPC_Other:
2354 return false;
2355
2358 // C++ [temp.param]p9:
2359 // A default template-argument shall not be specified in a
2360 // function template declaration or a function template
2361 // definition [...]
2362 // If a friend function template declaration specifies a default
2363 // template-argument, that declaration shall be a definition and shall be
2364 // the only declaration of the function template in the translation unit.
2365 // (C++98/03 doesn't have this wording; see DR226).
2366 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2367 << DefArgRange;
2368 return false;
2369
2371 // C++0x [temp.param]p9:
2372 // A default template-argument shall not be specified in the
2373 // template-parameter-lists of the definition of a member of a
2374 // class template that appears outside of the member's class.
2375 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2376 << DefArgRange;
2377 return true;
2378
2381 // C++ [temp.param]p9:
2382 // A default template-argument shall not be specified in a
2383 // friend template declaration.
2384 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2385 << DefArgRange;
2386 return true;
2387
2388 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2389 // for friend function templates if there is only a single
2390 // declaration (and it is a definition). Strange!
2391 }
2392
2393 llvm_unreachable("Invalid TemplateParamListContext!");
2394}
2395
2396/// Check for unexpanded parameter packs within the template parameters
2397/// of a template template parameter, recursively.
2400 // A template template parameter which is a parameter pack is also a pack
2401 // expansion.
2402 if (TTP->isParameterPack())
2403 return false;
2404
2406 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2407 NamedDecl *P = Params->getParam(I);
2408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2409 if (!TTP->isParameterPack())
2410 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2411 if (TC->hasExplicitTemplateArgs())
2412 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2415 return true;
2416 continue;
2417 }
2418
2419 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2420 if (!NTTP->isParameterPack() &&
2421 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2422 NTTP->getTypeSourceInfo(),
2424 return true;
2425
2426 continue;
2427 }
2428
2429 if (TemplateTemplateParmDecl *InnerTTP
2430 = dyn_cast<TemplateTemplateParmDecl>(P))
2431 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2432 return true;
2433 }
2434
2435 return false;
2436}
2437
2439 TemplateParameterList *OldParams,
2441 SkipBodyInfo *SkipBody) {
2442 bool Invalid = false;
2443
2444 // C++ [temp.param]p10:
2445 // The set of default template-arguments available for use with a
2446 // template declaration or definition is obtained by merging the
2447 // default arguments from the definition (if in scope) and all
2448 // declarations in scope in the same way default function
2449 // arguments are (8.3.6).
2450 bool SawDefaultArgument = false;
2451 SourceLocation PreviousDefaultArgLoc;
2452
2453 // Dummy initialization to avoid warnings.
2454 TemplateParameterList::iterator OldParam = NewParams->end();
2455 if (OldParams)
2456 OldParam = OldParams->begin();
2457
2458 bool RemoveDefaultArguments = false;
2459 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2460 NewParamEnd = NewParams->end();
2461 NewParam != NewParamEnd; ++NewParam) {
2462 // Whether we've seen a duplicate default argument in the same translation
2463 // unit.
2464 bool RedundantDefaultArg = false;
2465 // Whether we've found inconsis inconsitent default arguments in different
2466 // translation unit.
2467 bool InconsistentDefaultArg = false;
2468 // The name of the module which contains the inconsistent default argument.
2469 std::string PrevModuleName;
2470
2471 SourceLocation OldDefaultLoc;
2472 SourceLocation NewDefaultLoc;
2473
2474 // Variable used to diagnose missing default arguments
2475 bool MissingDefaultArg = false;
2476
2477 // Variable used to diagnose non-final parameter packs
2478 bool SawParameterPack = false;
2479
2480 if (TemplateTypeParmDecl *NewTypeParm
2481 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2482 // Check the presence of a default argument here.
2483 if (NewTypeParm->hasDefaultArgument() &&
2485 *this, TPC, NewTypeParm->getLocation(),
2486 NewTypeParm->getDefaultArgument().getSourceRange()))
2487 NewTypeParm->removeDefaultArgument();
2488
2489 // Merge default arguments for template type parameters.
2490 TemplateTypeParmDecl *OldTypeParm
2491 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2492 if (NewTypeParm->isParameterPack()) {
2493 assert(!NewTypeParm->hasDefaultArgument() &&
2494 "Parameter packs can't have a default argument!");
2495 SawParameterPack = true;
2496 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2497 NewTypeParm->hasDefaultArgument() &&
2498 (!SkipBody || !SkipBody->ShouldSkip)) {
2499 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2500 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2501 SawDefaultArgument = true;
2502
2503 if (!OldTypeParm->getOwningModule())
2504 RedundantDefaultArg = true;
2505 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2506 NewTypeParm)) {
2507 InconsistentDefaultArg = true;
2508 PrevModuleName =
2510 }
2511 PreviousDefaultArgLoc = NewDefaultLoc;
2512 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2513 // Merge the default argument from the old declaration to the
2514 // new declaration.
2515 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2516 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2517 } else if (NewTypeParm->hasDefaultArgument()) {
2518 SawDefaultArgument = true;
2519 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2520 } else if (SawDefaultArgument)
2521 MissingDefaultArg = true;
2522 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2523 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2524 // Check for unexpanded parameter packs, except in a template template
2525 // parameter pack, as in those any unexpanded packs should be expanded
2526 // along with the parameter itself.
2528 !NewNonTypeParm->isParameterPack() &&
2529 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2530 NewNonTypeParm->getTypeSourceInfo(),
2532 Invalid = true;
2533 continue;
2534 }
2535
2536 // Check the presence of a default argument here.
2537 if (NewNonTypeParm->hasDefaultArgument() &&
2539 *this, TPC, NewNonTypeParm->getLocation(),
2540 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2541 NewNonTypeParm->removeDefaultArgument();
2542 }
2543
2544 // Merge default arguments for non-type template parameters
2545 NonTypeTemplateParmDecl *OldNonTypeParm
2546 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2547 if (NewNonTypeParm->isParameterPack()) {
2548 assert(!NewNonTypeParm->hasDefaultArgument() &&
2549 "Parameter packs can't have a default argument!");
2550 if (!NewNonTypeParm->isPackExpansion())
2551 SawParameterPack = true;
2552 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2553 NewNonTypeParm->hasDefaultArgument() &&
2554 (!SkipBody || !SkipBody->ShouldSkip)) {
2555 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2556 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2557 SawDefaultArgument = true;
2558 if (!OldNonTypeParm->getOwningModule())
2559 RedundantDefaultArg = true;
2560 else if (!getASTContext().isSameDefaultTemplateArgument(
2561 OldNonTypeParm, NewNonTypeParm)) {
2562 InconsistentDefaultArg = true;
2563 PrevModuleName =
2564 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2565 }
2566 PreviousDefaultArgLoc = NewDefaultLoc;
2567 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2568 // Merge the default argument from the old declaration to the
2569 // new declaration.
2570 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2571 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2572 } else if (NewNonTypeParm->hasDefaultArgument()) {
2573 SawDefaultArgument = true;
2574 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2575 } else if (SawDefaultArgument)
2576 MissingDefaultArg = true;
2577 } else {
2578 TemplateTemplateParmDecl *NewTemplateParm
2579 = cast<TemplateTemplateParmDecl>(*NewParam);
2580
2581 // Check for unexpanded parameter packs, recursively.
2582 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2583 Invalid = true;
2584 continue;
2585 }
2586
2587 // Check the presence of a default argument here.
2588 if (NewTemplateParm->hasDefaultArgument() &&
2590 NewTemplateParm->getLocation(),
2591 NewTemplateParm->getDefaultArgument().getSourceRange()))
2592 NewTemplateParm->removeDefaultArgument();
2593
2594 // Merge default arguments for template template parameters
2595 TemplateTemplateParmDecl *OldTemplateParm
2596 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2597 if (NewTemplateParm->isParameterPack()) {
2598 assert(!NewTemplateParm->hasDefaultArgument() &&
2599 "Parameter packs can't have a default argument!");
2600 if (!NewTemplateParm->isPackExpansion())
2601 SawParameterPack = true;
2602 } else if (OldTemplateParm &&
2603 hasVisibleDefaultArgument(OldTemplateParm) &&
2604 NewTemplateParm->hasDefaultArgument() &&
2605 (!SkipBody || !SkipBody->ShouldSkip)) {
2606 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2607 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2608 SawDefaultArgument = true;
2609 if (!OldTemplateParm->getOwningModule())
2610 RedundantDefaultArg = true;
2611 else if (!getASTContext().isSameDefaultTemplateArgument(
2612 OldTemplateParm, NewTemplateParm)) {
2613 InconsistentDefaultArg = true;
2614 PrevModuleName =
2615 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2616 }
2617 PreviousDefaultArgLoc = NewDefaultLoc;
2618 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2619 // Merge the default argument from the old declaration to the
2620 // new declaration.
2621 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2622 PreviousDefaultArgLoc
2623 = OldTemplateParm->getDefaultArgument().getLocation();
2624 } else if (NewTemplateParm->hasDefaultArgument()) {
2625 SawDefaultArgument = true;
2626 PreviousDefaultArgLoc
2627 = NewTemplateParm->getDefaultArgument().getLocation();
2628 } else if (SawDefaultArgument)
2629 MissingDefaultArg = true;
2630 }
2631
2632 // C++11 [temp.param]p11:
2633 // If a template parameter of a primary class template or alias template
2634 // is a template parameter pack, it shall be the last template parameter.
2635 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2636 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2637 Diag((*NewParam)->getLocation(),
2638 diag::err_template_param_pack_must_be_last_template_parameter);
2639 Invalid = true;
2640 }
2641
2642 // [basic.def.odr]/13:
2643 // There can be more than one definition of a
2644 // ...
2645 // default template argument
2646 // ...
2647 // in a program provided that each definition appears in a different
2648 // translation unit and the definitions satisfy the [same-meaning
2649 // criteria of the ODR].
2650 //
2651 // Simply, the design of modules allows the definition of template default
2652 // argument to be repeated across translation unit. Note that the ODR is
2653 // checked elsewhere. But it is still not allowed to repeat template default
2654 // argument in the same translation unit.
2655 if (RedundantDefaultArg) {
2656 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2657 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2658 Invalid = true;
2659 } else if (InconsistentDefaultArg) {
2660 // We could only diagnose about the case that the OldParam is imported.
2661 // The case NewParam is imported should be handled in ASTReader.
2662 Diag(NewDefaultLoc,
2663 diag::err_template_param_default_arg_inconsistent_redefinition);
2664 Diag(OldDefaultLoc,
2665 diag::note_template_param_prev_default_arg_in_other_module)
2666 << PrevModuleName;
2667 Invalid = true;
2668 } else if (MissingDefaultArg &&
2669 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2670 TPC == TPC_FriendClassTemplate)) {
2671 // C++ 23[temp.param]p14:
2672 // If a template-parameter of a class template, variable template, or
2673 // alias template has a default template argument, each subsequent
2674 // template-parameter shall either have a default template argument
2675 // supplied or be a template parameter pack.
2676 Diag((*NewParam)->getLocation(),
2677 diag::err_template_param_default_arg_missing);
2678 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2679 Invalid = true;
2680 RemoveDefaultArguments = true;
2681 }
2682
2683 // If we have an old template parameter list that we're merging
2684 // in, move on to the next parameter.
2685 if (OldParams)
2686 ++OldParam;
2687 }
2688
2689 // We were missing some default arguments at the end of the list, so remove
2690 // all of the default arguments.
2691 if (RemoveDefaultArguments) {
2692 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2693 NewParamEnd = NewParams->end();
2694 NewParam != NewParamEnd; ++NewParam) {
2695 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2696 TTP->removeDefaultArgument();
2697 else if (NonTypeTemplateParmDecl *NTTP
2698 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2699 NTTP->removeDefaultArgument();
2700 else
2701 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2702 }
2703 }
2704
2705 return Invalid;
2706}
2707
2708namespace {
2709
2710/// A class which looks for a use of a certain level of template
2711/// parameter.
2712struct DependencyChecker : DynamicRecursiveASTVisitor {
2713 unsigned Depth;
2714
2715 // Whether we're looking for a use of a template parameter that makes the
2716 // overall construct type-dependent / a dependent type. This is strictly
2717 // best-effort for now; we may fail to match at all for a dependent type
2718 // in some cases if this is set.
2719 bool IgnoreNonTypeDependent;
2720
2721 bool Match;
2722 SourceLocation MatchLoc;
2723
2724 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2725 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2726 Match(false) {}
2727
2728 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2729 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2730 NamedDecl *ND = Params->getParam(0);
2731 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2732 Depth = PD->getDepth();
2733 } else if (NonTypeTemplateParmDecl *PD =
2734 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2735 Depth = PD->getDepth();
2736 } else {
2737 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2738 }
2739 }
2740
2741 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2742 if (ParmDepth >= Depth) {
2743 Match = true;
2744 MatchLoc = Loc;
2745 return true;
2746 }
2747 return false;
2748 }
2749
2750 bool TraverseStmt(Stmt *S) override {
2751 // Prune out non-type-dependent expressions if requested. This can
2752 // sometimes result in us failing to find a template parameter reference
2753 // (if a value-dependent expression creates a dependent type), but this
2754 // mode is best-effort only.
2755 if (auto *E = dyn_cast_or_null<Expr>(S))
2756 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2757 return true;
2759 }
2760
2761 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2762 if (IgnoreNonTypeDependent && !TL.isNull() &&
2763 !TL.getType()->isDependentType())
2764 return true;
2765 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2766 }
2767
2768 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2769 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2770 }
2771
2772 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2773 // For a best-effort search, keep looking until we find a location.
2774 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2775 }
2776
2777 bool TraverseTemplateName(TemplateName N) override {
2778 if (TemplateTemplateParmDecl *PD =
2779 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2780 if (Matches(PD->getDepth()))
2781 return false;
2783 }
2784
2785 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2786 if (NonTypeTemplateParmDecl *PD =
2787 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2788 if (Matches(PD->getDepth(), E->getExprLoc()))
2789 return false;
2790 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2791 }
2792
2793 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2794 if (Matches(E->getParameter()->getDepth(), E->getExprLoc()))
2795 return false;
2796 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(E);
2797 }
2798
2799 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2800 return TraverseType(T->getReplacementType());
2801 }
2802
2803 bool VisitSubstTemplateTypeParmPackType(
2804 SubstTemplateTypeParmPackType *T) override {
2805 return TraverseTemplateArgument(T->getArgumentPack());
2806 }
2807
2808 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2809 bool TraverseQualifier) override {
2810 // An InjectedClassNameType will never have a dependent template name,
2811 // so no need to traverse it.
2812 return TraverseTemplateArguments(
2813 T->getTemplateArgs(T->getDecl()->getASTContext()));
2814 }
2815};
2816} // end anonymous namespace
2817
2818/// Determines whether a given type depends on the given parameter
2819/// list.
2820static bool
2822 if (!Params->size())
2823 return false;
2824
2825 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2826 Checker.TraverseType(T);
2827 return Checker.Match;
2828}
2829
2830// Find the source range corresponding to the named type in the given
2831// nested-name-specifier, if any.
2833 QualType T,
2834 const CXXScopeSpec &SS) {
2836 for (;;) {
2839 break;
2840 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2841 return NNSLoc.castAsTypeLoc().getSourceRange();
2842 // FIXME: This will always be empty.
2843 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2844 }
2845
2846 return SourceRange();
2847}
2848
2850 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2851 TemplateIdAnnotation *TemplateId,
2852 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2853 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2854 IsMemberSpecialization = false;
2855 Invalid = false;
2856
2857 // The sequence of nested types to which we will match up the template
2858 // parameter lists. We first build this list by starting with the type named
2859 // by the nested-name-specifier and walking out until we run out of types.
2860 SmallVector<QualType, 4> NestedTypes;
2861 QualType T;
2862 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2863 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2864 if (CXXRecordDecl *Record =
2865 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2866 T = Context.getCanonicalTagType(Record);
2867 else
2868 T = QualType(Qualifier.getAsType(), 0);
2869 }
2870
2871 // If we found an explicit specialization that prevents us from needing
2872 // 'template<>' headers, this will be set to the location of that
2873 // explicit specialization.
2874 SourceLocation ExplicitSpecLoc;
2875
2876 while (!T.isNull()) {
2877 NestedTypes.push_back(T);
2878
2879 // Retrieve the parent of a record type.
2880 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2881 // If this type is an explicit specialization, we're done.
2883 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2885 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2886 ExplicitSpecLoc = Spec->getLocation();
2887 break;
2888 }
2889 } else if (Record->getTemplateSpecializationKind()
2891 ExplicitSpecLoc = Record->getLocation();
2892 break;
2893 }
2894
2895 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2896 T = Context.getTypeDeclType(Parent);
2897 else
2898 T = QualType();
2899 continue;
2900 }
2901
2902 if (const TemplateSpecializationType *TST
2903 = T->getAs<TemplateSpecializationType>()) {
2904 TemplateName Name = TST->getTemplateName();
2905 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2906 // Look one step prior in a dependent template specialization type.
2907 if (NestedNameSpecifier NNS = DTS->getQualifier();
2909 T = QualType(NNS.getAsType(), 0);
2910 else
2911 T = QualType();
2912 continue;
2913 }
2914 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2915 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2916 T = Context.getTypeDeclType(Parent);
2917 else
2918 T = QualType();
2919 continue;
2920 }
2921 }
2922
2923 // Look one step prior in a dependent name type.
2924 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2925 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2927 T = QualType(NNS.getAsType(), 0);
2928 else
2929 T = QualType();
2930 continue;
2931 }
2932
2933 // Retrieve the parent of an enumeration type.
2934 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2935 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2936 // check here.
2937 EnumDecl *Enum = EnumT->getDecl();
2938
2939 // Get to the parent type.
2940 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2941 T = Context.getCanonicalTypeDeclType(Parent);
2942 else
2943 T = QualType();
2944 continue;
2945 }
2946
2947 T = QualType();
2948 }
2949 // Reverse the nested types list, since we want to traverse from the outermost
2950 // to the innermost while checking template-parameter-lists.
2951 std::reverse(NestedTypes.begin(), NestedTypes.end());
2952
2953 // C++0x [temp.expl.spec]p17:
2954 // A member or a member template may be nested within many
2955 // enclosing class templates. In an explicit specialization for
2956 // such a member, the member declaration shall be preceded by a
2957 // template<> for each enclosing class template that is
2958 // explicitly specialized.
2959 bool SawNonEmptyTemplateParameterList = false;
2960
2961 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2962 if (SawNonEmptyTemplateParameterList) {
2963 if (!SuppressDiagnostic)
2964 Diag(DeclLoc, diag::err_specialize_member_of_template)
2965 << !Recovery << Range;
2966 Invalid = true;
2967 IsMemberSpecialization = false;
2968 return true;
2969 }
2970
2971 return false;
2972 };
2973
2974 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2975 // Check that we can have an explicit specialization here.
2976 if (CheckExplicitSpecialization(Range, true))
2977 return true;
2978
2979 // We don't have a template header, but we should.
2980 SourceLocation ExpectedTemplateLoc;
2981 if (!ParamLists.empty())
2982 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2983 else
2984 ExpectedTemplateLoc = DeclStartLoc;
2985
2986 if (!SuppressDiagnostic)
2987 Diag(DeclLoc, diag::err_template_spec_needs_header)
2988 << Range
2989 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2990 return false;
2991 };
2992
2993 unsigned ParamIdx = 0;
2994 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2995 ++TypeIdx) {
2996 T = NestedTypes[TypeIdx];
2997
2998 // Whether we expect a 'template<>' header.
2999 bool NeedEmptyTemplateHeader = false;
3000
3001 // Whether we expect a template header with parameters.
3002 bool NeedNonemptyTemplateHeader = false;
3003
3004 // For a dependent type, the set of template parameters that we
3005 // expect to see.
3006 TemplateParameterList *ExpectedTemplateParams = nullptr;
3007
3008 // C++0x [temp.expl.spec]p15:
3009 // A member or a member template may be nested within many enclosing
3010 // class templates. In an explicit specialization for such a member, the
3011 // member declaration shall be preceded by a template<> for each
3012 // enclosing class template that is explicitly specialized.
3013 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3015 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3016 ExpectedTemplateParams = Partial->getTemplateParameters();
3017 NeedNonemptyTemplateHeader = true;
3018 } else if (Record->isDependentType()) {
3019 if (Record->getDescribedClassTemplate()) {
3020 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3021 ->getTemplateParameters();
3022 NeedNonemptyTemplateHeader = true;
3023 }
3024 } else if (ClassTemplateSpecializationDecl *Spec
3025 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3026 // C++0x [temp.expl.spec]p4:
3027 // Members of an explicitly specialized class template are defined
3028 // in the same manner as members of normal classes, and not using
3029 // the template<> syntax.
3030 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3031 NeedEmptyTemplateHeader = true;
3032 else
3033 continue;
3034 } else if (Record->getTemplateSpecializationKind()) {
3035 if (Record->getTemplateSpecializationKind()
3037 TypeIdx == NumTypes - 1)
3038 IsMemberSpecialization = true;
3039
3040 continue;
3041 }
3042 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3043 TemplateName Name = TST->getTemplateName();
3044 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3045 ExpectedTemplateParams = Template->getTemplateParameters();
3046 NeedNonemptyTemplateHeader = true;
3047 } else if (Name.getAsDependentTemplateName()) {
3048 NeedNonemptyTemplateHeader = true;
3049 } else if (Name.getAsDeducedTemplateName()) {
3050 // FIXME: We actually could/should check the template arguments here
3051 // against the corresponding template parameter list.
3052 NeedNonemptyTemplateHeader = false;
3053 }
3054 }
3055
3056 // C++ [temp.expl.spec]p16:
3057 // In an explicit specialization declaration for a member of a class
3058 // template or a member template that appears in namespace scope, the
3059 // member template and some of its enclosing class templates may remain
3060 // unspecialized, except that the declaration shall not explicitly
3061 // specialize a class member template if its enclosing class templates
3062 // are not explicitly specialized as well.
3063 if (ParamIdx < ParamLists.size()) {
3064 if (ParamLists[ParamIdx]->size() == 0) {
3065 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3066 false))
3067 return nullptr;
3068 } else
3069 SawNonEmptyTemplateParameterList = true;
3070 }
3071
3072 if (NeedEmptyTemplateHeader) {
3073 // If we're on the last of the types, and we need a 'template<>' header
3074 // here, then it's a member specialization.
3075 if (TypeIdx == NumTypes - 1)
3076 IsMemberSpecialization = true;
3077
3078 if (ParamIdx < ParamLists.size()) {
3079 if (ParamLists[ParamIdx]->size() > 0) {
3080 // The header has template parameters when it shouldn't. Complain.
3081 if (!SuppressDiagnostic)
3082 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3083 diag::err_template_param_list_matches_nontemplate)
3084 << T
3085 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3086 ParamLists[ParamIdx]->getRAngleLoc())
3088 Invalid = true;
3089 return nullptr;
3090 }
3091
3092 // Consume this template header.
3093 ++ParamIdx;
3094 continue;
3095 }
3096
3097 if (!IsFriend)
3098 if (DiagnoseMissingExplicitSpecialization(
3100 return nullptr;
3101
3102 continue;
3103 }
3104
3105 if (NeedNonemptyTemplateHeader) {
3106 // In friend declarations we can have template-ids which don't
3107 // depend on the corresponding template parameter lists. But
3108 // assume that empty parameter lists are supposed to match this
3109 // template-id.
3110 if (IsFriend && T->isDependentType()) {
3111 if (ParamIdx < ParamLists.size() &&
3113 ExpectedTemplateParams = nullptr;
3114 else
3115 continue;
3116 }
3117
3118 if (ParamIdx < ParamLists.size()) {
3119 // Check the template parameter list, if we can.
3120 if (ExpectedTemplateParams &&
3122 ExpectedTemplateParams,
3123 !SuppressDiagnostic, TPL_TemplateMatch))
3124 Invalid = true;
3125
3126 if (!Invalid &&
3127 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3129 Invalid = true;
3130
3131 ++ParamIdx;
3132 continue;
3133 }
3134
3135 if (!SuppressDiagnostic)
3136 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3137 << T
3139 Invalid = true;
3140 continue;
3141 }
3142 }
3143
3144 // If there were at least as many template-ids as there were template
3145 // parameter lists, then there are no template parameter lists remaining for
3146 // the declaration itself.
3147 if (ParamIdx >= ParamLists.size()) {
3148 if (TemplateId && !IsFriend) {
3149 // We don't have a template header for the declaration itself, but we
3150 // should.
3151 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3152 TemplateId->RAngleLoc));
3153
3154 // Fabricate an empty template parameter list for the invented header.
3156 SourceLocation(), {},
3157 SourceLocation(), nullptr);
3158 }
3159
3160 return nullptr;
3161 }
3162
3163 // If there were too many template parameter lists, complain about that now.
3164 if (ParamIdx < ParamLists.size() - 1) {
3165 bool HasAnyExplicitSpecHeader = false;
3166 bool AllExplicitSpecHeaders = true;
3167 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3168 if (ParamLists[I]->size() == 0)
3169 HasAnyExplicitSpecHeader = true;
3170 else
3171 AllExplicitSpecHeaders = false;
3172 }
3173
3174 if (!SuppressDiagnostic)
3175 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3176 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3177 : diag::err_template_spec_extra_headers)
3178 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3179 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3180
3181 // If there was a specialization somewhere, such that 'template<>' is
3182 // not required, and there were any 'template<>' headers, note where the
3183 // specialization occurred.
3184 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3185 !SuppressDiagnostic)
3186 Diag(ExplicitSpecLoc,
3187 diag::note_explicit_template_spec_does_not_need_header)
3188 << NestedTypes.back();
3189
3190 // We have a template parameter list with no corresponding scope, which
3191 // means that the resulting template declaration can't be instantiated
3192 // properly (we'll end up with dependent nodes when we shouldn't).
3193 if (!AllExplicitSpecHeaders)
3194 Invalid = true;
3195 }
3196
3197 // C++ [temp.expl.spec]p16:
3198 // In an explicit specialization declaration for a member of a class
3199 // template or a member template that ap- pears in namespace scope, the
3200 // member template and some of its enclosing class templates may remain
3201 // unspecialized, except that the declaration shall not explicitly
3202 // specialize a class member template if its en- closing class templates
3203 // are not explicitly specialized as well.
3204 if (ParamLists.back()->size() == 0 &&
3205 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3206 false))
3207 return nullptr;
3208
3209 // Return the last template parameter list, which corresponds to the
3210 // entity being declared.
3211 return ParamLists.back();
3212}
3213
3215 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3216 Diag(Template->getLocation(), diag::note_template_declared_here)
3218 ? 0
3220 ? 1
3222 ? 2
3224 << Template->getDeclName();
3225 return;
3226 }
3227
3229 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3230 IEnd = OST->end();
3231 I != IEnd; ++I)
3232 Diag((*I)->getLocation(), diag::note_template_declared_here)
3233 << 0 << (*I)->getDeclName();
3234
3235 return;
3236 }
3237}
3238
3240 TemplateName BaseTemplate,
3241 SourceLocation TemplateLoc,
3243 auto lookUpCommonType = [&](TemplateArgument T1,
3244 TemplateArgument T2) -> QualType {
3245 // Don't bother looking for other specializations if both types are
3246 // builtins - users aren't allowed to specialize for them
3247 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3248 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3249 {T1, T2});
3250
3254 Args.addArgument(TemplateArgumentLoc(
3255 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3256
3257 EnterExpressionEvaluationContext UnevaluatedContext(
3259 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3261
3262 QualType BaseTemplateInst = S.CheckTemplateIdType(
3263 Keyword, BaseTemplate, TemplateLoc, Args,
3264 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3265
3266 if (SFINAE.hasErrorOccurred())
3267 return QualType();
3268
3269 return BaseTemplateInst;
3270 };
3271
3272 // Note A: For the common_type trait applied to a template parameter pack T of
3273 // types, the member type shall be either defined or not present as follows:
3274 switch (Ts.size()) {
3275
3276 // If sizeof...(T) is zero, there shall be no member type.
3277 case 0:
3278 return QualType();
3279
3280 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3281 // pack T. The member typedef-name type shall denote the same type, if any, as
3282 // common_type_t<T0, T0>; otherwise there shall be no member type.
3283 case 1:
3284 return lookUpCommonType(Ts[0], Ts[0]);
3285
3286 // If sizeof...(T) is two, let the first and second types constituting T be
3287 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3288 // as decay_t<T1> and decay_t<T2>, respectively.
3289 case 2: {
3290 QualType T1 = Ts[0].getAsType();
3291 QualType T2 = Ts[1].getAsType();
3292 QualType D1 = S.BuiltinDecay(T1, {});
3293 QualType D2 = S.BuiltinDecay(T2, {});
3294
3295 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3296 // the same type, if any, as common_type_t<D1, D2>.
3297 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3298 return lookUpCommonType(D1, D2);
3299
3300 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3301 // denotes a valid type, let C denote that type.
3302 {
3303 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3304 EnterExpressionEvaluationContext UnevaluatedContext(
3306 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3308
3309 // false
3311 VK_PRValue);
3312 ExprResult Cond = &CondExpr;
3313
3314 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3315 if (ConstRefQual) {
3316 D1.addConst();
3317 D2.addConst();
3318 }
3319
3320 // declval<D1>()
3321 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3322 ExprResult LHS = &LHSExpr;
3323
3324 // declval<D2>()
3325 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3326 ExprResult RHS = &RHSExpr;
3327
3330
3331 // decltype(false ? declval<D1>() : declval<D2>())
3333 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3334
3335 if (Result.isNull() || SFINAE.hasErrorOccurred())
3336 return QualType();
3337
3338 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3339 return S.BuiltinDecay(Result, TemplateLoc);
3340 };
3341
3342 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3343 return Res;
3344
3345 // Let:
3346 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3347 // COND-RES(X, Y) be
3348 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3349
3350 // C++20 only
3351 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3352 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3353 if (!S.Context.getLangOpts().CPlusPlus20)
3354 return QualType();
3355 return CheckConditionalOperands(true);
3356 }
3357 }
3358
3359 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3360 // denote the first, second, and (pack of) remaining types constituting T. Let
3361 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3362 // a type C, the member typedef-name type shall denote the same type, if any,
3363 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3364 default: {
3365 QualType Result = Ts.front().getAsType();
3366 for (auto T : llvm::drop_begin(Ts)) {
3367 Result = lookUpCommonType(Result, T.getAsType());
3368 if (Result.isNull())
3369 return QualType();
3370 }
3371 return Result;
3372 }
3373 }
3374}
3375
3376static bool isInVkNamespace(const RecordType *RT) {
3377 DeclContext *DC = RT->getDecl()->getDeclContext();
3378 if (!DC)
3379 return false;
3380
3381 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3382 if (!ND)
3383 return false;
3384
3385 return ND->getQualifiedNameAsString() == "hlsl::vk";
3386}
3387
3388static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3389 QualType OperandArg,
3390 SourceLocation Loc) {
3391 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3392 bool Literal = false;
3393 SourceLocation LiteralLoc;
3394 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3395 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3396 assert(SpecDecl);
3397
3398 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3399 QualType ConstantType = LiteralArgs[0].getAsType();
3400 RT = ConstantType->getAsCanonical<RecordType>();
3401 Literal = true;
3402 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3403 }
3404
3405 if (RT && isInVkNamespace(RT) &&
3406 RT->getDecl()->getName() == "integral_constant") {
3407 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3408 assert(SpecDecl);
3409
3410 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3411
3412 QualType ConstantType = ConstantArgs[0].getAsType();
3413 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3414
3415 if (Literal)
3416 return SpirvOperand::createLiteral(Value);
3417 return SpirvOperand::createConstant(ConstantType, Value);
3418 } else if (Literal) {
3419 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3420 return SpirvOperand();
3421 }
3422 }
3423 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3424 diag::err_call_incomplete_argument))
3425 return SpirvOperand();
3426 return SpirvOperand::createType(OperandArg);
3427}
3428
3431 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3432 TemplateArgumentListInfo &TemplateArgs) {
3433 ASTContext &Context = SemaRef.getASTContext();
3434
3435 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3436 "Builtin template arguments do not match its parameters");
3437
3438 switch (BTD->getBuiltinTemplateKind()) {
3439 case BTK__make_integer_seq: {
3440 // Specializations of __make_integer_seq<S, T, N> are treated like
3441 // S<T, 0, ..., N-1>.
3442
3443 QualType OrigType = Converted[1].getAsType();
3444 // C++14 [inteseq.intseq]p1:
3445 // T shall be an integer type.
3446 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3447 SemaRef.Diag(TemplateArgs[1].getLocation(),
3448 diag::err_integer_sequence_integral_element_type);
3449 return QualType();
3450 }
3451
3452 TemplateArgument NumArgsArg = Converted[2];
3453 if (NumArgsArg.isDependent())
3454 return QualType();
3455
3456 TemplateArgumentListInfo SyntheticTemplateArgs;
3457 // The type argument, wrapped in substitution sugar, gets reused as the
3458 // first template argument in the synthetic template argument list.
3459 SyntheticTemplateArgs.addArgument(
3462 OrigType, TemplateArgs[1].getLocation())));
3463
3464 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3465 // Expand N into 0 ... N-1.
3466 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3467 I < NumArgs; ++I) {
3468 TemplateArgument TA(Context, I, OrigType);
3469 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3470 TA, OrigType, TemplateArgs[2].getLocation()));
3471 }
3472 } else {
3473 // C++14 [inteseq.make]p1:
3474 // If N is negative the program is ill-formed.
3475 SemaRef.Diag(TemplateArgs[2].getLocation(),
3476 diag::err_integer_sequence_negative_length);
3477 return QualType();
3478 }
3479
3480 // The first template argument will be reused as the template decl that
3481 // our synthetic template arguments will be applied to.
3482 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3483 TemplateLoc, SyntheticTemplateArgs,
3484 /*Scope=*/nullptr,
3485 /*ForNestedNameSpecifier=*/false);
3486 }
3487
3488 case BTK__type_pack_element: {
3489 // Specializations of
3490 // __type_pack_element<Index, T_1, ..., T_N>
3491 // are treated like T_Index.
3492 assert(Converted.size() == 2 &&
3493 "__type_pack_element should be given an index and a parameter pack");
3494
3495 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3496 if (IndexArg.isDependent() || Ts.isDependent())
3497 return QualType();
3498
3499 llvm::APSInt Index = IndexArg.getAsIntegral();
3500 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3501 "type std::size_t, and hence be non-negative");
3502 // If the Index is out of bounds, the program is ill-formed.
3503 if (Index >= Ts.pack_size()) {
3504 SemaRef.Diag(TemplateArgs[0].getLocation(),
3505 diag::err_type_pack_element_out_of_bounds);
3506 return QualType();
3507 }
3508
3509 // We simply return the type at index `Index`.
3510 int64_t N = Index.getExtValue();
3511 return Ts.getPackAsArray()[N].getAsType();
3512 }
3513
3514 case BTK__builtin_common_type: {
3515 assert(Converted.size() == 4);
3516 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3517 return QualType();
3518
3519 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3520 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3521 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3522 TemplateLoc, Ts);
3523 !CT.isNull()) {
3527 CT, TemplateArgs[1].getLocation())));
3528 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3529 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3530 TAs, /*Scope=*/nullptr,
3531 /*ForNestedNameSpecifier=*/false);
3532 }
3533 QualType HasNoTypeMember = Converted[2].getAsType();
3534 return HasNoTypeMember;
3535 }
3536
3537 case BTK__hlsl_spirv_type: {
3538 assert(Converted.size() == 4);
3539
3540 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3541 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3542 }
3543
3544 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3545 return QualType();
3546
3547 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3548 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3549 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3550
3551 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3552
3554
3555 for (auto &OperandTA : OperandArgs) {
3556 QualType OperandArg = OperandTA.getAsType();
3557 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3558 TemplateArgs[3].getLocation());
3559 if (!Operand.isValid())
3560 return QualType();
3561 Operands.push_back(Operand);
3562 }
3563
3564 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3565 }
3566 case BTK__builtin_dedup_pack: {
3567 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3568 "a parameter pack");
3569 TemplateArgument Ts = Converted[0];
3570 // Delay the computation until we can compute the final result. We choose
3571 // not to remove the duplicates upfront before substitution to keep the code
3572 // simple.
3573 if (Ts.isDependent())
3574 return QualType();
3575 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3577 llvm::SmallDenseSet<QualType> Seen;
3578 // Synthesize a new template argument list, removing duplicates.
3579 for (auto T : Ts.getPackAsArray()) {
3580 assert(T.getKind() == clang::TemplateArgument::Type);
3581 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3582 continue;
3583 OutArgs.push_back(T);
3584 }
3585 return Context.getSubstBuiltinTemplatePack(
3586 TemplateArgument::CreatePackCopy(Context, OutArgs));
3587 }
3588 }
3589 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3590}
3591
3592/// Determine whether this alias template is "enable_if_t".
3593/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3595 return AliasTemplate->getName() == "enable_if_t" ||
3596 AliasTemplate->getName() == "__enable_if_t";
3597}
3598
3599/// Collect all of the separable terms in the given condition, which
3600/// might be a conjunction.
3601///
3602/// FIXME: The right answer is to convert the logical expression into
3603/// disjunctive normal form, so we can find the first failed term
3604/// within each possible clause.
3605static void collectConjunctionTerms(Expr *Clause,
3606 SmallVectorImpl<Expr *> &Terms) {
3607 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3608 if (BinOp->getOpcode() == BO_LAnd) {
3609 collectConjunctionTerms(BinOp->getLHS(), Terms);
3610 collectConjunctionTerms(BinOp->getRHS(), Terms);
3611 return;
3612 }
3613 }
3614
3615 Terms.push_back(Clause);
3616}
3617
3618// The ranges-v3 library uses an odd pattern of a top-level "||" with
3619// a left-hand side that is value-dependent but never true. Identify
3620// the idiom and ignore that term.
3622 // Top-level '||'.
3623 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3624 if (!BinOp) return Cond;
3625
3626 if (BinOp->getOpcode() != BO_LOr) return Cond;
3627
3628 // With an inner '==' that has a literal on the right-hand side.
3629 Expr *LHS = BinOp->getLHS();
3630 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3631 if (!InnerBinOp) return Cond;
3632
3633 if (InnerBinOp->getOpcode() != BO_EQ ||
3634 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3635 return Cond;
3636
3637 // If the inner binary operation came from a macro expansion named
3638 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3639 // of the '||', which is the real, user-provided condition.
3640 SourceLocation Loc = InnerBinOp->getExprLoc();
3641 if (!Loc.isMacroID()) return Cond;
3642
3643 StringRef MacroName = PP.getImmediateMacroName(Loc);
3644 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3645 return BinOp->getRHS();
3646
3647 return Cond;
3648}
3649
3650namespace {
3651
3652// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3653// within failing boolean expression, such as substituting template parameters
3654// for actual types.
3655class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3656public:
3657 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3658 : Policy(P) {}
3659
3660 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3661 const auto *DR = dyn_cast<DeclRefExpr>(E);
3662 if (DR && DR->getQualifier()) {
3663 // If this is a qualified name, expand the template arguments in nested
3664 // qualifiers.
3665 DR->getQualifier().print(OS, Policy, true);
3666 // Then print the decl itself.
3667 const ValueDecl *VD = DR->getDecl();
3668 OS << *VD;
3669 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3670 // This is a template variable, print the expanded template arguments.
3671 printTemplateArgumentList(
3672 OS, IV->getTemplateArgs().asArray(), Policy,
3673 IV->getSpecializedTemplate()->getTemplateParameters());
3674 }
3675 return true;
3676 }
3677 return false;
3678 }
3679
3680private:
3681 const PrintingPolicy Policy;
3682};
3683
3684} // end anonymous namespace
3685
3686std::pair<Expr *, std::string>
3689
3690 // Separate out all of the terms in a conjunction.
3693
3694 // Determine which term failed.
3695 Expr *FailedCond = nullptr;
3696 for (Expr *Term : Terms) {
3697 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3698
3699 // Literals are uninteresting.
3700 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3701 isa<IntegerLiteral>(TermAsWritten))
3702 continue;
3703
3704 // The initialization of the parameter from the argument is
3705 // a constant-evaluated context.
3708
3709 bool Succeeded;
3710 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3711 !Succeeded) {
3712 FailedCond = TermAsWritten;
3713 break;
3714 }
3715 }
3716 if (!FailedCond)
3717 FailedCond = Cond->IgnoreParenImpCasts();
3718
3719 std::string Description;
3720 {
3721 llvm::raw_string_ostream Out(Description);
3723 Policy.PrintAsCanonical = true;
3724 FailedBooleanConditionPrinterHelper Helper(Policy);
3725 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3726 }
3727 return { FailedCond, Description };
3728}
3729
3730static TemplateName
3732 const AssumedTemplateStorage *ATN,
3733 SourceLocation NameLoc) {
3734 // We assumed this undeclared identifier to be an (ADL-only) function
3735 // template name, but it was used in a context where a type was required.
3736 // Try to typo-correct it now.
3737 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3738 struct CandidateCallback : CorrectionCandidateCallback {
3739 bool ValidateCandidate(const TypoCorrection &TC) override {
3740 return TC.getCorrectionDecl() &&
3742 }
3743 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3744 return std::make_unique<CandidateCallback>(*this);
3745 }
3746 } FilterCCC;
3747
3748 TypoCorrection Corrected =
3749 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3750 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3751 if (Corrected && Corrected.getFoundDecl()) {
3752 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3753 << ATN->getDeclName());
3755 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3757 }
3758
3759 return TemplateName();
3760}
3761
3763 TemplateName Name,
3764 SourceLocation TemplateLoc,
3765 TemplateArgumentListInfo &TemplateArgs,
3766 Scope *Scope, bool ForNestedNameSpecifier) {
3767 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3768
3769 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3770 if (!Template) {
3771 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3772 Template = S->getParameterPack();
3773 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3774 if (DTN->getName().getIdentifier())
3775 // When building a template-id where the template-name is dependent,
3776 // assume the template is a type template. Either our assumption is
3777 // correct, or the code is ill-formed and will be diagnosed when the
3778 // dependent name is substituted.
3779 return Context.getTemplateSpecializationType(Keyword, Name,
3780 TemplateArgs.arguments(),
3781 /*CanonicalArgs=*/{});
3782 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3784 *this, Scope, ATN, TemplateLoc);
3785 CorrectedName.isNull()) {
3786 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3787 return QualType();
3788 } else {
3789 Name = CorrectedName;
3790 Template = Name.getAsTemplateDecl();
3791 }
3792 }
3793 }
3794 if (!Template ||
3796 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3797 if (ForNestedNameSpecifier)
3798 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3799 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3800 else
3801 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3803 return QualType();
3804 }
3805
3806 // Check that the template argument list is well-formed for this
3807 // template.
3809 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3810 DefaultArgs, /*PartialTemplateArgs=*/false,
3811 CTAI,
3812 /*UpdateArgsWithConversions=*/true))
3813 return QualType();
3814
3815 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3816 // and there are no diagnsotics currently implemented for TemplateDecls,
3817 // so avoid doing it for now.
3818 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3819
3820 QualType CanonType;
3821
3823 // We might have a substituted template template parameter pack. If so,
3824 // build a template specialization type for it.
3826 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3827
3828 // C++0x [dcl.type.elab]p2:
3829 // If the identifier resolves to a typedef-name or the simple-template-id
3830 // resolves to an alias template specialization, the
3831 // elaborated-type-specifier is ill-formed.
3834 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3837 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3838 }
3839
3840 // Find the canonical type for this type alias template specialization.
3841 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3842
3843 // Diagnose uses of the pattern of this template.
3844 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3845 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3846
3847 if (Pattern->isInvalidDecl())
3848 return QualType();
3849
3850 // Only substitute for the innermost template argument list.
3851 MultiLevelTemplateArgumentList TemplateArgLists;
3853 /*Final=*/true);
3854 TemplateArgLists.addOuterRetainedLevels(
3855 AliasTemplate->getTemplateParameters()->getDepth());
3856
3858
3859 // FIXME: The TemplateArgs passed here are not used for the context note,
3860 // nor they should, because this note will be pointing to the specialization
3861 // anyway. These arguments are needed for a hack for instantiating lambdas
3862 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3863 // arguments will be used for collating the template arguments needed to
3864 // instantiate the lambda.
3865 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3866 /*Entity=*/AliasTemplate,
3867 /*TemplateArgs=*/CTAI.SugaredConverted);
3868 if (Inst.isInvalid())
3869 return QualType();
3870
3871 std::optional<ContextRAII> SavedContext;
3872 if (!AliasTemplate->getDeclContext()->isFileContext())
3873 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3874
3875 CanonType =
3876 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3877 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3878 if (CanonType.isNull()) {
3879 // If this was enable_if and we failed to find the nested type
3880 // within enable_if in a SFINAE context, dig out the specific
3881 // enable_if condition that failed and present that instead.
3883 if (SFINAETrap *Trap = getSFINAEContext();
3884 TemplateDeductionInfo *DeductionInfo =
3885 Trap ? Trap->getDeductionInfo() : nullptr) {
3886 if (DeductionInfo->hasSFINAEDiagnostic() &&
3887 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3888 diag::err_typename_nested_not_found_enable_if &&
3889 TemplateArgs[0].getArgument().getKind() ==
3891 Expr *FailedCond;
3892 std::string FailedDescription;
3893 std::tie(FailedCond, FailedDescription) =
3894 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3895
3896 // Remove the old SFINAE diagnostic.
3897 PartialDiagnosticAt OldDiag =
3899 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3900
3901 // Add a new SFINAE diagnostic specifying which condition
3902 // failed.
3903 DeductionInfo->addSFINAEDiagnostic(
3904 OldDiag.first,
3905 PDiag(diag::err_typename_nested_not_found_requirement)
3906 << FailedDescription << FailedCond->getSourceRange());
3907 }
3908 }
3909 }
3910
3911 return QualType();
3912 }
3913 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3914 CanonType = checkBuiltinTemplateIdType(
3915 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3916 } else if (Name.isDependent() ||
3917 TemplateSpecializationType::anyDependentTemplateArguments(
3918 TemplateArgs, CTAI.CanonicalConverted)) {
3919 // This class template specialization is a dependent
3920 // type. Therefore, its canonical type is another class template
3921 // specialization type that contains all of the converted
3922 // arguments in canonical form. This ensures that, e.g., A<T> and
3923 // A<T, T> have identical types when A is declared as:
3924 //
3925 // template<typename T, typename U = T> struct A;
3926 CanonType = Context.getCanonicalTemplateSpecializationType(
3928 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3929 CTAI.CanonicalConverted);
3930 assert(CanonType->isCanonicalUnqualified());
3931
3932 // This might work out to be a current instantiation, in which
3933 // case the canonical type needs to be the InjectedClassNameType.
3934 //
3935 // TODO: in theory this could be a simple hashtable lookup; most
3936 // changes to CurContext don't change the set of current
3937 // instantiations.
3939 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3940 // If we get out to a namespace, we're done.
3941 if (Ctx->isFileContext()) break;
3942
3943 // If this isn't a record, keep looking.
3944 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3945 if (!Record) continue;
3946
3947 // Look for one of the two cases with InjectedClassNameTypes
3948 // and check whether it's the same template.
3950 !Record->getDescribedClassTemplate())
3951 continue;
3952
3953 // Fetch the injected class name type and check whether its
3954 // injected type is equal to the type we just built.
3955 CanQualType ICNT = Context.getCanonicalTagType(Record);
3956 CanQualType Injected =
3957 Record->getCanonicalTemplateSpecializationType(Context);
3958
3959 if (CanonType != Injected)
3960 continue;
3961
3962 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3963 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3964
3965 // If so, the canonical type of this TST is the injected
3966 // class name type of the record we just found.
3967 CanonType = ICNT;
3968 break;
3969 }
3970 }
3971 } else if (ClassTemplateDecl *ClassTemplate =
3972 dyn_cast<ClassTemplateDecl>(Template)) {
3973 // Find the class template specialization declaration that
3974 // corresponds to these arguments.
3975 void *InsertPos = nullptr;
3977 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3978 if (!Decl) {
3979 // This is the first time we have referenced this class template
3980 // specialization. Create the canonical declaration and add it to
3981 // the set of specializations.
3983 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3984 ClassTemplate->getDeclContext(),
3985 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3986 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3987 CTAI.StrictPackMatch, nullptr);
3988 ClassTemplate->AddSpecialization(Decl, InsertPos);
3989 if (ClassTemplate->isOutOfLine())
3990 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3991 }
3992
3993 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3994 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3995 NonSFINAEContext _(*this);
3996 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3997 if (!Inst.isInvalid()) {
3999 CTAI.CanonicalConverted,
4000 /*Final=*/false);
4001 InstantiateAttrsForDecl(TemplateArgLists,
4002 ClassTemplate->getTemplatedDecl(), Decl);
4003 }
4004 }
4005
4006 // Diagnose uses of this specialization.
4007 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4008 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4009
4010 CanonType = Context.getCanonicalTagType(Decl);
4011 assert(isa<RecordType>(CanonType) &&
4012 "type of non-dependent specialization is not a RecordType");
4013 } else {
4014 llvm_unreachable("Unhandled template kind");
4015 }
4016
4017 // Build the fully-sugared type for this class template
4018 // specialization, which refers back to the class template
4019 // specialization we created or found.
4020 return Context.getTemplateSpecializationType(
4021 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4022 CanonType);
4023}
4024
4026 TemplateNameKind &TNK,
4027 SourceLocation NameLoc,
4028 IdentifierInfo *&II) {
4029 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4030
4031 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4032 assert(ATN && "not an assumed template name");
4033 II = ATN->getDeclName().getAsIdentifierInfo();
4034
4035 if (TemplateName Name =
4036 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4037 !Name.isNull()) {
4038 // Resolved to a type template name.
4039 ParsedName = TemplateTy::make(Name);
4040 TNK = TNK_Type_template;
4041 }
4042}
4043
4045 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4046 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4047 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4048 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4049 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4050 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4051 ImplicitTypenameContext AllowImplicitTypename) {
4052 if (SS.isInvalid())
4053 return true;
4054
4055 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4056 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4057
4058 // C++ [temp.res]p3:
4059 // A qualified-id that refers to a type and in which the
4060 // nested-name-specifier depends on a template-parameter (14.6.2)
4061 // shall be prefixed by the keyword typename to indicate that the
4062 // qualified-id denotes a type, forming an
4063 // elaborated-type-specifier (7.1.5.3).
4064 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4065 // C++2a relaxes some of those restrictions in [temp.res]p5.
4066 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4067 SS.getScopeRep(), TemplateII);
4069 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4070 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4071 << NNS;
4072 if (!getLangOpts().CPlusPlus20)
4073 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4074 } else
4075 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4076
4077 // FIXME: This is not quite correct recovery as we don't transform SS
4078 // into the corresponding dependent form (and we don't diagnose missing
4079 // 'template' keywords within SS as a result).
4080 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4081 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4082 TemplateArgsIn, RAngleLoc);
4083 }
4084
4085 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4086 // it's not actually allowed to be used as a type in most cases. Because
4087 // we annotate it before we know whether it's valid, we have to check for
4088 // this case here.
4089 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4090 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4091 Diag(TemplateIILoc,
4092 TemplateKWLoc.isInvalid()
4093 ? diag::err_out_of_line_qualified_id_type_names_constructor
4094 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4095 << TemplateII << 0 /*injected-class-name used as template name*/
4096 << 1 /*if any keyword was present, it was 'template'*/;
4097 }
4098 }
4099
4100 // Translate the parser's template argument list in our AST format.
4101 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4102 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4103
4105 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4106 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4107 if (SpecTy.isNull())
4108 return true;
4109
4110 // Build type-source information.
4111 TypeLocBuilder TLB;
4112 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4113 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4114 TemplateIILoc, TemplateArgs);
4115 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4116}
4117
4119 TypeSpecifierType TagSpec,
4120 SourceLocation TagLoc,
4121 CXXScopeSpec &SS,
4122 SourceLocation TemplateKWLoc,
4123 TemplateTy TemplateD,
4124 SourceLocation TemplateLoc,
4125 SourceLocation LAngleLoc,
4126 ASTTemplateArgsPtr TemplateArgsIn,
4127 SourceLocation RAngleLoc) {
4128 if (SS.isInvalid())
4129 return TypeResult(true);
4130
4131 // Translate the parser's template argument list in our AST format.
4132 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4133 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4134
4135 // Determine the tag kind
4139
4141 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4142 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4143 if (Result.isNull())
4144 return TypeResult(true);
4145
4146 // Check the tag kind
4147 if (const RecordType *RT = Result->getAs<RecordType>()) {
4148 RecordDecl *D = RT->getDecl();
4149
4150 IdentifierInfo *Id = D->getIdentifier();
4151 assert(Id && "templated class must have an identifier");
4152
4154 TagLoc, Id)) {
4155 Diag(TagLoc, diag::err_use_with_wrong_tag)
4156 << Result
4158 Diag(D->getLocation(), diag::note_previous_use);
4159 }
4160 }
4161
4162 // Provide source-location information for the template specialization.
4163 TypeLocBuilder TLB;
4165 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4166 TemplateArgs);
4168}
4169
4170static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4171 NamedDecl *PrevDecl,
4172 SourceLocation Loc,
4174
4176
4178 unsigned Depth,
4179 unsigned Index) {
4180 switch (Arg.getKind()) {
4188 return false;
4189
4191 QualType Type = Arg.getAsType();
4192 const TemplateTypeParmType *TPT =
4193 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4194 return TPT && !Type.hasQualifiers() &&
4195 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4196 }
4197
4199 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4200 if (!DRE || !DRE->getDecl())
4201 return false;
4202 const NonTypeTemplateParmDecl *NTTP =
4203 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4204 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4205 }
4206
4208 const TemplateTemplateParmDecl *TTP =
4209 dyn_cast_or_null<TemplateTemplateParmDecl>(
4211 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4212 }
4213 llvm_unreachable("unexpected kind of template argument");
4214}
4215
4217 TemplateParameterList *SpecParams,
4219 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4220 return false;
4221
4222 unsigned Depth = Params->getDepth();
4223
4224 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4225 TemplateArgument Arg = Args[I];
4226
4227 // If the parameter is a pack expansion, the argument must be a pack
4228 // whose only element is a pack expansion.
4229 if (Params->getParam(I)->isParameterPack()) {
4230 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4231 !Arg.pack_begin()->isPackExpansion())
4232 return false;
4233 Arg = Arg.pack_begin()->getPackExpansionPattern();
4234 }
4235
4236 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4237 return false;
4238
4239 // For NTTPs further specialization is allowed via deduced types, so
4240 // we need to make sure to only reject here if primary template and
4241 // specialization use the same type for the NTTP.
4242 if (auto *SpecNTTP =
4243 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4244 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4245 if (!NTTP || NTTP->getType().getCanonicalType() !=
4246 SpecNTTP->getType().getCanonicalType())
4247 return false;
4248 }
4249 }
4250
4251 return true;
4252}
4253
4254template<typename PartialSpecDecl>
4255static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4256 if (Partial->getDeclContext()->isDependentContext())
4257 return;
4258
4259 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4260 // for non-substitution-failure issues?
4261 TemplateDeductionInfo Info(Partial->getLocation());
4262 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4263 return;
4264
4265 auto *Template = Partial->getSpecializedTemplate();
4266 S.Diag(Partial->getLocation(),
4267 diag::ext_partial_spec_not_more_specialized_than_primary)
4269
4270 if (Info.hasSFINAEDiagnostic()) {
4274 SmallString<128> SFINAEArgString;
4275 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4276 S.Diag(Diag.first,
4277 diag::note_partial_spec_not_more_specialized_than_primary)
4278 << SFINAEArgString;
4279 }
4280
4282 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4283 Template->getAssociatedConstraints(TemplateAC);
4284 Partial->getAssociatedConstraints(PartialAC);
4286 TemplateAC);
4287}
4288
4289static void
4291 const llvm::SmallBitVector &DeducibleParams) {
4292 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4293 if (!DeducibleParams[I]) {
4294 NamedDecl *Param = TemplateParams->getParam(I);
4295 if (Param->getDeclName())
4296 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4297 << Param->getDeclName();
4298 else
4299 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4300 << "(anonymous)";
4301 }
4302 }
4303}
4304
4305
4306template<typename PartialSpecDecl>
4308 PartialSpecDecl *Partial) {
4309 // C++1z [temp.class.spec]p8: (DR1495)
4310 // - The specialization shall be more specialized than the primary
4311 // template (14.5.5.2).
4313
4314 // C++ [temp.class.spec]p8: (DR1315)
4315 // - Each template-parameter shall appear at least once in the
4316 // template-id outside a non-deduced context.
4317 // C++1z [temp.class.spec.match]p3 (P0127R2)
4318 // If the template arguments of a partial specialization cannot be
4319 // deduced because of the structure of its template-parameter-list
4320 // and the template-id, the program is ill-formed.
4321 auto *TemplateParams = Partial->getTemplateParameters();
4322 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4323 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4324 TemplateParams->getDepth(), DeducibleParams);
4325
4326 if (!DeducibleParams.all()) {
4327 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4328 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4330 << (NumNonDeducible > 1)
4331 << SourceRange(Partial->getLocation(),
4332 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4333 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4334 }
4335}
4336
4341
4346
4348 // C++1z [temp.param]p11:
4349 // A template parameter of a deduction guide template that does not have a
4350 // default-argument shall be deducible from the parameter-type-list of the
4351 // deduction guide template.
4352 auto *TemplateParams = TD->getTemplateParameters();
4353 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4354 MarkDeducedTemplateParameters(TD, DeducibleParams);
4355 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4356 // A parameter pack is deducible (to an empty pack).
4357 auto *Param = TemplateParams->getParam(I);
4358 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4359 DeducibleParams[I] = true;
4360 }
4361
4362 if (!DeducibleParams.all()) {
4363 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4364 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4365 << (NumNonDeducible > 1);
4366 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4367 }
4368}
4369
4372 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4374 // D must be variable template id.
4376 "Variable template specialization is declared with a template id.");
4377
4378 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4379 TemplateArgumentListInfo TemplateArgs =
4380 makeTemplateArgumentListInfo(*this, *TemplateId);
4381 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4382 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4383 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4384
4385 TemplateName Name = TemplateId->Template.get();
4386
4387 // The template-id must name a variable template.
4389 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4390 if (!VarTemplate) {
4391 NamedDecl *FnTemplate;
4392 if (auto *OTS = Name.getAsOverloadedTemplate())
4393 FnTemplate = *OTS->begin();
4394 else
4395 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4396 if (FnTemplate)
4397 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4398 << FnTemplate->getDeclName();
4399 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4401 }
4402
4403 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4404 auto Message = DSA->getMessage();
4405 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4406 << VarTemplate << !Message.empty() << Message;
4407 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4408 }
4409
4410 // Check for unexpanded parameter packs in any of the template arguments.
4411 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4412 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4416 return true;
4417
4418 // Check that the template argument list is well-formed for this
4419 // template.
4421 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4422 /*DefaultArgs=*/{},
4423 /*PartialTemplateArgs=*/false, CTAI,
4424 /*UpdateArgsWithConversions=*/true))
4425 return true;
4426
4427 // Find the variable template (partial) specialization declaration that
4428 // corresponds to these arguments.
4431 TemplateArgs.size(),
4432 CTAI.CanonicalConverted))
4433 return true;
4434
4435 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4436 // we also do them during instantiation.
4437 if (!Name.isDependent() &&
4438 !TemplateSpecializationType::anyDependentTemplateArguments(
4439 TemplateArgs, CTAI.CanonicalConverted)) {
4440 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4441 << VarTemplate->getDeclName();
4443 }
4444
4445 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4446 TemplateParams, CTAI.CanonicalConverted) &&
4447 (!Context.getLangOpts().CPlusPlus20 ||
4448 !TemplateParams->hasAssociatedConstraints())) {
4449 // C++ [temp.class.spec]p9b3:
4450 //
4451 // -- The argument list of the specialization shall not be identical
4452 // to the implicit argument list of the primary template.
4453 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4454 << /*variable template*/ 1
4455 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4456 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4457 // FIXME: Recover from this by treating the declaration as a
4458 // redeclaration of the primary template.
4459 return true;
4460 }
4461 }
4462
4463 void *InsertPos = nullptr;
4464 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4465
4467 PrevDecl = VarTemplate->findPartialSpecialization(
4468 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4469 else
4470 PrevDecl =
4471 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4472
4474
4475 // Check whether we can declare a variable template specialization in
4476 // the current scope.
4477 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4478 TemplateNameLoc,
4480 return true;
4481
4482 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4483 // Since the only prior variable template specialization with these
4484 // arguments was referenced but not declared, reuse that
4485 // declaration node as our own, updating its source location and
4486 // the list of outer template parameters to reflect our new declaration.
4487 Specialization = PrevDecl;
4488 Specialization->setLocation(TemplateNameLoc);
4489 PrevDecl = nullptr;
4490 } else if (IsPartialSpecialization) {
4491 // Create a new class template partial specialization declaration node.
4493 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4496 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4497 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4498 SC, CTAI.CanonicalConverted);
4499 Partial->setTemplateArgsAsWritten(TemplateArgs);
4500
4501 if (!PrevPartial)
4502 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4503 Specialization = Partial;
4504
4506 } else {
4507 // Create a new class template specialization declaration node for
4508 // this explicit specialization or friend declaration.
4510 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4511 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4512 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4513
4514 if (!PrevDecl)
4515 VarTemplate->AddSpecialization(Specialization, InsertPos);
4516 }
4517
4518 // C++ [temp.expl.spec]p6:
4519 // If a template, a member template or the member of a class template is
4520 // explicitly specialized then that specialization shall be declared
4521 // before the first use of that specialization that would cause an implicit
4522 // instantiation to take place, in every translation unit in which such a
4523 // use occurs; no diagnostic is required.
4524 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4525 bool Okay = false;
4526 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4527 // Is there any previous explicit specialization declaration?
4529 Okay = true;
4530 break;
4531 }
4532 }
4533
4534 if (!Okay) {
4535 SourceRange Range(TemplateNameLoc, RAngleLoc);
4536 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4537 << Name << Range;
4538
4539 Diag(PrevDecl->getPointOfInstantiation(),
4540 diag::note_instantiation_required_here)
4541 << (PrevDecl->getTemplateSpecializationKind() !=
4543 return true;
4544 }
4545 }
4546
4547 Specialization->setLexicalDeclContext(CurContext);
4548
4549 // Add the specialization into its lexical context, so that it can
4550 // be seen when iterating through the list of declarations in that
4551 // context. However, specializations are not found by name lookup.
4552 CurContext->addDecl(Specialization);
4553
4554 // Note that this is an explicit specialization.
4555 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4556
4557 Previous.clear();
4558 if (PrevDecl)
4559 Previous.addDecl(PrevDecl);
4560 else if (Specialization->isStaticDataMember() &&
4561 Specialization->isOutOfLine())
4562 Specialization->setAccess(VarTemplate->getAccess());
4563
4564 return Specialization;
4565}
4566
4567namespace {
4568/// A partial specialization whose template arguments have matched
4569/// a given template-id.
4570struct PartialSpecMatchResult {
4573};
4574
4575// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4576// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4577static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4578 if (Var->getName() != "format_kind" ||
4579 !Var->getDeclContext()->isStdNamespace())
4580 return false;
4581
4582 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4583 // release in which users can access std::format_kind.
4584 // We can use 20250520 as the final date, see the following commits.
4585 // GCC releases/gcc-15 branch:
4586 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4587 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4588 // GCC master branch:
4589 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4590 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4591 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4592}
4593} // end anonymous namespace
4594
4597 SourceLocation TemplateNameLoc,
4598 const TemplateArgumentListInfo &TemplateArgs,
4599 bool SetWrittenArgs) {
4600 assert(Template && "A variable template id without template?");
4601
4602 // Check that the template argument list is well-formed for this template.
4605 Template, TemplateNameLoc,
4606 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4607 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4608 /*UpdateArgsWithConversions=*/true))
4609 return true;
4610
4611 // Produce a placeholder value if the specialization is dependent.
4612 if (Template->getDeclContext()->isDependentContext() ||
4613 TemplateSpecializationType::anyDependentTemplateArguments(
4614 TemplateArgs, CTAI.CanonicalConverted)) {
4615 if (ParsingInitForAutoVars.empty())
4616 return DeclResult();
4617
4618 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4619 const TemplateArgument &Arg2) {
4620 return Context.isSameTemplateArgument(Arg1, Arg2);
4621 };
4622
4623 if (VarDecl *Var = Template->getTemplatedDecl();
4624 ParsingInitForAutoVars.count(Var) &&
4625 // See comments on this function definition
4626 !IsLibstdcxxStdFormatKind(PP, Var) &&
4627 llvm::equal(
4628 CTAI.CanonicalConverted,
4629 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4630 IsSameTemplateArg)) {
4631 Diag(TemplateNameLoc,
4632 diag::err_auto_variable_cannot_appear_in_own_initializer)
4633 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4634 return true;
4635 }
4636
4638 Template->getPartialSpecializations(PartialSpecs);
4639 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4640 if (ParsingInitForAutoVars.count(Partial) &&
4641 llvm::equal(CTAI.CanonicalConverted,
4642 Partial->getTemplateArgs().asArray(),
4643 IsSameTemplateArg)) {
4644 Diag(TemplateNameLoc,
4645 diag::err_auto_variable_cannot_appear_in_own_initializer)
4646 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4647 << Partial->getType();
4648 return true;
4649 }
4650
4651 return DeclResult();
4652 }
4653
4654 // Find the variable template specialization declaration that
4655 // corresponds to these arguments.
4656 void *InsertPos = nullptr;
4658 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4659 checkSpecializationReachability(TemplateNameLoc, Spec);
4660 if (Spec->getType()->isUndeducedType()) {
4661 if (ParsingInitForAutoVars.count(Spec))
4662 Diag(TemplateNameLoc,
4663 diag::err_auto_variable_cannot_appear_in_own_initializer)
4664 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4665 << Spec->getType();
4666 else
4667 // We are substituting the initializer of this variable template
4668 // specialization.
4669 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4670 << Spec << Spec->getType();
4671
4672 return true;
4673 }
4674 // If we already have a variable template specialization, return it.
4675 return Spec;
4676 }
4677
4678 // This is the first time we have referenced this variable template
4679 // specialization. Create the canonical declaration and add it to
4680 // the set of specializations, based on the closest partial specialization
4681 // that it represents. That is,
4682 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4683 const TemplateArgumentList *PartialSpecArgs = nullptr;
4684 bool AmbiguousPartialSpec = false;
4685 typedef PartialSpecMatchResult MatchResult;
4687 SourceLocation PointOfInstantiation = TemplateNameLoc;
4688 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4689 /*ForTakingAddress=*/false);
4690
4691 // 1. Attempt to find the closest partial specialization that this
4692 // specializes, if any.
4693 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4694 // Perhaps better after unification of DeduceTemplateArguments() and
4695 // getMoreSpecializedPartialSpecialization().
4697 Template->getPartialSpecializations(PartialSpecs);
4698
4699 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4700 // C++ [temp.spec.partial.member]p2:
4701 // If the primary member template is explicitly specialized for a given
4702 // (implicit) specialization of the enclosing class template, the partial
4703 // specializations of the member template are ignored for this
4704 // specialization of the enclosing class template. If a partial
4705 // specialization of the member template is explicitly specialized for a
4706 // given (implicit) specialization of the enclosing class template, the
4707 // primary member template and its other partial specializations are still
4708 // considered for this specialization of the enclosing class template.
4709 if (Template->isMemberSpecialization() &&
4710 !Partial->isMemberSpecialization())
4711 continue;
4712
4713 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4714
4716 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4718 // Store the failed-deduction information for use in diagnostics, later.
4719 // TODO: Actually use the failed-deduction info?
4720 FailedCandidates.addCandidate().set(
4723 (void)Result;
4724 } else {
4725 Matched.push_back(PartialSpecMatchResult());
4726 Matched.back().Partial = Partial;
4727 Matched.back().Args = Info.takeSugared();
4728 }
4729 }
4730
4731 if (Matched.size() >= 1) {
4732 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4733 if (Matched.size() == 1) {
4734 // -- If exactly one matching specialization is found, the
4735 // instantiation is generated from that specialization.
4736 // We don't need to do anything for this.
4737 } else {
4738 // -- If more than one matching specialization is found, the
4739 // partial order rules (14.5.4.2) are used to determine
4740 // whether one of the specializations is more specialized
4741 // than the others. If none of the specializations is more
4742 // specialized than all of the other matching
4743 // specializations, then the use of the variable template is
4744 // ambiguous and the program is ill-formed.
4745 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4746 PEnd = Matched.end();
4747 P != PEnd; ++P) {
4748 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4749 PointOfInstantiation) ==
4750 P->Partial)
4751 Best = P;
4752 }
4753
4754 // Determine if the best partial specialization is more specialized than
4755 // the others.
4756 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4757 PEnd = Matched.end();
4758 P != PEnd; ++P) {
4760 P->Partial, Best->Partial,
4761 PointOfInstantiation) != Best->Partial) {
4762 AmbiguousPartialSpec = true;
4763 break;
4764 }
4765 }
4766 }
4767
4768 // Instantiate using the best variable template partial specialization.
4769 InstantiationPattern = Best->Partial;
4770 PartialSpecArgs = Best->Args;
4771 } else {
4772 // -- If no match is found, the instantiation is generated
4773 // from the primary template.
4774 // InstantiationPattern = Template->getTemplatedDecl();
4775 }
4776
4777 // 2. Create the canonical declaration.
4778 // Note that we do not instantiate a definition until we see an odr-use
4779 // in DoMarkVarDeclReferenced().
4780 // FIXME: LateAttrs et al.?
4781 if (AmbiguousPartialSpec) {
4782 // Partial ordering did not produce a clear winner. Complain.
4783 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4784 << Template;
4785 // Print the matching partial specializations.
4786 for (MatchResult P : Matched)
4787 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4788 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4789 *P.Args);
4790 return true;
4791 }
4792
4794 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4795 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4796 if (!Decl)
4797 return true;
4798 if (SetWrittenArgs)
4799 Decl->setTemplateArgsAsWritten(TemplateArgs);
4800
4802 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4803 Decl->setInstantiationOf(D, PartialSpecArgs);
4804
4805 checkSpecializationReachability(TemplateNameLoc, Decl);
4806
4807 assert(Decl && "No variable template specialization?");
4808 return Decl;
4809}
4810
4812 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4813 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4814 const TemplateArgumentListInfo *TemplateArgs) {
4815
4816 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4817 *TemplateArgs, /*SetWrittenArgs=*/false);
4818 if (Decl.isInvalid())
4819 return ExprError();
4820
4821 if (!Decl.get())
4822 return ExprResult();
4823
4824 VarDecl *Var = cast<VarDecl>(Decl.get());
4827 NameInfo.getLoc());
4828
4829 // Build an ordinary singleton decl ref.
4830 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4831}
4832
4835 const TemplateArgumentListInfo *TemplateArgs) {
4836 assert(Template && "A variable template id without template?");
4837
4838 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4839 Template->templateParameterKind() !=
4841 return ExprResult();
4842
4843 // Check that the template argument list is well-formed for this template.
4846 Template, /*Template kw loc=*/{},
4847 // FIXME: TemplateArgs will not be modified because
4848 // UpdateArgsWithConversions is false, however, we should
4849 // CheckTemplateArgumentList to be const-correct.
4850 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4851 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4852 /*UpdateArgsWithConversions=*/false))
4853 return true;
4854
4856 TemplateName(Template), *TemplateArgs);
4857}
4858
4860 SourceLocation Loc) {
4861 Diag(Loc, diag::err_template_missing_args)
4862 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4863 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4864 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4865 }
4866}
4867
4869 bool TemplateKeyword,
4870 TemplateDecl *TD,
4871 SourceLocation Loc) {
4872 TemplateName Name = Context.getQualifiedTemplateName(
4873 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4875}
4876
4878 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4879 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4880 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4881 bool DoCheckConstraintSatisfaction) {
4882 assert(NamedConcept && "A concept template id without a template?");
4883
4884 if (NamedConcept->isInvalidDecl())
4885 return ExprError();
4886
4889 NamedConcept, ConceptNameInfo.getLoc(),
4890 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4891 /*DefaultArgs=*/{},
4892 /*PartialTemplateArgs=*/false, CTAI,
4893 /*UpdateArgsWithConversions=*/false))
4894 return ExprError();
4895
4896 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4897
4898 // There's a bug with CTAI.CanonicalConverted.
4899 // If the template argument contains a DependentDecltypeType that includes a
4900 // TypeAliasType, and the same written type had occurred previously in the
4901 // source, then the DependentDecltypeType would be canonicalized to that
4902 // previous type which would mess up the substitution.
4903 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4905 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4906 CTAI.SugaredConverted);
4907 ConstraintSatisfaction Satisfaction;
4908 bool AreArgsDependent =
4909 TemplateSpecializationType::anyDependentTemplateArguments(
4910 *TemplateArgs, CTAI.SugaredConverted);
4911 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4912 /*Final=*/false);
4914 Context,
4916 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4918
4919 bool Error = false;
4920 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4921 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4922 DoCheckConstraintSatisfaction) {
4923
4925
4928
4930 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4931 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4932 TemplateArgs->getRAngleLoc()),
4933 Satisfaction, CL);
4934 Satisfaction.ContainsErrors = Error;
4935 }
4936
4937 if (Error)
4938 return ExprError();
4939
4941 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4942}
4943
4945 SourceLocation TemplateKWLoc,
4946 LookupResult &R,
4947 bool RequiresADL,
4948 const TemplateArgumentListInfo *TemplateArgs) {
4949 // FIXME: Can we do any checking at this point? I guess we could check the
4950 // template arguments that we have against the template name, if the template
4951 // name refers to a single template. That's not a terribly common case,
4952 // though.
4953 // foo<int> could identify a single function unambiguously
4954 // This approach does NOT work, since f<int>(1);
4955 // gets resolved prior to resorting to overload resolution
4956 // i.e., template<class T> void f(double);
4957 // vs template<class T, class U> void f(U);
4958
4959 // These should be filtered out by our callers.
4960 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4961
4962 // Non-function templates require a template argument list.
4963 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4964 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4966 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4967 return ExprError();
4968 }
4969 }
4970 bool KnownDependent = false;
4971 // In C++1y, check variable template ids.
4972 if (R.getAsSingle<VarTemplateDecl>()) {
4974 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4975 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4976 if (Res.isInvalid() || Res.isUsable())
4977 return Res;
4978 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4979 KnownDependent = true;
4980 }
4981
4982 // We don't want lookup warnings at this point.
4983 R.suppressDiagnostics();
4984
4985 if (R.getAsSingle<ConceptDecl>()) {
4986 assert(TemplateKWLoc.isInvalid() &&
4987 "template keyword in front of a concept id?");
4988 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4989 R.getRepresentativeDecl(),
4990 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4991 }
4992
4993 // Check variable template ids (C++17) and concept template parameters
4994 // (C++26).
4996 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
4997 assert(SS.isEmpty() && "template parameter with a scope specifier?");
4998 assert(TemplateKWLoc.isInvalid() &&
4999 "template keyword in front of a template parameter?");
5001 R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
5002 TemplateArgs);
5003 }
5004
5005 // Function templates
5007 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5008 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5009 R.begin(), R.end(), KnownDependent,
5010 /*KnownInstantiationDependent=*/false);
5011 // Model the templates with UnresolvedTemplateTy. The expression should then
5012 // either be transformed in an instantiation or be diagnosed in
5013 // CheckPlaceholderExpr.
5014 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5015 !R.getFoundDecl()->getAsFunction())
5016 ULE->setType(Context.UnresolvedTemplateTy);
5017
5018 return ULE;
5019}
5020
5022 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5023 const DeclarationNameInfo &NameInfo,
5024 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5025 assert(TemplateArgs || TemplateKWLoc.isValid());
5026
5027 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5028 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5029 /*EnteringContext=*/false, TemplateKWLoc))
5030 return ExprError();
5031
5032 if (R.isAmbiguous())
5033 return ExprError();
5034
5035 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5036 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5037
5038 if (R.empty()) {
5040 Diag(NameInfo.getLoc(), diag::err_no_member)
5041 << NameInfo.getName() << DC << SS.getRange();
5042 return ExprError();
5043 }
5044
5045 // If necessary, build an implicit class member access.
5046 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5047 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5048 /*S=*/nullptr);
5049
5050 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5051}
5052
5054 CXXScopeSpec &SS,
5055 SourceLocation TemplateKWLoc,
5056 const UnqualifiedId &Name,
5057 ParsedType ObjectType,
5058 bool EnteringContext,
5060 bool AllowInjectedClassName) {
5061 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5062 Diag(TemplateKWLoc,
5064 diag::warn_cxx98_compat_template_outside_of_template :
5065 diag::ext_template_outside_of_template)
5066 << FixItHint::CreateRemoval(TemplateKWLoc);
5067
5068 if (SS.isInvalid())
5069 return TNK_Non_template;
5070
5071 // Figure out where isTemplateName is going to look.
5072 DeclContext *LookupCtx = nullptr;
5073 if (SS.isNotEmpty())
5074 LookupCtx = computeDeclContext(SS, EnteringContext);
5075 else if (ObjectType)
5076 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5077
5078 // C++0x [temp.names]p5:
5079 // If a name prefixed by the keyword template is not the name of
5080 // a template, the program is ill-formed. [Note: the keyword
5081 // template may not be applied to non-template members of class
5082 // templates. -end note ] [ Note: as is the case with the
5083 // typename prefix, the template prefix is allowed in cases
5084 // where it is not strictly necessary; i.e., when the
5085 // nested-name-specifier or the expression on the left of the ->
5086 // or . is not dependent on a template-parameter, or the use
5087 // does not appear in the scope of a template. -end note]
5088 //
5089 // Note: C++03 was more strict here, because it banned the use of
5090 // the "template" keyword prior to a template-name that was not a
5091 // dependent name. C++ DR468 relaxed this requirement (the
5092 // "template" keyword is now permitted). We follow the C++0x
5093 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5094 bool MemberOfUnknownSpecialization;
5095 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5096 ObjectType, EnteringContext, Result,
5097 MemberOfUnknownSpecialization);
5098 if (TNK != TNK_Non_template) {
5099 // We resolved this to a (non-dependent) template name. Return it.
5100 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5101 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5103 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5104 // C++14 [class.qual]p2:
5105 // In a lookup in which function names are not ignored and the
5106 // nested-name-specifier nominates a class C, if the name specified
5107 // [...] is the injected-class-name of C, [...] the name is instead
5108 // considered to name the constructor
5109 //
5110 // We don't get here if naming the constructor would be valid, so we
5111 // just reject immediately and recover by treating the
5112 // injected-class-name as naming the template.
5113 Diag(Name.getBeginLoc(),
5114 diag::ext_out_of_line_qualified_id_type_names_constructor)
5115 << Name.Identifier
5116 << 0 /*injected-class-name used as template name*/
5117 << TemplateKWLoc.isValid();
5118 }
5119 return TNK;
5120 }
5121
5122 if (!MemberOfUnknownSpecialization) {
5123 // Didn't find a template name, and the lookup wasn't dependent.
5124 // Do the lookup again to determine if this is a "nothing found" case or
5125 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5126 // need to do this.
5128 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5130 // Tell LookupTemplateName that we require a template so that it diagnoses
5131 // cases where it finds a non-template.
5132 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5133 ? RequiredTemplateKind(TemplateKWLoc)
5135 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5136 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5137 !R.isAmbiguous()) {
5138 if (LookupCtx)
5139 Diag(Name.getBeginLoc(), diag::err_no_member)
5140 << DNI.getName() << LookupCtx << SS.getRange();
5141 else
5142 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5143 << DNI.getName() << SS.getRange();
5144 }
5145 return TNK_Non_template;
5146 }
5147
5148 NestedNameSpecifier Qualifier = SS.getScopeRep();
5149
5150 switch (Name.getKind()) {
5152 Result = TemplateTy::make(Context.getDependentTemplateName(
5153 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5155
5157 Result = TemplateTy::make(Context.getDependentTemplateName(
5158 {Qualifier, Name.OperatorFunctionId.Operator,
5159 TemplateKWLoc.isValid()}));
5160 return TNK_Function_template;
5161
5163 // This is a kind of template name, but can never occur in a dependent
5164 // scope (literal operators can only be declared at namespace scope).
5165 break;
5166
5167 default:
5168 break;
5169 }
5170
5171 // This name cannot possibly name a dependent template. Diagnose this now
5172 // rather than building a dependent template name that can never be valid.
5173 Diag(Name.getBeginLoc(),
5174 diag::err_template_kw_refers_to_dependent_non_template)
5176 << TemplateKWLoc.isValid() << TemplateKWLoc;
5177 return TNK_Non_template;
5178}
5179
5182 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5183 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5184 const TemplateArgument &Arg = AL.getArgument();
5186 TypeSourceInfo *TSI = nullptr;
5187
5188 // Check template type parameter.
5189 switch(Arg.getKind()) {
5191 // C++ [temp.arg.type]p1:
5192 // A template-argument for a template-parameter which is a
5193 // type shall be a type-id.
5194 ArgType = Arg.getAsType();
5195 TSI = AL.getTypeSourceInfo();
5196 break;
5199 // We have a template type parameter but the template argument
5200 // is a template without any arguments.
5201 SourceRange SR = AL.getSourceRange();
5204 return true;
5205 }
5207 // We have a template type parameter but the template argument is an
5208 // expression; see if maybe it is missing the "typename" keyword.
5209 CXXScopeSpec SS;
5210 DeclarationNameInfo NameInfo;
5211
5212 if (DependentScopeDeclRefExpr *ArgExpr =
5213 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5214 SS.Adopt(ArgExpr->getQualifierLoc());
5215 NameInfo = ArgExpr->getNameInfo();
5216 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5217 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5218 if (ArgExpr->isImplicitAccess()) {
5219 SS.Adopt(ArgExpr->getQualifierLoc());
5220 NameInfo = ArgExpr->getMemberNameInfo();
5221 }
5222 }
5223
5224 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5225 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5226 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5227
5228 if (Result.getAsSingle<TypeDecl>() ||
5229 Result.wasNotFoundInCurrentInstantiation()) {
5230 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5231 // Suggest that the user add 'typename' before the NNS.
5233 Diag(Loc, getLangOpts().MSVCCompat
5234 ? diag::ext_ms_template_type_arg_missing_typename
5235 : diag::err_template_arg_must_be_type_suggest)
5236 << FixItHint::CreateInsertion(Loc, "typename ");
5238
5239 // Recover by synthesizing a type using the location information that we
5240 // already have.
5241 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5242 SS.getScopeRep(), II);
5243 TypeLocBuilder TLB;
5245 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5247 TL.setNameLoc(NameInfo.getLoc());
5248 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5249
5250 // Overwrite our input TemplateArgumentLoc so that we can recover
5251 // properly.
5254
5255 break;
5256 }
5257 }
5258 // fallthrough
5259 [[fallthrough]];
5260 }
5261 default: {
5262 // We allow instantiating a template with template argument packs when
5263 // building deduction guides or mapping constraint template parameters.
5264 if (Arg.getKind() == TemplateArgument::Pack &&
5265 (CodeSynthesisContexts.back().Kind ==
5268 SugaredConverted.push_back(Arg);
5269 CanonicalConverted.push_back(Arg);
5270 return false;
5271 }
5272 // We have a template type parameter but the template argument
5273 // is not a type.
5274 SourceRange SR = AL.getSourceRange();
5275 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5277
5278 return true;
5279 }
5280 }
5281
5282 if (CheckTemplateArgument(TSI))
5283 return true;
5284
5285 // Objective-C ARC:
5286 // If an explicitly-specified template argument type is a lifetime type
5287 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5288 if (getLangOpts().ObjCAutoRefCount &&
5289 ArgType->isObjCLifetimeType() &&
5290 !ArgType.getObjCLifetime()) {
5291 Qualifiers Qs;
5293 ArgType = Context.getQualifiedType(ArgType, Qs);
5294 }
5295
5296 SugaredConverted.push_back(TemplateArgument(ArgType));
5297 CanonicalConverted.push_back(
5298 TemplateArgument(Context.getCanonicalType(ArgType)));
5299 return false;
5300}
5301
5302/// Substitute template arguments into the default template argument for
5303/// the given template type parameter.
5304///
5305/// \param SemaRef the semantic analysis object for which we are performing
5306/// the substitution.
5307///
5308/// \param Template the template that we are synthesizing template arguments
5309/// for.
5310///
5311/// \param TemplateLoc the location of the template name that started the
5312/// template-id we are checking.
5313///
5314/// \param RAngleLoc the location of the right angle bracket ('>') that
5315/// terminates the template-id.
5316///
5317/// \param Param the template template parameter whose default we are
5318/// substituting into.
5319///
5320/// \param Converted the list of template arguments provided for template
5321/// parameters that precede \p Param in the template parameter list.
5322///
5323/// \param Output the resulting substituted template argument.
5324///
5325/// \returns true if an error occurred.
5327 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5328 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5329 ArrayRef<TemplateArgument> SugaredConverted,
5330 ArrayRef<TemplateArgument> CanonicalConverted,
5331 TemplateArgumentLoc &Output) {
5332 Output = Param->getDefaultArgument();
5333
5334 // If the argument type is dependent, instantiate it now based
5335 // on the previously-computed template arguments.
5336 if (Output.getArgument().isInstantiationDependent()) {
5337 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5338 SugaredConverted,
5339 SourceRange(TemplateLoc, RAngleLoc));
5340 if (Inst.isInvalid())
5341 return true;
5342
5343 // Only substitute for the innermost template argument list.
5344 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5345 /*Final=*/true);
5346 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5347 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5348
5349 bool ForLambdaCallOperator = false;
5350 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5351 ForLambdaCallOperator = Rec->isLambda();
5352 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5353 !ForLambdaCallOperator);
5354
5355 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5356 Param->getDefaultArgumentLoc(),
5357 Param->getDeclName()))
5358 return true;
5359 }
5360
5361 return false;
5362}
5363
5364/// Substitute template arguments into the default template argument for
5365/// the given non-type template parameter.
5366///
5367/// \param SemaRef the semantic analysis object for which we are performing
5368/// the substitution.
5369///
5370/// \param Template the template that we are synthesizing template arguments
5371/// for.
5372///
5373/// \param TemplateLoc the location of the template name that started the
5374/// template-id we are checking.
5375///
5376/// \param RAngleLoc the location of the right angle bracket ('>') that
5377/// terminates the template-id.
5378///
5379/// \param Param the non-type template parameter whose default we are
5380/// substituting into.
5381///
5382/// \param Converted the list of template arguments provided for template
5383/// parameters that precede \p Param in the template parameter list.
5384///
5385/// \returns the substituted template argument, or NULL if an error occurred.
5387 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5388 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5389 ArrayRef<TemplateArgument> SugaredConverted,
5390 ArrayRef<TemplateArgument> CanonicalConverted,
5391 TemplateArgumentLoc &Output) {
5392 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5393 SugaredConverted,
5394 SourceRange(TemplateLoc, RAngleLoc));
5395 if (Inst.isInvalid())
5396 return true;
5397
5398 // Only substitute for the innermost template argument list.
5399 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5400 /*Final=*/true);
5401 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5402 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5403
5404 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5405 EnterExpressionEvaluationContext ConstantEvaluated(
5407 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5408 TemplateArgLists, Output);
5409}
5410
5411/// Substitute template arguments into the default template argument for
5412/// the given template template parameter.
5413///
5414/// \param SemaRef the semantic analysis object for which we are performing
5415/// the substitution.
5416///
5417/// \param Template the template that we are synthesizing template arguments
5418/// for.
5419///
5420/// \param TemplateLoc the location of the template name that started the
5421/// template-id we are checking.
5422///
5423/// \param RAngleLoc the location of the right angle bracket ('>') that
5424/// terminates the template-id.
5425///
5426/// \param Param the template template parameter whose default we are
5427/// substituting into.
5428///
5429/// \param Converted the list of template arguments provided for template
5430/// parameters that precede \p Param in the template parameter list.
5431///
5432/// \param QualifierLoc Will be set to the nested-name-specifier (with
5433/// source-location information) that precedes the template name.
5434///
5435/// \returns the substituted template argument, or NULL if an error occurred.
5437 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5438 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5440 ArrayRef<TemplateArgument> SugaredConverted,
5441 ArrayRef<TemplateArgument> CanonicalConverted,
5442 NestedNameSpecifierLoc &QualifierLoc) {
5444 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5445 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5446 if (Inst.isInvalid())
5447 return TemplateName();
5448
5449 // Only substitute for the innermost template argument list.
5450 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5451 /*Final=*/true);
5452 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5453 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5454
5455 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5456
5457 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5458 QualifierLoc = A.getTemplateQualifierLoc();
5459 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5461 A.getTemplateNameLoc(), TemplateArgLists);
5462}
5463
5465 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5466 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5467 ArrayRef<TemplateArgument> SugaredConverted,
5468 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5469 HasDefaultArg = false;
5470
5471 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5472 if (!hasReachableDefaultArgument(TypeParm))
5473 return TemplateArgumentLoc();
5474
5475 HasDefaultArg = true;
5476 TemplateArgumentLoc Output;
5477 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5478 RAngleLoc, TypeParm, SugaredConverted,
5479 CanonicalConverted, Output))
5480 return TemplateArgumentLoc();
5481 return Output;
5482 }
5483
5484 if (NonTypeTemplateParmDecl *NonTypeParm
5485 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5486 if (!hasReachableDefaultArgument(NonTypeParm))
5487 return TemplateArgumentLoc();
5488
5489 HasDefaultArg = true;
5490 TemplateArgumentLoc Output;
5491 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5492 RAngleLoc, NonTypeParm, SugaredConverted,
5493 CanonicalConverted, Output))
5494 return TemplateArgumentLoc();
5495 return Output;
5496 }
5497
5498 TemplateTemplateParmDecl *TempTempParm
5500 if (!hasReachableDefaultArgument(TempTempParm))
5501 return TemplateArgumentLoc();
5502
5503 HasDefaultArg = true;
5504 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5505 NestedNameSpecifierLoc QualifierLoc;
5507 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5508 SugaredConverted, CanonicalConverted, QualifierLoc);
5509 if (TName.isNull())
5510 return TemplateArgumentLoc();
5511
5512 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5513 QualifierLoc, A.getTemplateNameLoc());
5514}
5515
5516/// Convert a template-argument that we parsed as a type into a template, if
5517/// possible. C++ permits injected-class-names to perform dual service as
5518/// template template arguments and as template type arguments.
5521 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5522 if (!TagLoc)
5523 return TemplateArgumentLoc();
5524
5525 // If this type was written as an injected-class-name, it can be used as a
5526 // template template argument.
5527 // If this type was written as an injected-class-name, it may have been
5528 // converted to a RecordType during instantiation. If the RecordType is
5529 // *not* wrapped in a TemplateSpecializationType and denotes a class
5530 // template specialization, it must have come from an injected-class-name.
5531
5532 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5533 if (Name.isNull())
5534 return TemplateArgumentLoc();
5535
5536 return TemplateArgumentLoc(Context, Name,
5537 /*TemplateKWLoc=*/SourceLocation(),
5538 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5539}
5540
5543 SourceLocation TemplateLoc,
5544 SourceLocation RAngleLoc,
5545 unsigned ArgumentPackIndex,
5548 // Check template type parameters.
5549 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5550 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5551 CTAI.CanonicalConverted);
5552
5553 const TemplateArgument &Arg = ArgLoc.getArgument();
5554 // Check non-type template parameters.
5555 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5556 // Do substitution on the type of the non-type template parameter
5557 // with the template arguments we've seen thus far. But if the
5558 // template has a dependent context then we cannot substitute yet.
5559 QualType NTTPType = NTTP->getType();
5560 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5561 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5562
5563 if (NTTPType->isInstantiationDependentType()) {
5564 // Do substitution on the type of the non-type template parameter.
5565 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5566 CTAI.SugaredConverted,
5567 SourceRange(TemplateLoc, RAngleLoc));
5568 if (Inst.isInvalid())
5569 return true;
5570
5572 /*Final=*/true);
5573 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5574 // If the parameter is a pack expansion, expand this slice of the pack.
5575 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5576 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5577 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5578 NTTP->getDeclName());
5579 } else {
5580 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5581 NTTP->getDeclName());
5582 }
5583
5584 // If that worked, check the non-type template parameter type
5585 // for validity.
5586 if (!NTTPType.isNull())
5587 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5588 NTTP->getLocation());
5589 if (NTTPType.isNull())
5590 return true;
5591 }
5592
5593 auto checkExpr = [&](Expr *E) -> Expr * {
5594 TemplateArgument SugaredResult, CanonicalResult;
5596 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5597 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5598 // If the current template argument causes an error, give up now.
5599 if (Res.isInvalid())
5600 return nullptr;
5601 CTAI.SugaredConverted.push_back(SugaredResult);
5602 CTAI.CanonicalConverted.push_back(CanonicalResult);
5603 return Res.get();
5604 };
5605
5606 switch (Arg.getKind()) {
5608 llvm_unreachable("Should never see a NULL template argument here");
5609
5611 Expr *E = Arg.getAsExpr();
5612 Expr *R = checkExpr(E);
5613 if (!R)
5614 return true;
5615 // If the resulting expression is new, then use it in place of the
5616 // old expression in the template argument.
5617 if (R != E) {
5618 TemplateArgument TA(R, /*IsCanonical=*/false);
5619 ArgLoc = TemplateArgumentLoc(TA, R);
5620 }
5621 break;
5622 }
5623
5624 // As for the converted NTTP kinds, they still might need another
5625 // conversion, as the new corresponding parameter might be different.
5626 // Ideally, we would always perform substitution starting with sugared types
5627 // and never need these, as we would still have expressions. Since these are
5628 // needed so rarely, it's probably a better tradeoff to just convert them
5629 // back to expressions.
5634 // FIXME: StructuralValue is untested here.
5635 ExprResult R =
5637 assert(R.isUsable());
5638 if (!checkExpr(R.get()))
5639 return true;
5640 break;
5641 }
5642
5645 // We were given a template template argument. It may not be ill-formed;
5646 // see below.
5649 // We have a template argument such as \c T::template X, which we
5650 // parsed as a template template argument. However, since we now
5651 // know that we need a non-type template argument, convert this
5652 // template name into an expression.
5653
5654 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5655 ArgLoc.getTemplateNameLoc());
5656
5657 CXXScopeSpec SS;
5658 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5659 // FIXME: the template-template arg was a DependentTemplateName,
5660 // so it was provided with a template keyword. However, its source
5661 // location is not stored in the template argument structure.
5662 SourceLocation TemplateKWLoc;
5664 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5665 nullptr);
5666
5667 // If we parsed the template argument as a pack expansion, create a
5668 // pack expansion expression.
5671 if (E.isInvalid())
5672 return true;
5673 }
5674
5675 TemplateArgument SugaredResult, CanonicalResult;
5677 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5678 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5679 if (E.isInvalid())
5680 return true;
5681
5682 CTAI.SugaredConverted.push_back(SugaredResult);
5683 CTAI.CanonicalConverted.push_back(CanonicalResult);
5684 break;
5685 }
5686
5687 // We have a template argument that actually does refer to a class
5688 // template, alias template, or template template parameter, and
5689 // therefore cannot be a non-type template argument.
5690 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5691 << ArgLoc.getSourceRange();
5693
5694 return true;
5695
5697 // We have a non-type template parameter but the template
5698 // argument is a type.
5699
5700 // C++ [temp.arg]p2:
5701 // In a template-argument, an ambiguity between a type-id and
5702 // an expression is resolved to a type-id, regardless of the
5703 // form of the corresponding template-parameter.
5704 //
5705 // We warn specifically about this case, since it can be rather
5706 // confusing for users.
5707 QualType T = Arg.getAsType();
5708 SourceRange SR = ArgLoc.getSourceRange();
5709 if (T->isFunctionType())
5710 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5711 else
5712 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5714 return true;
5715 }
5716
5718 llvm_unreachable("Caller must expand template argument packs");
5719 }
5720
5721 return false;
5722 }
5723
5724
5725 // Check template template parameters.
5727
5728 TemplateParameterList *Params = TempParm->getTemplateParameters();
5729 if (TempParm->isExpandedParameterPack())
5730 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5731
5732 // Substitute into the template parameter list of the template
5733 // template parameter, since previously-supplied template arguments
5734 // may appear within the template template parameter.
5735 //
5736 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5737 {
5738 // Set up a template instantiation context.
5740 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5741 CTAI.SugaredConverted,
5742 SourceRange(TemplateLoc, RAngleLoc));
5743 if (Inst.isInvalid())
5744 return true;
5745
5746 Params = SubstTemplateParams(
5747 Params, CurContext,
5749 /*Final=*/true),
5750 /*EvaluateConstraints=*/false);
5751 if (!Params)
5752 return true;
5753 }
5754
5755 // C++1z [temp.local]p1: (DR1004)
5756 // When [the injected-class-name] is used [...] as a template-argument for
5757 // a template template-parameter [...] it refers to the class template
5758 // itself.
5759 if (Arg.getKind() == TemplateArgument::Type) {
5761 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5762 if (!ConvertedArg.getArgument().isNull())
5763 ArgLoc = ConvertedArg;
5764 }
5765
5766 switch (Arg.getKind()) {
5768 llvm_unreachable("Should never see a NULL template argument here");
5769
5772 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5773 CTAI.PartialOrdering,
5774 &CTAI.StrictPackMatch))
5775 return true;
5776
5777 CTAI.SugaredConverted.push_back(Arg);
5778 CTAI.CanonicalConverted.push_back(
5779 Context.getCanonicalTemplateArgument(Arg));
5780 break;
5781
5784 auto Kind = 0;
5785 switch (TempParm->templateParameterKind()) {
5787 Kind = 1;
5788 break;
5790 Kind = 2;
5791 break;
5792 default:
5793 break;
5794 }
5795
5796 // We have a template template parameter but the template
5797 // argument does not refer to a template.
5798 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5799 << Kind << getLangOpts().CPlusPlus11;
5800 return true;
5801 }
5802
5807 llvm_unreachable("non-type argument with template template parameter");
5808
5810 llvm_unreachable("Caller must expand template argument packs");
5811 }
5812
5813 return false;
5814}
5815
5816/// Diagnose a missing template argument.
5817template<typename TemplateParmDecl>
5819 TemplateDecl *TD,
5820 const TemplateParmDecl *D,
5822 // Dig out the most recent declaration of the template parameter; there may be
5823 // declarations of the template that are more recent than TD.
5825 ->getTemplateParameters()
5826 ->getParam(D->getIndex()));
5827
5828 // If there's a default argument that's not reachable, diagnose that we're
5829 // missing a module import.
5831 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5833 D->getDefaultArgumentLoc(), Modules,
5835 /*Recover*/true);
5836 return true;
5837 }
5838
5839 // FIXME: If there's a more recent default argument that *is* visible,
5840 // diagnose that it was declared too late.
5841
5843
5844 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5845 << /*not enough args*/0
5847 << TD;
5848 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5849 return true;
5850}
5851
5852/// Check that the given template argument list is well-formed
5853/// for specializing the given template.
5855 TemplateDecl *Template, SourceLocation TemplateLoc,
5856 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5857 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5858 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5860 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5861 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5863}
5864
5865/// Check that the given template argument list is well-formed
5866/// for specializing the given template.
5869 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5870 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5871 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5873
5875 *ConstraintsNotSatisfied = false;
5876
5877 // Make a copy of the template arguments for processing. Only make the
5878 // changes at the end when successful in matching the arguments to the
5879 // template.
5880 TemplateArgumentListInfo NewArgs = TemplateArgs;
5881
5882 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5883
5884 // C++23 [temp.arg.general]p1:
5885 // [...] The type and form of each template-argument specified in
5886 // a template-id shall match the type and form specified for the
5887 // corresponding parameter declared by the template in its
5888 // template-parameter-list.
5889 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5890 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5891 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5892 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5893 LocalInstantiationScope InstScope(*this, true);
5894 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5895 ParamEnd = Params->end(),
5896 Param = ParamBegin;
5897 Param != ParamEnd;
5898 /* increment in loop */) {
5899 if (size_t ParamIdx = Param - ParamBegin;
5900 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5901 // All written arguments should have been consumed by this point.
5902 assert(ArgIdx == NumArgs && "bad default argument deduction");
5903 if (ParamIdx == DefaultArgs.StartPos) {
5904 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5905 // Default arguments from a DeducedTemplateName are already converted.
5906 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5907 CTAI.SugaredConverted.push_back(DefArg);
5908 CTAI.CanonicalConverted.push_back(
5909 Context.getCanonicalTemplateArgument(DefArg));
5910 ++Param;
5911 }
5912 continue;
5913 }
5914 }
5915
5916 // If we have an expanded parameter pack, make sure we don't have too
5917 // many arguments.
5918 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5919 if (*Expansions == SugaredArgumentPack.size()) {
5920 // We're done with this parameter pack. Pack up its arguments and add
5921 // them to the list.
5922 CTAI.SugaredConverted.push_back(
5923 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5924 SugaredArgumentPack.clear();
5925
5926 CTAI.CanonicalConverted.push_back(
5927 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5928 CanonicalArgumentPack.clear();
5929
5930 // This argument is assigned to the next parameter.
5931 ++Param;
5932 continue;
5933 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5934 // Not enough arguments for this parameter pack.
5935 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5936 << /*not enough args*/0
5938 << Template;
5940 return true;
5941 }
5942 }
5943
5944 // Check for builtins producing template packs in this context, we do not
5945 // support them yet.
5946 if (const NonTypeTemplateParmDecl *NTTP =
5947 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5948 NTTP && NTTP->isPackExpansion()) {
5949 auto TL = NTTP->getTypeSourceInfo()
5950 ->getTypeLoc()
5953 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5954 for (const auto &UPP : Unexpanded) {
5955 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5956 if (!TST)
5957 continue;
5958 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5959 // Expanding a built-in pack in this context is not yet supported.
5960 Diag(TL.getEllipsisLoc(),
5961 diag::err_unsupported_builtin_template_pack_expansion)
5962 << TST->getTemplateName();
5963 return true;
5964 }
5965 }
5966
5967 if (ArgIdx < NumArgs) {
5968 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5969 bool NonPackParameter =
5970 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5971 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5972
5973 if (ArgIsExpansion && CTAI.MatchingTTP) {
5974 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5975 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5976 ++Param) {
5977 TemplateArgument &Arg = Args[Param - First];
5978 Arg = ArgLoc.getArgument();
5979 if (!(*Param)->isTemplateParameterPack() ||
5980 getExpandedPackSize(*Param))
5981 Arg = Arg.getPackExpansionPattern();
5982 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5983 SaveAndRestore _1(CTAI.PartialOrdering, false);
5984 SaveAndRestore _2(CTAI.MatchingTTP, true);
5985 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5986 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5988 return true;
5989 Arg = NewArgLoc.getArgument();
5990 CTAI.CanonicalConverted.back().setIsDefaulted(
5991 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5992 CTAI.CanonicalConverted,
5993 Params->getDepth()));
5994 }
5995 ArgLoc = TemplateArgumentLoc(
5998 } else {
5999 SaveAndRestore _1(CTAI.PartialOrdering, false);
6000 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6001 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6003 return true;
6004 CTAI.CanonicalConverted.back().setIsDefaulted(
6005 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6006 *Param, CTAI.CanonicalConverted,
6007 Params->getDepth()));
6008 if (ArgIsExpansion && NonPackParameter) {
6009 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6010 // alias template, builtin template, or concept, and it's not part of
6011 // a parameter pack. This can't be canonicalized, so reject it now.
6013 Template)) {
6014 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6016 : 0;
6017 Diag(ArgLoc.getLocation(),
6018 diag::err_template_expansion_into_fixed_list)
6019 << DiagSelect << ArgLoc.getSourceRange();
6021 return true;
6022 }
6023 }
6024 }
6025
6026 // We're now done with this argument.
6027 ++ArgIdx;
6028
6029 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6030 // Directly convert the remaining arguments, because we don't know what
6031 // parameters they'll match up with.
6032
6033 if (!SugaredArgumentPack.empty()) {
6034 // If we were part way through filling in an expanded parameter pack,
6035 // fall back to just producing individual arguments.
6036 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6037 SugaredArgumentPack.begin(),
6038 SugaredArgumentPack.end());
6039 SugaredArgumentPack.clear();
6040
6041 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6042 CanonicalArgumentPack.begin(),
6043 CanonicalArgumentPack.end());
6044 CanonicalArgumentPack.clear();
6045 }
6046
6047 while (ArgIdx < NumArgs) {
6048 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6049 CTAI.SugaredConverted.push_back(Arg);
6050 CTAI.CanonicalConverted.push_back(
6051 Context.getCanonicalTemplateArgument(Arg));
6052 ++ArgIdx;
6053 }
6054
6055 return false;
6056 }
6057
6058 if ((*Param)->isTemplateParameterPack()) {
6059 // The template parameter was a template parameter pack, so take the
6060 // deduced argument and place it on the argument pack. Note that we
6061 // stay on the same template parameter so that we can deduce more
6062 // arguments.
6063 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6064 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6065 } else {
6066 // Move to the next template parameter.
6067 ++Param;
6068 }
6069 continue;
6070 }
6071
6072 // If we're checking a partial template argument list, we're done.
6073 if (PartialTemplateArgs) {
6074 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6075 CTAI.SugaredConverted.push_back(
6076 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6077 CTAI.CanonicalConverted.push_back(
6078 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6079 }
6080 return false;
6081 }
6082
6083 // If we have a template parameter pack with no more corresponding
6084 // arguments, just break out now and we'll fill in the argument pack below.
6085 if ((*Param)->isTemplateParameterPack()) {
6086 assert(!getExpandedPackSize(*Param) &&
6087 "Should have dealt with this already");
6088
6089 // A non-expanded parameter pack before the end of the parameter list
6090 // only occurs for an ill-formed template parameter list, unless we've
6091 // got a partial argument list for a function template, so just bail out.
6092 if (Param + 1 != ParamEnd) {
6093 assert(
6094 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6095 "Concept templates must have parameter packs at the end.");
6096 return true;
6097 }
6098
6099 CTAI.SugaredConverted.push_back(
6100 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6101 SugaredArgumentPack.clear();
6102
6103 CTAI.CanonicalConverted.push_back(
6104 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6105 CanonicalArgumentPack.clear();
6106
6107 ++Param;
6108 continue;
6109 }
6110
6111 // Check whether we have a default argument.
6112 bool HasDefaultArg;
6113
6114 // Retrieve the default template argument from the template
6115 // parameter. For each kind of template parameter, we substitute the
6116 // template arguments provided thus far and any "outer" template arguments
6117 // (when the template parameter was part of a nested template) into
6118 // the default argument.
6120 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6121 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6122
6123 if (Arg.getArgument().isNull()) {
6124 if (!HasDefaultArg) {
6125 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6126 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6127 NewArgs);
6128 if (NonTypeTemplateParmDecl *NTTP =
6129 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6130 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6131 NewArgs);
6132 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6134 NewArgs);
6135 }
6136 return true;
6137 }
6138
6139 // Introduce an instantiation record that describes where we are using
6140 // the default template argument. We're not actually instantiating a
6141 // template here, we just create this object to put a note into the
6142 // context stack.
6143 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6144 CTAI.SugaredConverted,
6145 SourceRange(TemplateLoc, RAngleLoc));
6146 if (Inst.isInvalid())
6147 return true;
6148
6149 SaveAndRestore _1(CTAI.PartialOrdering, false);
6150 SaveAndRestore _2(CTAI.MatchingTTP, false);
6151 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6152 // Check the default template argument.
6153 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6154 CTAI, CTAK_Specified))
6155 return true;
6156
6157 CTAI.SugaredConverted.back().setIsDefaulted(true);
6158 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6159
6160 // Core issue 150 (assumed resolution): if this is a template template
6161 // parameter, keep track of the default template arguments from the
6162 // template definition.
6163 if (isTemplateTemplateParameter)
6164 NewArgs.addArgument(Arg);
6165
6166 // Move to the next template parameter and argument.
6167 ++Param;
6168 ++ArgIdx;
6169 }
6170
6171 // If we're performing a partial argument substitution, allow any trailing
6172 // pack expansions; they might be empty. This can happen even if
6173 // PartialTemplateArgs is false (the list of arguments is complete but
6174 // still dependent).
6175 if (CTAI.MatchingTTP ||
6177 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6178 while (ArgIdx < NumArgs &&
6179 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6180 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6181 CTAI.SugaredConverted.push_back(Arg);
6182 CTAI.CanonicalConverted.push_back(
6183 Context.getCanonicalTemplateArgument(Arg));
6184 }
6185 }
6186
6187 // If we have any leftover arguments, then there were too many arguments.
6188 // Complain and fail.
6189 if (ArgIdx < NumArgs) {
6190 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6191 << /*too many args*/1
6193 << Template
6194 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6196 return true;
6197 }
6198
6199 // No problems found with the new argument list, propagate changes back
6200 // to caller.
6201 if (UpdateArgsWithConversions)
6202 TemplateArgs = std::move(NewArgs);
6203
6204 if (!PartialTemplateArgs) {
6205 // Setup the context/ThisScope for the case where we are needing to
6206 // re-instantiate constraints outside of normal instantiation.
6207 DeclContext *NewContext = Template->getDeclContext();
6208
6209 // If this template is in a template, make sure we extract the templated
6210 // decl.
6211 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6212 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6213 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6214
6215 Qualifiers ThisQuals;
6216 if (const auto *Method =
6217 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6218 ThisQuals = Method->getMethodQualifiers();
6219
6220 ContextRAII Context(*this, NewContext);
6221 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6222
6224 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6225 /*RelativeToPrimary=*/true,
6226 /*Pattern=*/nullptr,
6227 /*ForConceptInstantiation=*/true);
6228 if (!isa<ConceptDecl>(Template) &&
6230 Template, MLTAL,
6231 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6234 return true;
6235 }
6236 }
6237
6238 return false;
6239}
6240
6241namespace {
6242 class UnnamedLocalNoLinkageFinder
6243 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6244 {
6245 Sema &S;
6246 SourceRange SR;
6247
6249
6250 public:
6251 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6252
6253 bool Visit(QualType T) {
6254 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6255 }
6256
6257#define TYPE(Class, Parent) \
6258 bool Visit##Class##Type(const Class##Type *);
6259#define ABSTRACT_TYPE(Class, Parent) \
6260 bool Visit##Class##Type(const Class##Type *) { return false; }
6261#define NON_CANONICAL_TYPE(Class, Parent) \
6262 bool Visit##Class##Type(const Class##Type *) { return false; }
6263#include "clang/AST/TypeNodes.inc"
6264
6265 bool VisitTagDecl(const TagDecl *Tag);
6266 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6267 };
6268} // end anonymous namespace
6269
6270bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6271 return false;
6272}
6273
6274bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6275 return Visit(T->getElementType());
6276}
6277
6278bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6279 return Visit(T->getPointeeType());
6280}
6281
6282bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6283 const BlockPointerType* T) {
6284 return Visit(T->getPointeeType());
6285}
6286
6287bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6288 const LValueReferenceType* T) {
6289 return Visit(T->getPointeeType());
6290}
6291
6292bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6293 const RValueReferenceType* T) {
6294 return Visit(T->getPointeeType());
6295}
6296
6297bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6298 const MemberPointerType *T) {
6299 if (Visit(T->getPointeeType()))
6300 return true;
6301 if (auto *RD = T->getMostRecentCXXRecordDecl())
6302 return VisitTagDecl(RD);
6303 return VisitNestedNameSpecifier(T->getQualifier());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6307 const ConstantArrayType* T) {
6308 return Visit(T->getElementType());
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6312 const IncompleteArrayType* T) {
6313 return Visit(T->getElementType());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6317 const VariableArrayType* T) {
6318 return Visit(T->getElementType());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6322 const DependentSizedArrayType* T) {
6323 return Visit(T->getElementType());
6324}
6325
6326bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6328 return Visit(T->getElementType());
6329}
6330
6331bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6332 const DependentSizedMatrixType *T) {
6333 return Visit(T->getElementType());
6334}
6335
6336bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6338 return Visit(T->getPointeeType());
6339}
6340
6341bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6342 return Visit(T->getElementType());
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6346 const DependentVectorType *T) {
6347 return Visit(T->getElementType());
6348}
6349
6350bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6351 return Visit(T->getElementType());
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6355 const ConstantMatrixType *T) {
6356 return Visit(T->getElementType());
6357}
6358
6359bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6360 const FunctionProtoType* T) {
6361 for (const auto &A : T->param_types()) {
6362 if (Visit(A))
6363 return true;
6364 }
6365
6366 return Visit(T->getReturnType());
6367}
6368
6369bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6370 const FunctionNoProtoType* T) {
6371 return Visit(T->getReturnType());
6372}
6373
6374bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6375 const UnresolvedUsingType*) {
6376 return false;
6377}
6378
6379bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6380 return false;
6381}
6382
6383bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6384 return Visit(T->getUnmodifiedType());
6385}
6386
6387bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6388 return false;
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6392 const PackIndexingType *) {
6393 return false;
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6397 const UnaryTransformType*) {
6398 return false;
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6402 return Visit(T->getDeducedType());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6406 const DeducedTemplateSpecializationType *T) {
6407 return Visit(T->getDeducedType());
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6411 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6415 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6419 const TemplateTypeParmType*) {
6420 return false;
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6424 const SubstTemplateTypeParmPackType *) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6429 const SubstBuiltinTemplatePackType *) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6434 const TemplateSpecializationType*) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6439 const InjectedClassNameType* T) {
6440 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6441}
6442
6443bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6444 const DependentNameType* T) {
6445 return VisitNestedNameSpecifier(T->getQualifier());
6446}
6447
6448bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6449 const PackExpansionType* T) {
6450 return Visit(T->getPattern());
6451}
6452
6453bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6454 return false;
6455}
6456
6457bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6458 const ObjCInterfaceType *) {
6459 return false;
6460}
6461
6462bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6463 const ObjCObjectPointerType *) {
6464 return false;
6465}
6466
6467bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6468 return Visit(T->getValueType());
6469}
6470
6471bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6472 const OverflowBehaviorType *T) {
6473 return Visit(T->getUnderlyingType());
6474}
6475
6476bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6477 return false;
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6481 return false;
6482}
6483
6484bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6485 const ArrayParameterType *T) {
6486 return VisitConstantArrayType(T);
6487}
6488
6489bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6490 const DependentBitIntType *T) {
6491 return false;
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6495 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6496 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6497 ? diag::warn_cxx98_compat_template_arg_local_type
6498 : diag::ext_template_arg_local_type)
6499 << S.Context.getCanonicalTagType(Tag) << SR;
6500 return true;
6501 }
6502
6503 if (!Tag->hasNameForLinkage()) {
6504 S.Diag(SR.getBegin(),
6505 S.getLangOpts().CPlusPlus11 ?
6506 diag::warn_cxx98_compat_template_arg_unnamed_type :
6507 diag::ext_template_arg_unnamed_type) << SR;
6508 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6509 return true;
6510 }
6511
6512 return false;
6513}
6514
6515bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6516 NestedNameSpecifier NNS) {
6517 switch (NNS.getKind()) {
6522 return false;
6524 return Visit(QualType(NNS.getAsType(), 0));
6525 }
6526 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6527}
6528
6529bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6530 const HLSLAttributedResourceType *T) {
6531 if (T->hasContainedType() && Visit(T->getContainedType()))
6532 return true;
6533 return Visit(T->getWrappedType());
6534}
6535
6536bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6537 const HLSLInlineSpirvType *T) {
6538 for (auto &Operand : T->getOperands())
6539 if (Operand.isConstant() && Operand.isLiteral())
6540 if (Visit(Operand.getResultType()))
6541 return true;
6542 return false;
6543}
6544
6546 assert(ArgInfo && "invalid TypeSourceInfo");
6547 QualType Arg = ArgInfo->getType();
6548 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6549 QualType CanonArg = Context.getCanonicalType(Arg);
6550
6551 if (CanonArg->isVariablyModifiedType()) {
6552 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6553 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6554 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6555 }
6556
6557 // C++03 [temp.arg.type]p2:
6558 // A local type, a type with no linkage, an unnamed type or a type
6559 // compounded from any of these types shall not be used as a
6560 // template-argument for a template type-parameter.
6561 //
6562 // C++11 allows these, and even in C++03 we allow them as an extension with
6563 // a warning.
6564 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6565 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6566 (void)Finder.Visit(CanonArg);
6567 }
6568
6569 return false;
6570}
6571
6577
6578/// Determine whether the given template argument is a null pointer
6579/// value of the appropriate type.
6582 QualType ParamType, Expr *Arg,
6583 Decl *Entity = nullptr) {
6584 if (Arg->isValueDependent() || Arg->isTypeDependent())
6585 return NPV_NotNullPointer;
6586
6587 // dllimport'd entities aren't constant but are available inside of template
6588 // arguments.
6589 if (Entity && Entity->hasAttr<DLLImportAttr>())
6590 return NPV_NotNullPointer;
6591
6592 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6593 llvm_unreachable(
6594 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6595
6596 if (!S.getLangOpts().CPlusPlus11)
6597 return NPV_NotNullPointer;
6598
6599 // Determine whether we have a constant expression.
6601 if (ArgRV.isInvalid())
6602 return NPV_Error;
6603 Arg = ArgRV.get();
6604
6605 Expr::EvalResult EvalResult;
6607 EvalResult.Diag = &Notes;
6608 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6609 EvalResult.HasSideEffects) {
6610 SourceLocation DiagLoc = Arg->getExprLoc();
6611
6612 // If our only note is the usual "invalid subexpression" note, just point
6613 // the caret at its location rather than producing an essentially
6614 // redundant note.
6615 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6616 diag::note_invalid_subexpr_in_const_expr) {
6617 DiagLoc = Notes[0].first;
6618 Notes.clear();
6619 }
6620
6621 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6622 << Arg->getType() << Arg->getSourceRange();
6623 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6624 S.Diag(Notes[I].first, Notes[I].second);
6625
6627 return NPV_Error;
6628 }
6629
6630 // C++11 [temp.arg.nontype]p1:
6631 // - an address constant expression of type std::nullptr_t
6632 if (Arg->getType()->isNullPtrType())
6633 return NPV_NullPointer;
6634
6635 // - a constant expression that evaluates to a null pointer value (4.10); or
6636 // - a constant expression that evaluates to a null member pointer value
6637 // (4.11); or
6638 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6639 (EvalResult.Val.isMemberPointer() &&
6640 !EvalResult.Val.getMemberPointerDecl())) {
6641 // If our expression has an appropriate type, we've succeeded.
6642 bool ObjCLifetimeConversion;
6643 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6644 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6645 ObjCLifetimeConversion))
6646 return NPV_NullPointer;
6647
6648 // The types didn't match, but we know we got a null pointer; complain,
6649 // then recover as if the types were correct.
6650 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6651 << Arg->getType() << ParamType << Arg->getSourceRange();
6653 return NPV_NullPointer;
6654 }
6655
6656 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6657 // We found a pointer that isn't null, but doesn't refer to an object.
6658 // We could just return NPV_NotNullPointer, but we can print a better
6659 // message with the information we have here.
6660 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6661 << EvalResult.Val.getAsString(S.Context, ParamType);
6663 return NPV_Error;
6664 }
6665
6666 // If we don't have a null pointer value, but we do have a NULL pointer
6667 // constant, suggest a cast to the appropriate type.
6669 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6670 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6671 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6673 ")");
6675 return NPV_NullPointer;
6676 }
6677
6678 // FIXME: If we ever want to support general, address-constant expressions
6679 // as non-type template arguments, we should return the ExprResult here to
6680 // be interpreted by the caller.
6681 return NPV_NotNullPointer;
6682}
6683
6684/// Checks whether the given template argument is compatible with its
6685/// template parameter.
6686static bool
6688 QualType ParamType, Expr *ArgIn,
6689 Expr *Arg, QualType ArgType) {
6690 bool ObjCLifetimeConversion;
6691 if (ParamType->isPointerType() &&
6692 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6693 S.IsQualificationConversion(ArgType, ParamType, false,
6694 ObjCLifetimeConversion)) {
6695 // For pointer-to-object types, qualification conversions are
6696 // permitted.
6697 } else {
6698 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6699 if (!ParamRef->getPointeeType()->isFunctionType()) {
6700 // C++ [temp.arg.nontype]p5b3:
6701 // For a non-type template-parameter of type reference to
6702 // object, no conversions apply. The type referred to by the
6703 // reference may be more cv-qualified than the (otherwise
6704 // identical) type of the template- argument. The
6705 // template-parameter is bound directly to the
6706 // template-argument, which shall be an lvalue.
6707
6708 // FIXME: Other qualifiers?
6709 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6710 unsigned ArgQuals = ArgType.getCVRQualifiers();
6711
6712 if ((ParamQuals | ArgQuals) != ParamQuals) {
6713 S.Diag(Arg->getBeginLoc(),
6714 diag::err_template_arg_ref_bind_ignores_quals)
6715 << ParamType << Arg->getType() << Arg->getSourceRange();
6717 return true;
6718 }
6719 }
6720 }
6721
6722 // At this point, the template argument refers to an object or
6723 // function with external linkage. We now need to check whether the
6724 // argument and parameter types are compatible.
6725 if (!S.Context.hasSameUnqualifiedType(ArgType,
6726 ParamType.getNonReferenceType())) {
6727 // We can't perform this conversion or binding.
6728 if (ParamType->isReferenceType())
6729 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6730 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6731 else
6732 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6733 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6735 return true;
6736 }
6737 }
6738
6739 return false;
6740}
6741
6742/// Checks whether the given template argument is the address
6743/// of an object or function according to C++ [temp.arg.nontype]p1.
6745 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6746 bool IsSpecified, TemplateArgument &SugaredConverted,
6747 TemplateArgument &CanonicalConverted) {
6748 Expr *Arg = ArgIn;
6749 QualType ArgType = Arg->getType();
6750
6751 bool AddressTaken = false;
6752 SourceLocation AddrOpLoc;
6753 if (S.getLangOpts().MicrosoftExt) {
6754 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6755 // dereference and address-of operators.
6756 Arg = Arg->IgnoreParenCasts();
6757
6758 bool ExtWarnMSTemplateArg = false;
6759 UnaryOperatorKind FirstOpKind;
6760 SourceLocation FirstOpLoc;
6761 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6762 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6763 if (UnOpKind == UO_Deref)
6764 ExtWarnMSTemplateArg = true;
6765 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6766 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6767 if (!AddrOpLoc.isValid()) {
6768 FirstOpKind = UnOpKind;
6769 FirstOpLoc = UnOp->getOperatorLoc();
6770 }
6771 } else
6772 break;
6773 }
6774 if (FirstOpLoc.isValid()) {
6775 if (ExtWarnMSTemplateArg)
6776 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6777 << ArgIn->getSourceRange();
6778
6779 if (FirstOpKind == UO_AddrOf)
6780 AddressTaken = true;
6781 else if (Arg->getType()->isPointerType()) {
6782 // We cannot let pointers get dereferenced here, that is obviously not a
6783 // constant expression.
6784 assert(FirstOpKind == UO_Deref);
6785 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6786 << Arg->getSourceRange();
6787 }
6788 }
6789 } else {
6790 // See through any implicit casts we added to fix the type.
6791 // Also ignore parentheses for deduced template arguments.
6792 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6793
6794 // C++ [temp.arg.nontype]p1:
6795 //
6796 // A template-argument for a non-type, non-template
6797 // template-parameter shall be one of: [...]
6798 //
6799 // -- the address of an object or function with external
6800 // linkage, including function templates and function
6801 // template-ids but excluding non-static class members,
6802 // expressed as & id-expression where the & is optional if
6803 // the name refers to a function or array, or if the
6804 // corresponding template-parameter is a reference; or
6805
6806 // In C++98/03 mode, give an extension warning on any extra parentheses.
6807 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6808 if (IsSpecified) {
6809 bool ExtraParens = false;
6810 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6811 if (!ExtraParens) {
6812 S.DiagCompat(Arg->getBeginLoc(),
6813 diag_compat::template_arg_extra_parens)
6814 << Arg->getSourceRange();
6815 ExtraParens = true;
6816 }
6817
6818 Arg = Parens->getSubExpr();
6819 }
6820 }
6821
6822 while (SubstNonTypeTemplateParmExpr *subst =
6823 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6824 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6825
6826 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6827 if (UnOp->getOpcode() == UO_AddrOf) {
6828 Arg = UnOp->getSubExpr();
6829 AddressTaken = true;
6830 AddrOpLoc = UnOp->getOperatorLoc();
6831 }
6832 }
6833
6834 while (SubstNonTypeTemplateParmExpr *subst =
6835 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6836 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6837 }
6838
6839 ValueDecl *Entity = nullptr;
6840 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6841 Entity = DRE->getDecl();
6842 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6843 Entity = CUE->getGuidDecl();
6844
6845 // If our parameter has pointer type, check for a null template value.
6846 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6847 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6848 Entity)) {
6849 case NPV_NullPointer:
6850 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6851 SugaredConverted = TemplateArgument(ParamType,
6852 /*isNullPtr=*/true);
6853 CanonicalConverted =
6855 /*isNullPtr=*/true);
6856 return false;
6857
6858 case NPV_Error:
6859 return true;
6860
6861 case NPV_NotNullPointer:
6862 break;
6863 }
6864 }
6865
6866 // Stop checking the precise nature of the argument if it is value dependent,
6867 // it should be checked when instantiated.
6868 if (Arg->isValueDependent()) {
6869 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6870 CanonicalConverted =
6871 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6872 return false;
6873 }
6874
6875 if (!Entity) {
6876 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6877 << Arg->getSourceRange();
6879 return true;
6880 }
6881
6882 // Cannot refer to non-static data members
6883 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6884 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6885 << Entity << Arg->getSourceRange();
6887 return true;
6888 }
6889
6890 // Cannot refer to non-static member functions
6891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6892 if (!Method->isStatic()) {
6893 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6894 << Method << Arg->getSourceRange();
6896 return true;
6897 }
6898 }
6899
6900 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6901 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6902 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6903
6904 // A non-type template argument must refer to an object or function.
6905 if (!Func && !Var && !Guid) {
6906 // We found something, but we don't know specifically what it is.
6907 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6908 << Arg->getSourceRange();
6909 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6910 return true;
6911 }
6912
6913 // Address / reference template args must have external linkage in C++98.
6914 if (Entity->getFormalLinkage() == Linkage::Internal) {
6915 S.Diag(Arg->getBeginLoc(),
6916 S.getLangOpts().CPlusPlus11
6917 ? diag::warn_cxx98_compat_template_arg_object_internal
6918 : diag::ext_template_arg_object_internal)
6919 << !Func << Entity << Arg->getSourceRange();
6920 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6921 << !Func;
6922 } else if (!Entity->hasLinkage()) {
6923 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6924 << !Func << Entity << Arg->getSourceRange();
6925 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6926 << !Func;
6927 return true;
6928 }
6929
6930 if (Var) {
6931 // A value of reference type is not an object.
6932 if (Var->getType()->isReferenceType()) {
6933 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6934 << Var->getType() << Arg->getSourceRange();
6936 return true;
6937 }
6938
6939 // A template argument must have static storage duration.
6940 if (Var->getTLSKind()) {
6941 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6942 << Arg->getSourceRange();
6943 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6944 return true;
6945 }
6946 }
6947
6948 if (AddressTaken && ParamType->isReferenceType()) {
6949 // If we originally had an address-of operator, but the
6950 // parameter has reference type, complain and (if things look
6951 // like they will work) drop the address-of operator.
6952 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6953 ParamType.getNonReferenceType())) {
6954 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6955 << ParamType;
6957 return true;
6958 }
6959
6960 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6961 << ParamType
6962 << FixItHint::CreateRemoval(AddrOpLoc);
6964
6965 ArgType = Entity->getType();
6966 }
6967
6968 // If the template parameter has pointer type, either we must have taken the
6969 // address or the argument must decay to a pointer.
6970 if (!AddressTaken && ParamType->isPointerType()) {
6971 if (Func) {
6972 // Function-to-pointer decay.
6973 ArgType = S.Context.getPointerType(Func->getType());
6974 } else if (Entity->getType()->isArrayType()) {
6975 // Array-to-pointer decay.
6976 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6977 } else {
6978 // If the template parameter has pointer type but the address of
6979 // this object was not taken, complain and (possibly) recover by
6980 // taking the address of the entity.
6981 ArgType = S.Context.getPointerType(Entity->getType());
6982 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6983 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6984 << ParamType;
6986 return true;
6987 }
6988
6989 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6990 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6991
6993 }
6994 }
6995
6996 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6997 Arg, ArgType))
6998 return true;
6999
7000 // Create the template argument.
7001 SugaredConverted = TemplateArgument(Entity, ParamType);
7002 CanonicalConverted =
7004 S.Context.getCanonicalType(ParamType));
7005 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7006 return false;
7007}
7008
7009/// Checks whether the given template argument is a pointer to
7010/// member constant according to C++ [temp.arg.nontype]p1.
7012 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7013 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7014 bool Invalid = false;
7015
7016 Expr *Arg = ResultArg;
7017 bool ObjCLifetimeConversion;
7018
7019 // C++ [temp.arg.nontype]p1:
7020 //
7021 // A template-argument for a non-type, non-template
7022 // template-parameter shall be one of: [...]
7023 //
7024 // -- a pointer to member expressed as described in 5.3.1.
7025 DeclRefExpr *DRE = nullptr;
7026
7027 // In C++98/03 mode, give an extension warning on any extra parentheses.
7028 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7029 bool ExtraParens = false;
7030 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7031 if (!Invalid && !ExtraParens) {
7032 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7033 << Arg->getSourceRange();
7034 ExtraParens = true;
7035 }
7036
7037 Arg = Parens->getSubExpr();
7038 }
7039
7040 while (SubstNonTypeTemplateParmExpr *subst =
7041 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7042 Arg = subst->getReplacement()->IgnoreImpCasts();
7043
7044 // A pointer-to-member constant written &Class::member.
7045 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7046 if (UnOp->getOpcode() == UO_AddrOf) {
7047 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7048 if (DRE && !DRE->getQualifier())
7049 DRE = nullptr;
7050 }
7051 }
7052 // A constant of pointer-to-member type.
7053 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7054 ValueDecl *VD = DRE->getDecl();
7055 if (VD->getType()->isMemberPointerType()) {
7057 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7058 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7059 CanonicalConverted =
7060 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7061 } else {
7062 SugaredConverted = TemplateArgument(VD, ParamType);
7063 CanonicalConverted =
7065 S.Context.getCanonicalType(ParamType));
7066 }
7067 return Invalid;
7068 }
7069 }
7070
7071 DRE = nullptr;
7072 }
7073
7074 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7075
7076 // Check for a null pointer value.
7077 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7078 Entity)) {
7079 case NPV_Error:
7080 return true;
7081 case NPV_NullPointer:
7082 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7083 SugaredConverted = TemplateArgument(ParamType,
7084 /*isNullPtr*/ true);
7085 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7086 /*isNullPtr*/ true);
7087 return false;
7088 case NPV_NotNullPointer:
7089 break;
7090 }
7091
7092 if (S.IsQualificationConversion(ResultArg->getType(),
7093 ParamType.getNonReferenceType(), false,
7094 ObjCLifetimeConversion)) {
7095 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7096 ResultArg->getValueKind())
7097 .get();
7098 } else if (!S.Context.hasSameUnqualifiedType(
7099 ResultArg->getType(), ParamType.getNonReferenceType())) {
7100 // We can't perform this conversion.
7101 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7102 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7104 return true;
7105 }
7106
7107 if (!DRE)
7108 return S.Diag(Arg->getBeginLoc(),
7109 diag::err_template_arg_not_pointer_to_member_form)
7110 << Arg->getSourceRange();
7111
7112 if (isa<FieldDecl>(DRE->getDecl()) ||
7114 isa<CXXMethodDecl>(DRE->getDecl())) {
7115 assert((isa<FieldDecl>(DRE->getDecl()) ||
7118 ->isImplicitObjectMemberFunction()) &&
7119 "Only non-static member pointers can make it here");
7120
7121 // Okay: this is the address of a non-static member, and therefore
7122 // a member pointer constant.
7123 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7124 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7125 CanonicalConverted =
7126 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7127 } else {
7128 ValueDecl *D = DRE->getDecl();
7129 SugaredConverted = TemplateArgument(D, ParamType);
7130 CanonicalConverted =
7132 S.Context.getCanonicalType(ParamType));
7133 }
7134 return Invalid;
7135 }
7136
7137 // We found something else, but we don't know specifically what it is.
7138 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7139 << Arg->getSourceRange();
7140 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7141 return true;
7142}
7143
7144/// Check a template argument against its corresponding
7145/// non-type template parameter.
7146///
7147/// This routine implements the semantics of C++ [temp.arg.nontype].
7148/// If an error occurred, it returns ExprError(); otherwise, it
7149/// returns the converted template argument. \p ParamType is the
7150/// type of the non-type template parameter after it has been instantiated.
7152 Expr *Arg,
7153 TemplateArgument &SugaredConverted,
7154 TemplateArgument &CanonicalConverted,
7155 bool StrictCheck,
7157 SourceLocation StartLoc = Arg->getBeginLoc();
7158 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7159 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7160 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7161 DeductionArg = NewDeductionArg;
7162 if (ArgPE) {
7163 // Recreate a pack expansion if we unwrapped one.
7164 Arg = new (Context) PackExpansionExpr(
7165 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7166 } else {
7167 Arg = DeductionArg;
7168 }
7169 };
7170
7171 // If the parameter type somehow involves auto, deduce the type now.
7172 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7173 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7174 if (IsDeduced) {
7175 // When checking a deduced template argument, deduce from its type even if
7176 // the type is dependent, in order to check the types of non-type template
7177 // arguments line up properly in partial ordering.
7178 TypeSourceInfo *TSI =
7179 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7181 InitializedEntity Entity =
7184 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7185 Expr *Inits[1] = {DeductionArg};
7186 ParamType =
7188 if (ParamType.isNull())
7189 return ExprError();
7190 } else {
7191 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7192 Param->getTemplateDepth() + 1);
7193 ParamType = QualType();
7195 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7196 /*DependentDeduction=*/true,
7197 // We do not check constraints right now because the
7198 // immediately-declared constraint of the auto type is
7199 // also an associated constraint, and will be checked
7200 // along with the other associated constraints after
7201 // checking the template argument list.
7202 /*IgnoreConstraints=*/true);
7204 ParamType = TSI->getType();
7205 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7207 return ExprError();
7208 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7209 Diag(Arg->getExprLoc(),
7210 diag::err_non_type_template_parm_type_deduction_failure)
7211 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7212 << Arg->getSourceRange();
7214 return ExprError();
7215 }
7216 ParamType = SubstAutoTypeDependent(ParamType);
7217 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7218 }
7219 }
7220 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7221 // an error. The error message normally references the parameter
7222 // declaration, but here we'll pass the argument location because that's
7223 // where the parameter type is deduced.
7224 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7225 if (ParamType.isNull()) {
7227 return ExprError();
7228 }
7229 }
7230
7231 // We should have already dropped all cv-qualifiers by now.
7232 assert(!ParamType.hasQualifiers() &&
7233 "non-type template parameter type cannot be qualified");
7234
7235 // If either the parameter has a dependent type or the argument is
7236 // type-dependent, there's nothing we can check now.
7237 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7238 // Force the argument to the type of the parameter to maintain invariants.
7239 if (!IsDeduced) {
7241 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7242 ParamType->isLValueReferenceType() ? VK_LValue
7243 : ParamType->isRValueReferenceType() ? VK_XValue
7244 : VK_PRValue);
7245 if (E.isInvalid())
7246 return ExprError();
7247 setDeductionArg(E.get());
7248 }
7249 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7250 CanonicalConverted = TemplateArgument(
7251 Context.getCanonicalTemplateArgument(SugaredConverted));
7252 return Arg;
7253 }
7254
7255 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7256 if (CTAK == CTAK_Deduced && !StrictCheck &&
7257 (ParamType->isReferenceType()
7258 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7259 DeductionArg->getType())
7260 : !Context.hasSameUnqualifiedType(ParamType,
7261 DeductionArg->getType()))) {
7262 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7263 // we should actually be checking the type of the template argument in P,
7264 // not the type of the template argument deduced from A, against the
7265 // template parameter type.
7266 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7267 << Arg->getType() << ParamType.getUnqualifiedType();
7269 return ExprError();
7270 }
7271
7272 // If the argument is a pack expansion, we don't know how many times it would
7273 // expand. If we continue checking the argument, this will make the template
7274 // definition ill-formed if it would be ill-formed for any number of
7275 // expansions during instantiation time. When partial ordering or matching
7276 // template template parameters, this is exactly what we want. Otherwise, the
7277 // normal template rules apply: we accept the template if it would be valid
7278 // for any number of expansions (i.e. none).
7279 if (ArgPE && !StrictCheck) {
7280 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7281 CanonicalConverted = TemplateArgument(
7282 Context.getCanonicalTemplateArgument(SugaredConverted));
7283 return Arg;
7284 }
7285
7286 // Avoid making a copy when initializing a template parameter of class type
7287 // from a template parameter object of the same type. This is going beyond
7288 // the standard, but is required for soundness: in
7289 // template<A a> struct X { X *p; X<a> *q; };
7290 // ... we need p and q to have the same type.
7291 //
7292 // Similarly, don't inject a call to a copy constructor when initializing
7293 // from a template parameter of the same type.
7294 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7295 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7296 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7297 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7298 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7299
7300 SugaredConverted = TemplateArgument(TPO, ParamType);
7301 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7302 ParamType.getCanonicalType());
7303 return Arg;
7304 }
7306 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7307 CanonicalConverted =
7308 Context.getCanonicalTemplateArgument(SugaredConverted);
7309 return Arg;
7310 }
7311 }
7312
7313 // The initialization of the parameter from the argument is
7314 // a constant-evaluated context.
7317
7318 bool IsConvertedConstantExpression = true;
7319 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7321 StartLoc, /*DirectInit=*/false, DeductionArg);
7322 Expr *Inits[1] = {DeductionArg};
7323 InitializedEntity Entity =
7325 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7326 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7327 if (Result.isInvalid() || !Result.get())
7328 return ExprError();
7330 if (Result.isInvalid() || !Result.get())
7331 return ExprError();
7332 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7333 /*DiscardedValue=*/false,
7334 /*IsConstexpr=*/true,
7335 /*IsTemplateArgument=*/true)
7336 .get());
7337 IsConvertedConstantExpression = false;
7338 }
7339
7340 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7341 // C++17 [temp.arg.nontype]p1:
7342 // A template-argument for a non-type template parameter shall be
7343 // a converted constant expression of the type of the template-parameter.
7344 APValue Value;
7345 ExprResult ArgResult;
7346 if (IsConvertedConstantExpression) {
7348 DeductionArg, ParamType,
7349 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7350 assert(!ArgResult.isUnset());
7351 if (ArgResult.isInvalid()) {
7353 return ExprError();
7354 }
7355 } else {
7356 ArgResult = DeductionArg;
7357 }
7358
7359 // For a value-dependent argument, CheckConvertedConstantExpression is
7360 // permitted (and expected) to be unable to determine a value.
7361 if (ArgResult.get()->isValueDependent()) {
7362 setDeductionArg(ArgResult.get());
7363 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7364 CanonicalConverted =
7365 Context.getCanonicalTemplateArgument(SugaredConverted);
7366 return Arg;
7367 }
7368
7369 APValue PreNarrowingValue;
7371 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7372 false, PreNarrowingValue);
7373 if (ArgResult.isInvalid())
7374 return ExprError();
7375 setDeductionArg(ArgResult.get());
7376
7377 if (Value.isLValue()) {
7378 APValue::LValueBase Base = Value.getLValueBase();
7379 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7380 // For a non-type template-parameter of pointer or reference type,
7381 // the value of the constant expression shall not refer to
7382 assert(ParamType->isPointerOrReferenceType() ||
7383 ParamType->isNullPtrType());
7384 // -- a temporary object
7385 // -- a string literal
7386 // -- the result of a typeid expression, or
7387 // -- a predefined __func__ variable
7388 if (Base &&
7389 (!VD ||
7391 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7392 << Arg->getSourceRange();
7393 return ExprError();
7394 }
7395
7396 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7397 VD->getType()->isArrayType() &&
7398 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7399 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7400 if (ArgPE) {
7401 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7402 CanonicalConverted =
7403 Context.getCanonicalTemplateArgument(SugaredConverted);
7404 } else {
7405 SugaredConverted = TemplateArgument(VD, ParamType);
7406 CanonicalConverted =
7407 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7408 ParamType.getCanonicalType());
7409 }
7410 return Arg;
7411 }
7412
7413 // -- a subobject [until C++20]
7414 if (!getLangOpts().CPlusPlus20) {
7415 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7416 Value.isLValueOnePastTheEnd()) {
7417 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7418 << Value.getAsString(Context, ParamType);
7419 return ExprError();
7420 }
7421 assert((VD || !ParamType->isReferenceType()) &&
7422 "null reference should not be a constant expression");
7423 assert((!VD || !ParamType->isNullPtrType()) &&
7424 "non-null value of type nullptr_t?");
7425 }
7426 }
7427
7428 if (Value.isAddrLabelDiff())
7429 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7430
7431 if (ArgPE) {
7432 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7433 CanonicalConverted =
7434 Context.getCanonicalTemplateArgument(SugaredConverted);
7435 } else {
7436 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7437 CanonicalConverted =
7439 }
7440 return Arg;
7441 }
7442
7443 // These should have all been handled above using the C++17 rules.
7444 assert(!ArgPE && !StrictCheck);
7445
7446 // C++ [temp.arg.nontype]p5:
7447 // The following conversions are performed on each expression used
7448 // as a non-type template-argument. If a non-type
7449 // template-argument cannot be converted to the type of the
7450 // corresponding template-parameter then the program is
7451 // ill-formed.
7452 if (ParamType->isIntegralOrEnumerationType()) {
7453 // C++11:
7454 // -- for a non-type template-parameter of integral or
7455 // enumeration type, conversions permitted in a converted
7456 // constant expression are applied.
7457 //
7458 // C++98:
7459 // -- for a non-type template-parameter of integral or
7460 // enumeration type, integral promotions (4.5) and integral
7461 // conversions (4.7) are applied.
7462
7463 if (getLangOpts().CPlusPlus11) {
7464 // C++ [temp.arg.nontype]p1:
7465 // A template-argument for a non-type, non-template template-parameter
7466 // shall be one of:
7467 //
7468 // -- for a non-type template-parameter of integral or enumeration
7469 // type, a converted constant expression of the type of the
7470 // template-parameter; or
7471 llvm::APSInt Value;
7473 Arg, ParamType, Value, CCEKind::TemplateArg);
7474 if (ArgResult.isInvalid())
7475 return ExprError();
7476 Arg = ArgResult.get();
7477
7478 // We can't check arbitrary value-dependent arguments.
7479 if (Arg->isValueDependent()) {
7480 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7481 CanonicalConverted =
7482 Context.getCanonicalTemplateArgument(SugaredConverted);
7483 return Arg;
7484 }
7485
7486 // Widen the argument value to sizeof(parameter type). This is almost
7487 // always a no-op, except when the parameter type is bool. In
7488 // that case, this may extend the argument from 1 bit to 8 bits.
7489 QualType IntegerType = ParamType;
7490 if (const auto *ED = IntegerType->getAsEnumDecl())
7491 IntegerType = ED->getIntegerType();
7492 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7493 ? Context.getIntWidth(IntegerType)
7494 : Context.getTypeSize(IntegerType));
7495
7496 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7497 CanonicalConverted =
7498 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7499 return Arg;
7500 }
7501
7502 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7503 if (ArgResult.isInvalid())
7504 return ExprError();
7505 Arg = ArgResult.get();
7506
7507 QualType ArgType = Arg->getType();
7508
7509 // C++ [temp.arg.nontype]p1:
7510 // A template-argument for a non-type, non-template
7511 // template-parameter shall be one of:
7512 //
7513 // -- an integral constant-expression of integral or enumeration
7514 // type; or
7515 // -- the name of a non-type template-parameter; or
7516 llvm::APSInt Value;
7517 if (!ArgType->isIntegralOrEnumerationType()) {
7518 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7519 << ArgType << Arg->getSourceRange();
7521 return ExprError();
7522 }
7523 if (!Arg->isValueDependent()) {
7524 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7525 QualType T;
7526
7527 public:
7528 TmplArgICEDiagnoser(QualType T) : T(T) { }
7529
7530 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7531 SourceLocation Loc) override {
7532 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7533 }
7534 } Diagnoser(ArgType);
7535
7536 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7537 if (!Arg)
7538 return ExprError();
7539 }
7540
7541 // From here on out, all we care about is the unqualified form
7542 // of the argument type.
7543 ArgType = ArgType.getUnqualifiedType();
7544
7545 // Try to convert the argument to the parameter's type.
7546 if (Context.hasSameType(ParamType, ArgType)) {
7547 // Okay: no conversion necessary
7548 } else if (ParamType->isBooleanType()) {
7549 // This is an integral-to-boolean conversion.
7550 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7551 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7552 !ParamType->isEnumeralType()) {
7553 // This is an integral promotion or conversion.
7554 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7555 } else {
7556 // We can't perform this conversion.
7557 Diag(StartLoc, diag::err_template_arg_not_convertible)
7558 << Arg->getType() << ParamType << Arg->getSourceRange();
7560 return ExprError();
7561 }
7562
7563 // Add the value of this argument to the list of converted
7564 // arguments. We use the bitwidth and signedness of the template
7565 // parameter.
7566 if (Arg->isValueDependent()) {
7567 // The argument is value-dependent. Create a new
7568 // TemplateArgument with the converted expression.
7569 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7570 CanonicalConverted =
7571 Context.getCanonicalTemplateArgument(SugaredConverted);
7572 return Arg;
7573 }
7574
7575 QualType IntegerType = ParamType;
7576 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7577 IntegerType = ED->getIntegerType();
7578 }
7579
7580 if (ParamType->isBooleanType()) {
7581 // Value must be zero or one.
7582 Value = Value != 0;
7583 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7584 if (Value.getBitWidth() != AllowedBits)
7585 Value = Value.extOrTrunc(AllowedBits);
7586 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7587 } else {
7588 llvm::APSInt OldValue = Value;
7589
7590 // Coerce the template argument's value to the value it will have
7591 // based on the template parameter's type.
7592 unsigned AllowedBits = IntegerType->isBitIntType()
7593 ? Context.getIntWidth(IntegerType)
7594 : Context.getTypeSize(IntegerType);
7595 if (Value.getBitWidth() != AllowedBits)
7596 Value = Value.extOrTrunc(AllowedBits);
7597 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7598
7599 // Complain if an unsigned parameter received a negative value.
7600 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7601 (OldValue.isSigned() && OldValue.isNegative())) {
7602 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7603 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7604 << Arg->getSourceRange();
7606 }
7607
7608 // Complain if we overflowed the template parameter's type.
7609 unsigned RequiredBits;
7610 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7611 RequiredBits = OldValue.getActiveBits();
7612 else if (OldValue.isUnsigned())
7613 RequiredBits = OldValue.getActiveBits() + 1;
7614 else
7615 RequiredBits = OldValue.getSignificantBits();
7616 if (RequiredBits > AllowedBits) {
7617 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7618 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7619 << Arg->getSourceRange();
7621 }
7622 }
7623
7624 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7625 SugaredConverted = TemplateArgument(Context, Value, T);
7626 CanonicalConverted =
7627 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7628 return Arg;
7629 }
7630
7631 QualType ArgType = Arg->getType();
7632 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7633 bool IsSpecified = CTAK == CTAK_Specified;
7634
7635 // Handle pointer-to-function, reference-to-function, and
7636 // pointer-to-member-function all in (roughly) the same way.
7637 if (// -- For a non-type template-parameter of type pointer to
7638 // function, only the function-to-pointer conversion (4.3) is
7639 // applied. If the template-argument represents a set of
7640 // overloaded functions (or a pointer to such), the matching
7641 // function is selected from the set (13.4).
7642 (ParamType->isPointerType() &&
7643 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7644 // -- For a non-type template-parameter of type reference to
7645 // function, no conversions apply. If the template-argument
7646 // represents a set of overloaded functions, the matching
7647 // function is selected from the set (13.4).
7648 (ParamType->isReferenceType() &&
7649 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7650 // -- For a non-type template-parameter of type pointer to
7651 // member function, no conversions apply. If the
7652 // template-argument represents a set of overloaded member
7653 // functions, the matching member function is selected from
7654 // the set (13.4).
7655 (ParamType->isMemberPointerType() &&
7656 ParamType->castAs<MemberPointerType>()->getPointeeType()
7657 ->isFunctionType())) {
7658
7659 if (Arg->getType() == Context.OverloadTy) {
7660 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7661 true,
7662 FoundResult)) {
7663 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7664 return ExprError();
7665
7666 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7667 if (Res.isInvalid())
7668 return ExprError();
7669 Arg = Res.get();
7670 ArgType = Arg->getType();
7671 } else
7672 return ExprError();
7673 }
7674
7675 if (!ParamType->isMemberPointerType()) {
7677 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7678 CanonicalConverted))
7679 return ExprError();
7680 return Arg;
7681 }
7682
7684 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7685 return ExprError();
7686 return Arg;
7687 }
7688
7689 if (ParamType->isPointerType()) {
7690 // -- for a non-type template-parameter of type pointer to
7691 // object, qualification conversions (4.4) and the
7692 // array-to-pointer conversion (4.2) are applied.
7693 // C++0x also allows a value of std::nullptr_t.
7694 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7695 "Only object pointers allowed here");
7696
7698 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7699 CanonicalConverted))
7700 return ExprError();
7701 return Arg;
7702 }
7703
7704 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7705 // -- For a non-type template-parameter of type reference to
7706 // object, no conversions apply. The type referred to by the
7707 // reference may be more cv-qualified than the (otherwise
7708 // identical) type of the template-argument. The
7709 // template-parameter is bound directly to the
7710 // template-argument, which must be an lvalue.
7711 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7712 "Only object references allowed here");
7713
7714 if (Arg->getType() == Context.OverloadTy) {
7716 ParamRefType->getPointeeType(),
7717 true,
7718 FoundResult)) {
7719 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7720 return ExprError();
7721 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7722 if (Res.isInvalid())
7723 return ExprError();
7724 Arg = Res.get();
7725 ArgType = Arg->getType();
7726 } else
7727 return ExprError();
7728 }
7729
7731 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7732 CanonicalConverted))
7733 return ExprError();
7734 return Arg;
7735 }
7736
7737 // Deal with parameters of type std::nullptr_t.
7738 if (ParamType->isNullPtrType()) {
7739 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7740 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7741 CanonicalConverted =
7742 Context.getCanonicalTemplateArgument(SugaredConverted);
7743 return Arg;
7744 }
7745
7746 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7747 case NPV_NotNullPointer:
7748 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7749 << Arg->getType() << ParamType;
7751 return ExprError();
7752
7753 case NPV_Error:
7754 return ExprError();
7755
7756 case NPV_NullPointer:
7757 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7758 SugaredConverted = TemplateArgument(ParamType,
7759 /*isNullPtr=*/true);
7760 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7761 /*isNullPtr=*/true);
7762 return Arg;
7763 }
7764 }
7765
7766 // -- For a non-type template-parameter of type pointer to data
7767 // member, qualification conversions (4.4) are applied.
7768 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7769
7771 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7772 return ExprError();
7773 return Arg;
7774}
7775
7779
7782 const TemplateArgumentLoc &Arg) {
7783 // C++0x [temp.arg.template]p1:
7784 // A template-argument for a template template-parameter shall be
7785 // the name of a class template or an alias template, expressed as an
7786 // id-expression. When the template-argument names a class template, only
7787 // primary class templates are considered when matching the
7788 // template template argument with the corresponding parameter;
7789 // partial specializations are not considered even if their
7790 // parameter lists match that of the template template parameter.
7791 //
7792
7794 unsigned DiagFoundKind = 0;
7795
7796 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7797 switch (TTP->templateParameterKind()) {
7799 DiagFoundKind = 3;
7800 break;
7802 DiagFoundKind = 2;
7803 break;
7804 default:
7805 DiagFoundKind = 1;
7806 break;
7807 }
7808 Kind = TTP->templateParameterKind();
7809 } else if (isa<ConceptDecl>(Template)) {
7811 DiagFoundKind = 3;
7812 } else if (isa<FunctionTemplateDecl>(Template)) {
7814 DiagFoundKind = 0;
7815 } else if (isa<VarTemplateDecl>(Template)) {
7817 DiagFoundKind = 2;
7818 } else if (isa<ClassTemplateDecl>(Template) ||
7822 DiagFoundKind = 1;
7823 } else {
7824 assert(false && "Unexpected Decl");
7825 }
7826
7827 if (Kind == Param->templateParameterKind()) {
7828 return true;
7829 }
7830
7831 unsigned DiagKind = 0;
7832 switch (Param->templateParameterKind()) {
7834 DiagKind = 2;
7835 break;
7837 DiagKind = 1;
7838 break;
7839 default:
7840 DiagKind = 0;
7841 break;
7842 }
7843 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7844 << DiagKind;
7845 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7846 << DiagFoundKind << Template;
7847 return false;
7848}
7849
7850/// Check a template argument against its corresponding
7851/// template template parameter.
7852///
7853/// This routine implements the semantics of C++ [temp.arg.template].
7854/// It returns true if an error occurred, and false otherwise.
7856 TemplateParameterList *Params,
7858 bool PartialOrdering,
7859 bool *StrictPackMatch) {
7861 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7862 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7863 if (!Template) {
7864 // FIXME: Handle AssumedTemplateNames
7865 // Any dependent template name is fine.
7866 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7867 return false;
7868 }
7869
7870 if (Template->isInvalidDecl())
7871 return true;
7872
7874 return true;
7875 }
7876
7877 // C++1z [temp.arg.template]p3: (DR 150)
7878 // A template-argument matches a template template-parameter P when P
7879 // is at least as specialized as the template-argument A.
7881 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7882 PartialOrdering, StrictPackMatch))
7883 return true;
7884 // P2113
7885 // C++20[temp.func.order]p2
7886 // [...] If both deductions succeed, the partial ordering selects the
7887 // more constrained template (if one exists) as determined below.
7888 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7889 Params->getAssociatedConstraints(ParamsAC);
7890 // C++20[temp.arg.template]p3
7891 // [...] In this comparison, if P is unconstrained, the constraints on A
7892 // are not considered.
7893 if (ParamsAC.empty())
7894 return false;
7895
7896 Template->getAssociatedConstraints(TemplateAC);
7897
7898 bool IsParamAtLeastAsConstrained;
7899 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7900 IsParamAtLeastAsConstrained))
7901 return true;
7902 if (!IsParamAtLeastAsConstrained) {
7903 Diag(Arg.getLocation(),
7904 diag::err_template_template_parameter_not_at_least_as_constrained)
7905 << Template << Param << Arg.getSourceRange();
7906 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7907 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7909 TemplateAC);
7910 return true;
7911 }
7912 return false;
7913}
7914
7916 unsigned HereDiagID,
7917 unsigned ExternalDiagID) {
7918 if (Decl.getLocation().isValid())
7919 return S.Diag(Decl.getLocation(), HereDiagID);
7920
7921 SmallString<128> Str;
7922 llvm::raw_svector_ostream Out(Str);
7924 PP.TerseOutput = 1;
7925 Decl.print(Out, PP);
7926 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7927}
7928
7930 std::optional<SourceRange> ParamRange) {
7932 noteLocation(*this, Decl, diag::note_template_decl_here,
7933 diag::note_template_decl_external);
7934 if (ParamRange && ParamRange->isValid()) {
7935 assert(Decl.getLocation().isValid() &&
7936 "Parameter range has location when Decl does not");
7937 DB << *ParamRange;
7938 }
7939}
7940
7942 noteLocation(*this, Decl, diag::note_template_param_here,
7943 diag::note_template_param_external);
7944}
7945
7946/// Given a non-type template argument that refers to a
7947/// declaration and the type of its corresponding non-type template
7948/// parameter, produce an expression that properly refers to that
7949/// declaration.
7951 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7952 // C++ [temp.param]p8:
7953 //
7954 // A non-type template-parameter of type "array of T" or
7955 // "function returning T" is adjusted to be of type "pointer to
7956 // T" or "pointer to function returning T", respectively.
7957 if (ParamType->isArrayType())
7958 ParamType = Context.getArrayDecayedType(ParamType);
7959 else if (ParamType->isFunctionType())
7960 ParamType = Context.getPointerType(ParamType);
7961
7962 // For a NULL non-type template argument, return nullptr casted to the
7963 // parameter's type.
7964 if (Arg.getKind() == TemplateArgument::NullPtr) {
7965 return ImpCastExprToType(
7966 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7967 ParamType,
7968 ParamType->getAs<MemberPointerType>()
7969 ? CK_NullToMemberPointer
7970 : CK_NullToPointer);
7971 }
7972 assert(Arg.getKind() == TemplateArgument::Declaration &&
7973 "Only declaration template arguments permitted here");
7974
7975 ValueDecl *VD = Arg.getAsDecl();
7976
7977 CXXScopeSpec SS;
7978 if (ParamType->isMemberPointerType()) {
7979 // If this is a pointer to member, we need to use a qualified name to
7980 // form a suitable pointer-to-member constant.
7981 assert(VD->getDeclContext()->isRecord() &&
7982 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7984 CanQualType ClassType =
7985 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7986 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7987 SS.MakeTrivial(Context, Qualifier, Loc);
7988 }
7989
7991 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7992 if (RefExpr.isInvalid())
7993 return ExprError();
7994
7995 // For a pointer, the argument declaration is the pointee. Take its address.
7996 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7997 if (ParamType->isPointerType() && !ElemT.isNull() &&
7998 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7999 // Decay an array argument if we want a pointer to its first element.
8000 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8001 if (RefExpr.isInvalid())
8002 return ExprError();
8003 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8004 // For any other pointer, take the address (or form a pointer-to-member).
8005 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8006 if (RefExpr.isInvalid())
8007 return ExprError();
8008 } else if (ParamType->isRecordType()) {
8009 assert(isa<TemplateParamObjectDecl>(VD) &&
8010 "arg for class template param not a template parameter object");
8011 // No conversions apply in this case.
8012 return RefExpr;
8013 } else {
8014 assert(ParamType->isReferenceType() &&
8015 "unexpected type for decl template argument");
8016 // If the parameter has reference type, wrap it in paretheses so that this
8017 // expression will have the correct type under `decltype`.
8018 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8019 }
8020
8021 // At this point we should have the right value category.
8022 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8023 "value kind mismatch for non-type template argument");
8024
8025 // The type of the template parameter can differ from the type of the
8026 // argument in various ways; convert it now if necessary.
8027 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8028 QualType SrcExprType = RefExpr.get()->getType();
8029 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8030 CastKind CK;
8031 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8032 IsFunctionConversion(SrcExprType, DestExprType)) {
8033 CK = CK_NoOp;
8034 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8035 CK = CK_BitCast;
8036 } else {
8037 // FIXME: Pointers to members can need conversion derived-to-base or
8038 // base-to-derived conversions. We currently don't retain enough
8039 // information to convert properly (we need to track a cast path or
8040 // subobject number in the template argument).
8041 llvm_unreachable(
8042 "unexpected conversion required for non-type template argument");
8043 }
8044 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8045 RefExpr.get()->getValueKind());
8046 }
8047
8048 return RefExpr;
8049}
8050
8051/// Construct a new expression that refers to the given
8052/// integral template argument with the given source-location
8053/// information.
8054///
8055/// This routine takes care of the mapping from an integral template
8056/// argument (which may have any integral type) to the appropriate
8057/// literal value.
8059 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8060 assert(OrigT->isIntegralOrEnumerationType());
8061
8062 // If this is an enum type that we're instantiating, we need to use an integer
8063 // type the same size as the enumerator. We don't want to build an
8064 // IntegerLiteral with enum type. The integer type of an enum type can be of
8065 // any integral type with C++11 enum classes, make sure we create the right
8066 // type of literal for it.
8067 QualType T = OrigT;
8068 if (const auto *ED = OrigT->getAsEnumDecl())
8069 T = ED->getIntegerType();
8070
8071 Expr *E;
8072 if (T->isAnyCharacterType()) {
8074 if (T->isWideCharType())
8076 else if (T->isChar8Type() && S.getLangOpts().Char8)
8078 else if (T->isChar16Type())
8080 else if (T->isChar32Type())
8082 else
8084
8085 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8086 } else if (T->isBooleanType()) {
8087 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8088 } else {
8089 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8090 }
8091
8092 if (OrigT->isEnumeralType()) {
8093 // FIXME: This is a hack. We need a better way to handle substituted
8094 // non-type template parameters.
8095 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8096 nullptr, S.CurFPFeatureOverrides(),
8097 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8098 Loc, Loc);
8099 }
8100
8101 return E;
8102}
8103
8105 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8106 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8107 auto *ILE = new (S.Context)
8108 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8109 ILE->setType(T);
8110 return ILE;
8111 };
8112
8113 switch (Val.getKind()) {
8115 // This cannot occur in a template argument at all.
8116 case APValue::Array:
8117 case APValue::Struct:
8118 case APValue::Union:
8119 // These can only occur within a template parameter object, which is
8120 // represented as a TemplateArgument::Declaration.
8121 llvm_unreachable("unexpected template argument value");
8122
8123 case APValue::Int:
8125 Loc);
8126
8127 case APValue::Float:
8128 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8129 T, Loc);
8130
8133 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8134 Val.getFixedPoint().getScale());
8135
8136 case APValue::ComplexInt: {
8137 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8139 S, ElemT, Val.getComplexIntReal(), Loc),
8141 S, ElemT, Val.getComplexIntImag(), Loc)});
8142 }
8143
8144 case APValue::ComplexFloat: {
8145 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8146 return MakeInitList(
8148 ElemT, Loc),
8150 ElemT, Loc)});
8151 }
8152
8153 case APValue::Vector: {
8154 QualType ElemT = T->castAs<VectorType>()->getElementType();
8156 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8158 S, ElemT, Val.getVectorElt(I), Loc));
8159 return MakeInitList(Elts);
8160 }
8161
8162 case APValue::Matrix:
8163 llvm_unreachable("Matrix template argument expression not yet supported");
8164
8165 case APValue::None:
8167 llvm_unreachable("Unexpected APValue kind.");
8168 case APValue::LValue:
8170 // There isn't necessarily a valid equivalent source-level syntax for
8171 // these; in particular, a naive lowering might violate access control.
8172 // So for now we lower to a ConstantExpr holding the value, wrapped around
8173 // an OpaqueValueExpr.
8174 // FIXME: We should have a better representation for this.
8176 if (T->isReferenceType()) {
8177 T = T->getPointeeType();
8178 VK = VK_LValue;
8179 }
8180 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8181 return ConstantExpr::Create(S.Context, OVE, Val);
8182 }
8183 llvm_unreachable("Unhandled APValue::ValueKind enum");
8184}
8185
8188 SourceLocation Loc) {
8189 switch (Arg.getKind()) {
8195 llvm_unreachable("not a non-type template argument");
8196
8198 return Arg.getAsExpr();
8199
8203 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8204
8207 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8208
8211 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8212 }
8213 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8214}
8215
8216/// Match two template parameters within template parameter lists.
8218 Sema &S, NamedDecl *New,
8219 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8220 const NamedDecl *OldInstFrom, bool Complain,
8222 // Check the actual kind (type, non-type, template).
8223 if (Old->getKind() != New->getKind()) {
8224 if (Complain) {
8225 unsigned NextDiag = diag::err_template_param_different_kind;
8226 if (TemplateArgLoc.isValid()) {
8227 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8228 NextDiag = diag::note_template_param_different_kind;
8229 }
8230 S.Diag(New->getLocation(), NextDiag)
8231 << (Kind != Sema::TPL_TemplateMatch);
8232 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8233 << (Kind != Sema::TPL_TemplateMatch);
8234 }
8235
8236 return false;
8237 }
8238
8239 // Check that both are parameter packs or neither are parameter packs.
8240 // However, if we are matching a template template argument to a
8241 // template template parameter, the template template parameter can have
8242 // a parameter pack where the template template argument does not.
8243 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8244 if (Complain) {
8245 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8246 if (TemplateArgLoc.isValid()) {
8247 S.Diag(TemplateArgLoc,
8248 diag::err_template_arg_template_params_mismatch);
8249 NextDiag = diag::note_template_parameter_pack_non_pack;
8250 }
8251
8252 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8254 : 2;
8255 S.Diag(New->getLocation(), NextDiag)
8256 << ParamKind << New->isParameterPack();
8257 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8258 << ParamKind << Old->isParameterPack();
8259 }
8260
8261 return false;
8262 }
8263 // For non-type template parameters, check the type of the parameter.
8264 if (NonTypeTemplateParmDecl *OldNTTP =
8265 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8267
8268 // If we are matching a template template argument to a template
8269 // template parameter and one of the non-type template parameter types
8270 // is dependent, then we must wait until template instantiation time
8271 // to actually compare the arguments.
8273 (!OldNTTP->getType()->isDependentType() &&
8274 !NewNTTP->getType()->isDependentType())) {
8275 // C++20 [temp.over.link]p6:
8276 // Two [non-type] template-parameters are equivalent [if] they have
8277 // equivalent types ignoring the use of type-constraints for
8278 // placeholder types
8279 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8280 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8281 if (!S.Context.hasSameType(OldType, NewType)) {
8282 if (Complain) {
8283 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8284 if (TemplateArgLoc.isValid()) {
8285 S.Diag(TemplateArgLoc,
8286 diag::err_template_arg_template_params_mismatch);
8287 NextDiag = diag::note_template_nontype_parm_different_type;
8288 }
8289 S.Diag(NewNTTP->getLocation(), NextDiag)
8290 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8291 S.Diag(OldNTTP->getLocation(),
8292 diag::note_template_nontype_parm_prev_declaration)
8293 << OldNTTP->getType();
8294 }
8295 return false;
8296 }
8297 }
8298 }
8299 // For template template parameters, check the template parameter types.
8300 // The template parameter lists of template template
8301 // parameters must agree.
8302 else if (TemplateTemplateParmDecl *OldTTP =
8303 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8305 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8306 return false;
8308 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8309 OldTTP->getTemplateParameters(), Complain,
8312 : Kind),
8313 TemplateArgLoc))
8314 return false;
8315 }
8316
8320 const Expr *NewC = nullptr, *OldC = nullptr;
8321
8323 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8324 NewC = TC->getImmediatelyDeclaredConstraint();
8325 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8326 OldC = TC->getImmediatelyDeclaredConstraint();
8327 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8328 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8329 ->getPlaceholderTypeConstraint())
8330 NewC = E;
8331 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8332 ->getPlaceholderTypeConstraint())
8333 OldC = E;
8334 } else
8335 llvm_unreachable("unexpected template parameter type");
8336
8337 auto Diagnose = [&] {
8338 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8339 diag::err_template_different_type_constraint);
8340 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8341 diag::note_template_prev_declaration) << /*declaration*/0;
8342 };
8343
8344 if (!NewC != !OldC) {
8345 if (Complain)
8346 Diagnose();
8347 return false;
8348 }
8349
8350 if (NewC) {
8351 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8352 NewC)) {
8353 if (Complain)
8354 Diagnose();
8355 return false;
8356 }
8357 }
8358 }
8359
8360 return true;
8361}
8362
8363/// Diagnose a known arity mismatch when comparing template argument
8364/// lists.
8365static
8370 SourceLocation TemplateArgLoc) {
8371 unsigned NextDiag = diag::err_template_param_list_different_arity;
8372 if (TemplateArgLoc.isValid()) {
8373 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8374 NextDiag = diag::note_template_param_list_different_arity;
8375 }
8376 S.Diag(New->getTemplateLoc(), NextDiag)
8377 << (New->size() > Old->size())
8378 << (Kind != Sema::TPL_TemplateMatch)
8379 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8380 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8381 << (Kind != Sema::TPL_TemplateMatch)
8382 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8383}
8384
8387 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8388 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8389 if (Old->size() != New->size()) {
8390 if (Complain)
8392 TemplateArgLoc);
8393
8394 return false;
8395 }
8396
8397 // C++0x [temp.arg.template]p3:
8398 // A template-argument matches a template template-parameter (call it P)
8399 // when each of the template parameters in the template-parameter-list of
8400 // the template-argument's corresponding class template or alias template
8401 // (call it A) matches the corresponding template parameter in the
8402 // template-parameter-list of P. [...]
8403 TemplateParameterList::iterator NewParm = New->begin();
8404 TemplateParameterList::iterator NewParmEnd = New->end();
8405 for (TemplateParameterList::iterator OldParm = Old->begin(),
8406 OldParmEnd = Old->end();
8407 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8408 if (NewParm == NewParmEnd) {
8409 if (Complain)
8411 TemplateArgLoc);
8412 return false;
8413 }
8414 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8415 OldInstFrom, Complain, Kind,
8416 TemplateArgLoc))
8417 return false;
8418 }
8419
8420 // Make sure we exhausted all of the arguments.
8421 if (NewParm != NewParmEnd) {
8422 if (Complain)
8424 TemplateArgLoc);
8425
8426 return false;
8427 }
8428
8429 if (Kind != TPL_TemplateParamsEquivalent) {
8430 const Expr *NewRC = New->getRequiresClause();
8431 const Expr *OldRC = Old->getRequiresClause();
8432
8433 auto Diagnose = [&] {
8434 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8435 diag::err_template_different_requires_clause);
8436 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8437 diag::note_template_prev_declaration) << /*declaration*/0;
8438 };
8439
8440 if (!NewRC != !OldRC) {
8441 if (Complain)
8442 Diagnose();
8443 return false;
8444 }
8445
8446 if (NewRC) {
8447 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8448 NewRC)) {
8449 if (Complain)
8450 Diagnose();
8451 return false;
8452 }
8453 }
8454 }
8455
8456 return true;
8457}
8458
8459bool
8461 if (!S)
8462 return false;
8463
8464 // Find the nearest enclosing declaration scope.
8465 S = S->getDeclParent();
8466
8467 // C++ [temp.pre]p6: [P2096]
8468 // A template, explicit specialization, or partial specialization shall not
8469 // have C linkage.
8470 DeclContext *Ctx = S->getEntity();
8471 if (Ctx && Ctx->isExternCContext()) {
8472 SourceRange Range =
8473 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8474 ? TemplateParams->getParam(0)->getSourceRange()
8475 : TemplateParams->getSourceRange();
8476 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8477 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8478 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8479 return true;
8480 }
8481 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8482
8483 // C++ [temp]p2:
8484 // A template-declaration can appear only as a namespace scope or
8485 // class scope declaration.
8486 // C++ [temp.expl.spec]p3:
8487 // An explicit specialization may be declared in any scope in which the
8488 // corresponding primary template may be defined.
8489 // C++ [temp.class.spec]p6: [P2096]
8490 // A partial specialization may be declared in any scope in which the
8491 // corresponding primary template may be defined.
8492 if (Ctx) {
8493 if (Ctx->isFileContext())
8494 return false;
8495 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8496 // C++ [temp.mem]p2:
8497 // A local class shall not have member templates.
8498
8499 // Trace the outer context chain, bypassing nested records and OpenMP
8500 // captured regions, to determine if the class in defined inside a
8501 // function or method.
8502 const DeclContext *OutCtx = RD->getDeclContext();
8503 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8504 OutCtx = OutCtx->getParent();
8505
8506 if (OutCtx && OutCtx->isFunctionOrMethod())
8507 return Diag(TemplateParams->getTemplateLoc(),
8508 diag::err_template_inside_local_class)
8509 << TemplateParams->getSourceRange();
8510
8511 return false;
8512 }
8513 }
8514
8515 return Diag(TemplateParams->getTemplateLoc(),
8516 diag::err_template_outside_namespace_or_class_scope)
8517 << TemplateParams->getSourceRange();
8518}
8519
8520/// Determine what kind of template specialization the given declaration
8521/// is.
8523 if (!D)
8524 return TSK_Undeclared;
8525
8526 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8527 return Record->getTemplateSpecializationKind();
8528 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8529 return Function->getTemplateSpecializationKind();
8530 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8531 return Var->getTemplateSpecializationKind();
8532
8533 return TSK_Undeclared;
8534}
8535
8536/// Check whether a specialization is well-formed in the current
8537/// context.
8538///
8539/// This routine determines whether a template specialization can be declared
8540/// in the current context (C++ [temp.expl.spec]p2).
8541///
8542/// \param S the semantic analysis object for which this check is being
8543/// performed.
8544///
8545/// \param Specialized the entity being specialized or instantiated, which
8546/// may be a kind of template (class template, function template, etc.) or
8547/// a member of a class template (member function, static data member,
8548/// member class).
8549///
8550/// \param PrevDecl the previous declaration of this entity, if any.
8551///
8552/// \param Loc the location of the explicit specialization or instantiation of
8553/// this entity.
8554///
8555/// \param IsPartialSpecialization whether this is a partial specialization of
8556/// a class template.
8557///
8558/// \returns true if there was an error that we cannot recover from, false
8559/// otherwise.
8561 NamedDecl *Specialized,
8562 NamedDecl *PrevDecl,
8563 SourceLocation Loc,
8565 // Keep these "kind" numbers in sync with the %select statements in the
8566 // various diagnostics emitted by this routine.
8567 int EntityKind = 0;
8568 if (isa<ClassTemplateDecl>(Specialized))
8569 EntityKind = IsPartialSpecialization? 1 : 0;
8570 else if (isa<VarTemplateDecl>(Specialized))
8571 EntityKind = IsPartialSpecialization ? 3 : 2;
8572 else if (isa<FunctionTemplateDecl>(Specialized))
8573 EntityKind = 4;
8574 else if (isa<CXXMethodDecl>(Specialized))
8575 EntityKind = 5;
8576 else if (isa<VarDecl>(Specialized))
8577 EntityKind = 6;
8578 else if (isa<RecordDecl>(Specialized))
8579 EntityKind = 7;
8580 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8581 EntityKind = 8;
8582 else {
8583 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8584 << S.getLangOpts().CPlusPlus11;
8585 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8586 return true;
8587 }
8588
8589 // C++ [temp.expl.spec]p2:
8590 // An explicit specialization may be declared in any scope in which
8591 // the corresponding primary template may be defined.
8593 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8594 << Specialized;
8595 return true;
8596 }
8597
8598 // C++ [temp.class.spec]p6:
8599 // A class template partial specialization may be declared in any
8600 // scope in which the primary template may be defined.
8601 DeclContext *SpecializedContext =
8602 Specialized->getDeclContext()->getRedeclContext();
8604
8605 // Make sure that this redeclaration (or definition) occurs in the same
8606 // scope or an enclosing namespace.
8607 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8608 : DC->Equals(SpecializedContext))) {
8609 if (isa<TranslationUnitDecl>(SpecializedContext))
8610 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8611 << EntityKind << Specialized;
8612 else {
8613 auto *ND = cast<NamedDecl>(SpecializedContext);
8614 int Diag = diag::err_template_spec_redecl_out_of_scope;
8615 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8616 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8617 S.Diag(Loc, Diag) << EntityKind << Specialized
8618 << ND << isa<CXXRecordDecl>(ND);
8619 }
8620
8621 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8622
8623 // Don't allow specializing in the wrong class during error recovery.
8624 // Otherwise, things can go horribly wrong.
8625 if (DC->isRecord())
8626 return true;
8627 }
8628
8629 return false;
8630}
8631
8633 if (!E->isTypeDependent())
8634 return SourceLocation();
8635 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8636 Checker.TraverseStmt(E);
8637 if (Checker.MatchLoc.isInvalid())
8638 return E->getSourceRange();
8639 return Checker.MatchLoc;
8640}
8641
8642static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8643 if (!TL.getType()->isDependentType())
8644 return SourceLocation();
8645 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8646 Checker.TraverseTypeLoc(TL);
8647 if (Checker.MatchLoc.isInvalid())
8648 return TL.getSourceRange();
8649 return Checker.MatchLoc;
8650}
8651
8652/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8653/// that checks non-type template partial specialization arguments.
8655 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8656 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8657 bool HasError = false;
8658 for (unsigned I = 0; I != NumArgs; ++I) {
8659 if (Args[I].getKind() == TemplateArgument::Pack) {
8661 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8662 Args[I].pack_size(), IsDefaultArgument))
8663 return true;
8664
8665 continue;
8666 }
8667
8668 if (Args[I].getKind() != TemplateArgument::Expression)
8669 continue;
8670
8671 Expr *ArgExpr = Args[I].getAsExpr();
8672 if (ArgExpr->containsErrors()) {
8673 HasError = true;
8674 continue;
8675 }
8676
8677 // We can have a pack expansion of any of the bullets below.
8678 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8679 ArgExpr = Expansion->getPattern();
8680
8681 // Strip off any implicit casts we added as part of type checking.
8682 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8683 ArgExpr = ICE->getSubExpr();
8684
8685 // C++ [temp.class.spec]p8:
8686 // A non-type argument is non-specialized if it is the name of a
8687 // non-type parameter. All other non-type arguments are
8688 // specialized.
8689 //
8690 // Below, we check the two conditions that only apply to
8691 // specialized non-type arguments, so skip any non-specialized
8692 // arguments.
8693 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8694 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8695 continue;
8696
8697 if (isa<DependentTemplateIdExpr>(ArgExpr))
8698 continue;
8699
8700 // C++ [temp.class.spec]p9:
8701 // Within the argument list of a class template partial
8702 // specialization, the following restrictions apply:
8703 // -- A partially specialized non-type argument expression
8704 // shall not involve a template parameter of the partial
8705 // specialization except when the argument expression is a
8706 // simple identifier.
8707 // -- The type of a template parameter corresponding to a
8708 // specialized non-type argument shall not be dependent on a
8709 // parameter of the specialization.
8710 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8711 // We implement a compromise between the original rules and DR1315:
8712 // -- A specialized non-type template argument shall not be
8713 // type-dependent and the corresponding template parameter
8714 // shall have a non-dependent type.
8715 SourceRange ParamUseRange =
8716 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8717 if (ParamUseRange.isValid()) {
8718 if (IsDefaultArgument) {
8719 S.Diag(TemplateNameLoc,
8720 diag::err_dependent_non_type_arg_in_partial_spec);
8721 S.Diag(ParamUseRange.getBegin(),
8722 diag::note_dependent_non_type_default_arg_in_partial_spec)
8723 << ParamUseRange;
8724 } else {
8725 S.Diag(ParamUseRange.getBegin(),
8726 diag::err_dependent_non_type_arg_in_partial_spec)
8727 << ParamUseRange;
8728 }
8729 return true;
8730 }
8731
8732 ParamUseRange = findTemplateParameter(
8733 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8734 if (ParamUseRange.isValid()) {
8735 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8736 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8737 << Param->getType();
8739 return true;
8740 }
8741 }
8742
8743 return HasError;
8744}
8745
8747 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8748 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8749 // We have to be conservative when checking a template in a dependent
8750 // context.
8751 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8752 return false;
8753
8754 TemplateParameterList *TemplateParams =
8755 PrimaryTemplate->getTemplateParameters();
8756 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8758 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8759 if (!Param)
8760 continue;
8761
8762 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8763 Param, &TemplateArgs[I],
8764 1, I >= NumExplicit))
8765 return true;
8766 }
8767
8768 return false;
8769}
8770
8772 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8773 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8775 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8776 assert(TUK != TagUseKind::Reference && "References are not specializations");
8777
8778 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8779 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8780 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8781
8782 // Find the class template we're specializing
8783 TemplateName Name = TemplateId.Template.get();
8785 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8786
8787 if (!ClassTemplate) {
8788 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8789 << (Name.getAsTemplateDecl() &&
8791 return true;
8792 }
8793
8794 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8795 auto Message = DSA->getMessage();
8796 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8797 << ClassTemplate << !Message.empty() << Message;
8798 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8799 }
8800
8801 if (S->isTemplateParamScope())
8802 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8803
8804 DeclContext *DC = ClassTemplate->getDeclContext();
8805
8806 bool isMemberSpecialization = false;
8807 bool isPartialSpecialization = false;
8808
8809 if (SS.isSet()) {
8810 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8811 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8812 TemplateNameLoc, &TemplateId,
8813 /*IsMemberSpecialization=*/false))
8814 return true;
8815 }
8816
8817 // Check the validity of the template headers that introduce this
8818 // template.
8819 // FIXME: We probably shouldn't complain about these headers for
8820 // friend declarations.
8821 bool Invalid = false;
8822 TemplateParameterList *TemplateParams =
8824 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8825 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8826 if (Invalid)
8827 return true;
8828
8829 // Check that we can declare a template specialization here.
8830 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8831 return true;
8832
8833 if (TemplateParams && DC->isDependentContext()) {
8834 ContextRAII SavedContext(*this, DC);
8836 return true;
8837 }
8838
8839 if (TemplateParams && TemplateParams->size() > 0) {
8840 isPartialSpecialization = true;
8841
8842 if (TUK == TagUseKind::Friend) {
8843 Diag(KWLoc, diag::err_partial_specialization_friend)
8844 << SourceRange(LAngleLoc, RAngleLoc);
8845 return true;
8846 }
8847
8848 // C++ [temp.class.spec]p10:
8849 // The template parameter list of a specialization shall not
8850 // contain default template argument values.
8851 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8852 Decl *Param = TemplateParams->getParam(I);
8853 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8854 if (TTP->hasDefaultArgument()) {
8855 Diag(TTP->getDefaultArgumentLoc(),
8856 diag::err_default_arg_in_partial_spec);
8857 TTP->removeDefaultArgument();
8858 }
8859 } else if (NonTypeTemplateParmDecl *NTTP
8860 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8861 if (NTTP->hasDefaultArgument()) {
8862 Diag(NTTP->getDefaultArgumentLoc(),
8863 diag::err_default_arg_in_partial_spec)
8864 << NTTP->getDefaultArgument().getSourceRange();
8865 NTTP->removeDefaultArgument();
8866 }
8867 } else {
8869 if (TTP->hasDefaultArgument()) {
8871 diag::err_default_arg_in_partial_spec)
8873 TTP->removeDefaultArgument();
8874 }
8875 }
8876 }
8877 } else if (TemplateParams) {
8878 if (TUK == TagUseKind::Friend)
8879 Diag(KWLoc, diag::err_template_spec_friend)
8881 SourceRange(TemplateParams->getTemplateLoc(),
8882 TemplateParams->getRAngleLoc()))
8883 << SourceRange(LAngleLoc, RAngleLoc);
8884 } else {
8885 assert(TUK == TagUseKind::Friend &&
8886 "should have a 'template<>' for this decl");
8887 }
8888
8889 // Check that the specialization uses the same tag kind as the
8890 // original template.
8892 assert(Kind != TagTypeKind::Enum &&
8893 "Invalid enum tag in class template spec!");
8894 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8895 TUK == TagUseKind::Definition, KWLoc,
8896 ClassTemplate->getIdentifier())) {
8897 Diag(KWLoc, diag::err_use_with_wrong_tag)
8898 << ClassTemplate
8900 ClassTemplate->getTemplatedDecl()->getKindName());
8901 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8902 diag::note_previous_use);
8903 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8904 }
8905
8906 // Translate the parser's template argument list in our AST format.
8907 TemplateArgumentListInfo TemplateArgs =
8908 makeTemplateArgumentListInfo(*this, TemplateId);
8909
8910 // Check for unexpanded parameter packs in any of the template arguments.
8911 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8912 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8913 isPartialSpecialization
8916 return true;
8917
8918 // Check that the template argument list is well-formed for this
8919 // template.
8921 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8922 /*DefaultArgs=*/{},
8923 /*PartialTemplateArgs=*/false, CTAI,
8924 /*UpdateArgsWithConversions=*/true))
8925 return true;
8926
8927 // Find the class template (partial) specialization declaration that
8928 // corresponds to these arguments.
8929 if (isPartialSpecialization) {
8931 TemplateArgs.size(),
8932 CTAI.CanonicalConverted))
8933 return true;
8934
8935 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8936 // also do it during instantiation.
8937 if (!Name.isDependent() &&
8938 !TemplateSpecializationType::anyDependentTemplateArguments(
8939 TemplateArgs, CTAI.CanonicalConverted)) {
8940 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8941 << ClassTemplate->getDeclName();
8942 isPartialSpecialization = false;
8943 Invalid = true;
8944 }
8945 }
8946
8947 void *InsertPos = nullptr;
8948 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8949
8950 if (isPartialSpecialization)
8951 PrevDecl = ClassTemplate->findPartialSpecialization(
8952 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8953 else
8954 PrevDecl =
8955 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8956
8958
8959 // Check whether we can declare a class template specialization in
8960 // the current scope.
8961 if (TUK != TagUseKind::Friend &&
8963 TemplateNameLoc,
8964 isPartialSpecialization))
8965 return true;
8966
8967 if (!isPartialSpecialization) {
8968 // Create a new class template specialization declaration node for
8969 // this explicit specialization or friend declaration.
8971 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8972 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8973 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8975 if (TemplateParameterLists.size() > 0) {
8976 Specialization->setTemplateParameterListsInfo(Context,
8977 TemplateParameterLists);
8978 }
8979
8980 if (!PrevDecl)
8981 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8982 } else {
8984 Context.getCanonicalTemplateSpecializationType(
8986 TemplateName(ClassTemplate->getCanonicalDecl()),
8987 CTAI.CanonicalConverted));
8988 if (Context.hasSameType(
8989 CanonType,
8990 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8991 (!Context.getLangOpts().CPlusPlus20 ||
8992 !TemplateParams->hasAssociatedConstraints())) {
8993 // C++ [temp.class.spec]p9b3:
8994 //
8995 // -- The argument list of the specialization shall not be identical
8996 // to the implicit argument list of the primary template.
8997 //
8998 // This rule has since been removed, because it's redundant given DR1495,
8999 // but we keep it because it produces better diagnostics and recovery.
9000 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9001 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9002 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9003 return CheckClassTemplate(
9004 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9005 TemplateNameLoc, Attr, TemplateParams, AS_none,
9006 /*ModulePrivateLoc=*/SourceLocation(),
9007 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9008 TemplateParameterLists.data(), isMemberSpecialization);
9009 }
9010
9011 // Create a new class template partial specialization declaration node.
9013 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9016 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9017 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9018 Partial->setTemplateArgsAsWritten(TemplateArgs);
9019 SetNestedNameSpecifier(*this, Partial, SS);
9020 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9022 Context, TemplateParameterLists.drop_back(1));
9023 }
9024
9025 if (!PrevPartial)
9026 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9027 Specialization = Partial;
9028
9029 // If we are providing an explicit specialization of a member class
9030 // template specialization, make a note of that.
9031 if (isMemberSpecialization)
9032 Partial->setMemberSpecialization();
9033
9035 }
9036
9037 // C++ [temp.expl.spec]p6:
9038 // If a template, a member template or the member of a class template is
9039 // explicitly specialized then that specialization shall be declared
9040 // before the first use of that specialization that would cause an implicit
9041 // instantiation to take place, in every translation unit in which such a
9042 // use occurs; no diagnostic is required.
9043 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9044 bool Okay = false;
9045 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9046 // Is there any previous explicit specialization declaration?
9048 Okay = true;
9049 break;
9050 }
9051 }
9052
9053 if (!Okay) {
9054 SourceRange Range(TemplateNameLoc, RAngleLoc);
9055 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9056 << Context.getCanonicalTagType(Specialization) << Range;
9057
9058 Diag(PrevDecl->getPointOfInstantiation(),
9059 diag::note_instantiation_required_here)
9060 << (PrevDecl->getTemplateSpecializationKind()
9062 return true;
9063 }
9064 }
9065
9066 // If this is not a friend, note that this is an explicit specialization.
9067 if (TUK != TagUseKind::Friend)
9068 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9069
9070 // Check that this isn't a redefinition of this specialization.
9071 if (TUK == TagUseKind::Definition) {
9072 RecordDecl *Def = Specialization->getDefinition();
9073 NamedDecl *Hidden = nullptr;
9074 bool HiddenDefVisible = false;
9075 if (Def && SkipBody &&
9076 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9077 SkipBody->ShouldSkip = true;
9078 SkipBody->Previous = Def;
9079 if (!HiddenDefVisible && Hidden)
9081 } else if (Def) {
9082 SourceRange Range(TemplateNameLoc, RAngleLoc);
9083 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9084 Diag(Def->getLocation(), diag::note_previous_definition);
9085 Specialization->setInvalidDecl();
9086 return true;
9087 }
9088 }
9089
9092
9093 // Add alignment attributes if necessary; these attributes are checked when
9094 // the ASTContext lays out the structure.
9095 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9096 if (LangOpts.HLSL)
9097 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9100 }
9101
9102 if (ModulePrivateLoc.isValid())
9103 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9104 << (isPartialSpecialization? 1 : 0)
9105 << FixItHint::CreateRemoval(ModulePrivateLoc);
9106
9107 // C++ [temp.expl.spec]p9:
9108 // A template explicit specialization is in the scope of the
9109 // namespace in which the template was defined.
9110 //
9111 // We actually implement this paragraph where we set the semantic
9112 // context (in the creation of the ClassTemplateSpecializationDecl),
9113 // but we also maintain the lexical context where the actual
9114 // definition occurs.
9115 Specialization->setLexicalDeclContext(CurContext);
9116
9117 // We may be starting the definition of this specialization.
9118 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9119 Specialization->startDefinition();
9120
9121 if (TUK == TagUseKind::Friend) {
9122 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9123 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9124 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9126 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9127 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9128
9129 // Build the fully-sugared type for this class template
9130 // specialization as the user wrote in the specialization
9131 // itself. This means that we'll pretty-print the type retrieved
9132 // from the specialization's declaration the way that the user
9133 // actually wrote the specialization, rather than formatting the
9134 // name based on the "canonical" representation used to store the
9135 // template arguments in the specialization.
9137 TemplateNameLoc,
9138 WrittenTy,
9139 /*FIXME:*/KWLoc);
9140 Friend->setAccess(AS_public);
9141 CurContext->addDecl(Friend);
9142 } else {
9143 // Add the specialization into its lexical context, so that it can
9144 // be seen when iterating through the list of declarations in that
9145 // context. However, specializations are not found by name lookup.
9146 CurContext->addDecl(Specialization);
9147 }
9148
9149 if (SkipBody && SkipBody->ShouldSkip)
9150 return SkipBody->Previous;
9151
9152 Specialization->setInvalidDecl(Invalid);
9154 return Specialization;
9155}
9156
9158 MultiTemplateParamsArg TemplateParameterLists,
9159 Declarator &D) {
9160 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9161 ActOnDocumentableDecl(NewDecl);
9162 return NewDecl;
9163}
9164
9166 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9167 const IdentifierInfo *Name, SourceLocation NameLoc) {
9168 DeclContext *DC = CurContext;
9169
9170 if (!DC->getRedeclContext()->isFileContext()) {
9171 Diag(NameLoc,
9172 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9173 return nullptr;
9174 }
9175
9176 if (TemplateParameterLists.size() > 1) {
9177 Diag(NameLoc, diag::err_concept_extra_headers);
9178 return nullptr;
9179 }
9180
9181 TemplateParameterList *Params = TemplateParameterLists.front();
9182
9183 if (Params->size() == 0) {
9184 Diag(NameLoc, diag::err_concept_no_parameters);
9185 return nullptr;
9186 }
9187
9188 // Ensure that the parameter pack, if present, is the last parameter in the
9189 // template.
9190 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9191 ParamEnd = Params->end();
9192 ParamIt != ParamEnd; ++ParamIt) {
9193 Decl const *Param = *ParamIt;
9194 if (Param->isParameterPack()) {
9195 if (++ParamIt == ParamEnd)
9196 break;
9197 Diag(Param->getLocation(),
9198 diag::err_template_param_pack_must_be_last_template_parameter);
9199 return nullptr;
9200 }
9201 }
9202
9203 ConceptDecl *NewDecl =
9204 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9205
9206 if (NewDecl->hasAssociatedConstraints()) {
9207 // C++2a [temp.concept]p4:
9208 // A concept shall not have associated constraints.
9209 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9210 NewDecl->setInvalidDecl();
9211 }
9212
9213 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9214 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9216 LookupName(Previous, S);
9217 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9218 /*AllowInlineNamespace*/ false);
9219
9220 // We cannot properly handle redeclarations until we parse the constraint
9221 // expression, so only inject the name if we are sure we are not redeclaring a
9222 // symbol
9223 if (Previous.empty())
9224 PushOnScopeChains(NewDecl, S, true);
9225
9226 return NewDecl;
9227}
9228
9230 bool Found = false;
9231 LookupResult::Filter F = R.makeFilter();
9232 while (F.hasNext()) {
9233 NamedDecl *D = F.next();
9234 if (D == C) {
9235 F.erase();
9236 Found = true;
9237 break;
9238 }
9239 }
9240 F.done();
9241 return Found;
9242}
9243
9246 Expr *ConstraintExpr,
9247 const ParsedAttributesView &Attrs) {
9248 assert(!C->hasDefinition() && "Concept already defined");
9249 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9250 C->setInvalidDecl();
9251 return nullptr;
9252 }
9253 C->setDefinition(ConstraintExpr);
9254 ProcessDeclAttributeList(S, C, Attrs);
9255
9256 // Check for conflicting previous declaration.
9257 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9258 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9260 LookupName(Previous, S);
9261 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9262 /*AllowInlineNamespace*/ false);
9263 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9264 bool AddToScope = true;
9265 CheckConceptRedefinition(C, Previous, AddToScope);
9266
9268 if (!WasAlreadyAdded && AddToScope)
9269 PushOnScopeChains(C, S);
9270
9271 return C;
9272}
9273
9275 LookupResult &Previous, bool &AddToScope) {
9276 AddToScope = true;
9277
9278 if (Previous.empty())
9279 return;
9280
9281 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9282 if (!OldConcept) {
9283 auto *Old = Previous.getRepresentativeDecl();
9284 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9285 << NewDecl->getDeclName();
9286 notePreviousDefinition(Old, NewDecl->getLocation());
9287 AddToScope = false;
9288 return;
9289 }
9290 // Check if we can merge with a concept declaration.
9291 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9292 if (!IsSame) {
9293 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9294 << NewDecl->getDeclName();
9295 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9296 AddToScope = false;
9297 return;
9298 }
9299 if (hasReachableDefinition(OldConcept) &&
9300 IsRedefinitionInModule(NewDecl, OldConcept)) {
9301 Diag(NewDecl->getLocation(), diag::err_redefinition)
9302 << NewDecl->getDeclName();
9303 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9304 AddToScope = false;
9305 return;
9306 }
9307 if (!Previous.isSingleResult()) {
9308 // FIXME: we should produce an error in case of ambig and failed lookups.
9309 // Other decls (e.g. namespaces) also have this shortcoming.
9310 return;
9311 }
9312 // We unwrap canonical decl late to check for module visibility.
9313 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9314}
9315
9317 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9318 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9319 Diag(Loc, diag::err_recursive_concept) << CE;
9320 Diag(CE->getLocation(), diag::note_declared_at);
9321 CE->setInvalidDecl();
9322 return true;
9323 }
9324 // Concept template parameters don't have a definition and can't
9325 // be defined recursively.
9326 return false;
9327}
9328
9329/// \brief Strips various properties off an implicit instantiation
9330/// that has just been explicitly specialized.
9331static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9332 if (MinGW || (isa<FunctionDecl>(D) &&
9333 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9334 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9335
9336 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9337 FD->setInlineSpecified(false);
9338}
9339
9340/// Create an ExplicitInstantiationDecl to record source-location info for an
9341/// explicit template instantiation statement, and add it to \p CurContext.
9342///
9343/// For class templates / nested classes, the caller should build a
9344/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9345/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9346///
9347/// For function / variable templates, the caller should pass TypeAsWritten for
9348/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9350 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9351 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9352 NestedNameSpecifierLoc QualifierLoc,
9353 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9354 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9356 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9357 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9358 Context.addExplicitInstantiationDecl(Spec, EID);
9359 CurContext->addDecl(EID);
9360}
9361
9362/// Compute the diagnostic location for an explicit instantiation
9363// declaration or definition.
9364static SourceLocation
9366 SourceLocation PointOfInstantiation) {
9367 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9368 if (EID->getTemplateSpecializationKind() ==
9370 return EID->getTemplateLoc();
9371
9372 // Explicit instantiations following a specialization have no effect and
9373 // hence no PointOfInstantiation. In that case, walk decl backwards
9374 // until a valid name loc is found.
9375 SourceLocation PrevDiagLoc = PointOfInstantiation;
9376 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9377 Prev = Prev->getPreviousDecl()) {
9378 PrevDiagLoc = Prev->getLocation();
9379 }
9380 assert(PrevDiagLoc.isValid() &&
9381 "Explicit instantiation without point of instantiation?");
9382 return PrevDiagLoc;
9383}
9384
9385bool
9388 NamedDecl *PrevDecl,
9390 SourceLocation PrevPointOfInstantiation,
9391 bool &HasNoEffect) {
9392 HasNoEffect = false;
9393
9394 switch (NewTSK) {
9395 case TSK_Undeclared:
9397 assert(
9398 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9399 "previous declaration must be implicit!");
9400 return false;
9401
9403 switch (PrevTSK) {
9404 case TSK_Undeclared:
9406 // Okay, we're just specializing something that is either already
9407 // explicitly specialized or has merely been mentioned without any
9408 // instantiation.
9409 return false;
9410
9412 if (PrevPointOfInstantiation.isInvalid()) {
9413 // The declaration itself has not actually been instantiated, so it is
9414 // still okay to specialize it.
9416 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9417 return false;
9418 }
9419 // Fall through
9420 [[fallthrough]];
9421
9424 assert((PrevTSK == TSK_ImplicitInstantiation ||
9425 PrevPointOfInstantiation.isValid()) &&
9426 "Explicit instantiation without point of instantiation?");
9427
9428 // C++ [temp.expl.spec]p6:
9429 // If a template, a member template or the member of a class template
9430 // is explicitly specialized then that specialization shall be declared
9431 // before the first use of that specialization that would cause an
9432 // implicit instantiation to take place, in every translation unit in
9433 // which such a use occurs; no diagnostic is required.
9434 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9435 // Is there any previous explicit specialization declaration?
9437 return false;
9438 }
9439
9440 Diag(NewLoc, diag::err_specialization_after_instantiation)
9441 << PrevDecl;
9442 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9443 << (PrevTSK != TSK_ImplicitInstantiation);
9444
9445 return true;
9446 }
9447 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9448
9450 switch (PrevTSK) {
9452 // This explicit instantiation declaration is redundant (that's okay).
9453 HasNoEffect = true;
9454 return false;
9455
9456 case TSK_Undeclared:
9458 // We're explicitly instantiating something that may have already been
9459 // implicitly instantiated; that's fine.
9460 return false;
9461
9463 // C++0x [temp.explicit]p4:
9464 // For a given set of template parameters, if an explicit instantiation
9465 // of a template appears after a declaration of an explicit
9466 // specialization for that template, the explicit instantiation has no
9467 // effect.
9468 HasNoEffect = true;
9469 return false;
9470
9472 // C++0x [temp.explicit]p10:
9473 // If an entity is the subject of both an explicit instantiation
9474 // declaration and an explicit instantiation definition in the same
9475 // translation unit, the definition shall follow the declaration.
9476 Diag(NewLoc,
9477 diag::err_explicit_instantiation_declaration_after_definition);
9478
9479 // Explicit instantiations following a specialization have no effect and
9480 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9481 // until a valid name loc is found.
9482 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9483 diag::note_explicit_instantiation_definition_here);
9484 HasNoEffect = true;
9485 return false;
9486 }
9487 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9488
9490 switch (PrevTSK) {
9491 case TSK_Undeclared:
9493 // We're explicitly instantiating something that may have already been
9494 // implicitly instantiated; that's fine.
9495 return false;
9496
9498 // C++ DR 259, C++0x [temp.explicit]p4:
9499 // For a given set of template parameters, if an explicit
9500 // instantiation of a template appears after a declaration of
9501 // an explicit specialization for that template, the explicit
9502 // instantiation has no effect.
9503 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9504 << PrevDecl;
9505 Diag(PrevDecl->getLocation(),
9506 diag::note_previous_template_specialization);
9507 HasNoEffect = true;
9508 return false;
9509
9511 // We're explicitly instantiating a definition for something for which we
9512 // were previously asked to suppress instantiations. That's fine.
9513
9514 // C++0x [temp.explicit]p4:
9515 // For a given set of template parameters, if an explicit instantiation
9516 // of a template appears after a declaration of an explicit
9517 // specialization for that template, the explicit instantiation has no
9518 // effect.
9519 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9520 // Is there any previous explicit specialization declaration?
9522 HasNoEffect = true;
9523 break;
9524 }
9525 }
9526
9527 return false;
9528
9530 // C++0x [temp.spec]p5:
9531 // For a given template and a given set of template-arguments,
9532 // - an explicit instantiation definition shall appear at most once
9533 // in a program,
9534
9535 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9536 Diag(NewLoc, (getLangOpts().MSVCCompat)
9537 ? diag::ext_explicit_instantiation_duplicate
9538 : diag::err_explicit_instantiation_duplicate)
9539 << PrevDecl;
9540 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9541 diag::note_previous_explicit_instantiation);
9542 HasNoEffect = true;
9543 return false;
9544 }
9545 }
9546
9547 llvm_unreachable("Missing specialization/instantiation case?");
9548}
9549
9551 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9553 // Remove anything from Previous that isn't a function template in
9554 // the correct context.
9555 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9556 LookupResult::Filter F = Previous.makeFilter();
9557 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9558 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9559 while (F.hasNext()) {
9560 NamedDecl *D = F.next()->getUnderlyingDecl();
9561 if (!isa<FunctionTemplateDecl>(D)) {
9562 F.erase();
9563 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9564 continue;
9565 }
9566
9567 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9569 F.erase();
9570 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9571 continue;
9572 }
9573 }
9574 F.done();
9575
9576 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9577 if (Previous.empty()) {
9578 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9579 if (IsFriend && FriendQualifier.isDependent() &&
9580 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9581 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9583 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9584 return false;
9585 }
9586
9587 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9588 << IsFriend;
9589 for (auto &P : DiscardedCandidates)
9590 Diag(P.second->getLocation(),
9591 diag::note_dependent_function_template_spec_discard_reason)
9592 << P.first << IsFriend;
9593 return true;
9594 }
9595
9597 ExplicitTemplateArgs);
9598 return false;
9599}
9600
9602 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9603 LookupResult &Previous, bool QualifiedFriend) {
9604 // The set of function template specializations that could match this
9605 // explicit function template specialization.
9606 UnresolvedSet<8> Candidates;
9607 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9608 /*ForTakingAddress=*/false);
9609
9610 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9611 ConvertedTemplateArgs;
9612
9613 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9614 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9615 I != E; ++I) {
9616 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9617 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9618 // Only consider templates found within the same semantic lookup scope as
9619 // FD.
9620 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9622 continue;
9623
9624 QualType FT = FD->getType();
9625 // C++11 [dcl.constexpr]p8:
9626 // A constexpr specifier for a non-static member function that is not
9627 // a constructor declares that member function to be const.
9628 //
9629 // When matching a constexpr member function template specialization
9630 // against the primary template, we don't yet know whether the
9631 // specialization has an implicit 'const' (because we don't know whether
9632 // it will be a static member function until we know which template it
9633 // specializes). This rule was removed in C++14.
9634 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9635 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9637 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9638 if (OldMD && OldMD->isConst()) {
9639 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9641 EPI.TypeQuals.addConst();
9642 FT = Context.getFunctionType(FPT->getReturnType(),
9643 FPT->getParamTypes(), EPI);
9644 }
9645 }
9646
9648 if (ExplicitTemplateArgs)
9649 Args = *ExplicitTemplateArgs;
9650
9651 // C++ [temp.expl.spec]p11:
9652 // A trailing template-argument can be left unspecified in the
9653 // template-id naming an explicit function template specialization
9654 // provided it can be deduced from the function argument type.
9655 // Perform template argument deduction to determine whether we may be
9656 // specializing this template.
9657 // FIXME: It is somewhat wasteful to build
9658 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9659 FunctionDecl *Specialization = nullptr;
9661 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9662 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9664 // Template argument deduction failed; record why it failed, so
9665 // that we can provide nifty diagnostics.
9666 FailedCandidates.addCandidate().set(
9667 I.getPair(), FunTmpl->getTemplatedDecl(),
9668 MakeDeductionFailureInfo(Context, TDK, Info));
9669 (void)TDK;
9670 continue;
9671 }
9672
9673 // Target attributes are part of the cuda function signature, so
9674 // the deduced template's cuda target must match that of the
9675 // specialization. Given that C++ template deduction does not
9676 // take target attributes into account, we reject candidates
9677 // here that have a different target.
9678 if (LangOpts.CUDA &&
9679 CUDA().IdentifyTarget(Specialization,
9680 /* IgnoreImplicitHDAttr = */ true) !=
9681 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9682 FailedCandidates.addCandidate().set(
9683 I.getPair(), FunTmpl->getTemplatedDecl(),
9686 continue;
9687 }
9688
9689 // Record this candidate.
9690 if (ExplicitTemplateArgs)
9691 ConvertedTemplateArgs[Specialization] = std::move(Args);
9692 Candidates.addDecl(Specialization, I.getAccess());
9693 }
9694 }
9695
9696 // For a qualified friend declaration (with no explicit marker to indicate
9697 // that a template specialization was intended), note all (template and
9698 // non-template) candidates.
9699 if (QualifiedFriend && Candidates.empty()) {
9700 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9701 << FD->getDeclName() << FDLookupContext;
9702 // FIXME: We should form a single candidate list and diagnose all
9703 // candidates at once, to get proper sorting and limiting.
9704 for (auto *OldND : Previous) {
9705 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9706 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9707 }
9708 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9709 return true;
9710 }
9711
9712 // Find the most specialized function template.
9714 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9715 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9716 PDiag(diag::err_function_template_spec_ambiguous)
9717 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9718 PDiag(diag::note_function_template_spec_matched));
9719
9720 if (Result == Candidates.end())
9721 return true;
9722
9723 // Ignore access information; it doesn't figure into redeclaration checking.
9725
9726 if (const auto *PT = Specialization->getPrimaryTemplate();
9727 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9728 auto Message = DSA->getMessage();
9729 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9730 << PT << !Message.empty() << Message;
9731 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9732 }
9733
9734 // C++23 [except.spec]p13:
9735 // An exception specification is considered to be needed when:
9736 // - [...]
9737 // - the exception specification is compared to that of another declaration
9738 // (e.g., an explicit specialization or an overriding virtual function);
9739 // - [...]
9740 //
9741 // The exception specification of a defaulted function is evaluated as
9742 // described above only when needed; similarly, the noexcept-specifier of a
9743 // specialization of a function template or member function of a class
9744 // template is instantiated only when needed.
9745 //
9746 // The standard doesn't specify what the "comparison with another declaration"
9747 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9748 // not state which properties of an explicit specialization must match the
9749 // primary template.
9750 //
9751 // We assume that an explicit specialization must correspond with (per
9752 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9753 // the declaration produced by substitution into the function template.
9754 //
9755 // Since the determination whether two function declarations correspond does
9756 // not consider exception specification, we only need to instantiate it once
9757 // we determine the primary template when comparing types per
9758 // [basic.link]p11.1.
9759 auto *SpecializationFPT =
9760 Specialization->getType()->castAs<FunctionProtoType>();
9761 // If the function has a dependent exception specification, resolve it after
9762 // we have selected the primary template so we can check whether it matches.
9763 if (getLangOpts().CPlusPlus17 &&
9764 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9765 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9766 return true;
9767
9769 = Specialization->getTemplateSpecializationInfo();
9770 assert(SpecInfo && "Function template specialization info missing?");
9771
9772 // Note: do not overwrite location info if previous template
9773 // specialization kind was explicit.
9775 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9776 Specialization->setLocation(FD->getLocation());
9777 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9778 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9779 // function can differ from the template declaration with respect to
9780 // the constexpr specifier.
9781 // FIXME: We need an update record for this AST mutation.
9782 // FIXME: What if there are multiple such prior declarations (for instance,
9783 // from different modules)?
9784 Specialization->setConstexprKind(FD->getConstexprKind());
9785 }
9786
9787 // FIXME: Check if the prior specialization has a point of instantiation.
9788 // If so, we have run afoul of .
9789
9790 // If this is a friend declaration, then we're not really declaring
9791 // an explicit specialization.
9792 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9793
9794 // Check the scope of this explicit specialization.
9795 if (!isFriend &&
9797 Specialization->getPrimaryTemplate(),
9799 false))
9800 return true;
9801
9802 // C++ [temp.expl.spec]p6:
9803 // If a template, a member template or the member of a class template is
9804 // explicitly specialized then that specialization shall be declared
9805 // before the first use of that specialization that would cause an implicit
9806 // instantiation to take place, in every translation unit in which such a
9807 // use occurs; no diagnostic is required.
9808 bool HasNoEffect = false;
9809 if (!isFriend &&
9814 SpecInfo->getPointOfInstantiation(),
9815 HasNoEffect))
9816 return true;
9817
9818 // Mark the prior declaration as an explicit specialization, so that later
9819 // clients know that this is an explicit specialization.
9820 // A dependent friend specialization which has a definition should be treated
9821 // as explicit specialization, despite being invalid.
9822 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9823 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9824 // Since explicit specializations do not inherit '=delete' from their
9825 // primary function template - check if the 'specialization' that was
9826 // implicitly generated (during template argument deduction for partial
9827 // ordering) from the most specialized of all the function templates that
9828 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9829 // first check that it was implicitly generated during template argument
9830 // deduction by making sure it wasn't referenced, and then reset the deleted
9831 // flag to not-deleted, so that we can inherit that information from 'FD'.
9832 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9833 !Specialization->getCanonicalDecl()->isReferenced()) {
9834 // FIXME: This assert will not hold in the presence of modules.
9835 assert(
9836 Specialization->getCanonicalDecl() == Specialization &&
9837 "This must be the only existing declaration of this specialization");
9838 // FIXME: We need an update record for this AST mutation.
9839 Specialization->setDeletedAsWritten(false);
9840 }
9841 // FIXME: We need an update record for this AST mutation.
9844 }
9845
9846 // Turn the given function declaration into a function template
9847 // specialization, with the template arguments from the previous
9848 // specialization.
9849 // Take copies of (semantic and syntactic) template argument lists.
9851 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9852 FD->setFunctionTemplateSpecialization(
9853 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9855 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9856
9857 // A function template specialization inherits the target attributes
9858 // of its template. (We require the attributes explicitly in the
9859 // code to match, but a template may have implicit attributes by
9860 // virtue e.g. of being constexpr, and it passes these implicit
9861 // attributes on to its specializations.)
9862 if (LangOpts.CUDA)
9863 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9864
9865 // The "previous declaration" for this function template specialization is
9866 // the prior function template specialization.
9867 Previous.clear();
9868 Previous.addDecl(Specialization);
9869 return false;
9870}
9871
9872bool
9874 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9875 "Only for non-template members");
9876
9877 // Try to find the member we are instantiating.
9878 NamedDecl *FoundInstantiation = nullptr;
9879 NamedDecl *Instantiation = nullptr;
9880 NamedDecl *InstantiatedFrom = nullptr;
9881 MemberSpecializationInfo *MSInfo = nullptr;
9882
9883 if (Previous.empty()) {
9884 // Nowhere to look anyway.
9885 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9886 UnresolvedSet<8> Candidates;
9887 for (NamedDecl *Candidate : Previous) {
9888 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9889 // Ignore any candidates that aren't member functions.
9890 if (!Method)
9891 continue;
9892
9893 QualType Adjusted = Function->getType();
9894 if (!hasExplicitCallingConv(Adjusted))
9895 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9896 // Ignore any candidates with the wrong type.
9897 // This doesn't handle deduced return types, but both function
9898 // declarations should be undeduced at this point.
9899 // FIXME: The exception specification should probably be ignored when
9900 // comparing the types.
9901 if (!Context.hasSameType(Adjusted, Method->getType()))
9902 continue;
9903
9904 // Ignore any candidates with unsatisfied constraints.
9905 if (ConstraintSatisfaction Satisfaction;
9906 Method->getTrailingRequiresClause() &&
9907 (CheckFunctionConstraints(Method, Satisfaction,
9908 /*UsageLoc=*/Member->getLocation(),
9909 /*ForOverloadResolution=*/true) ||
9910 !Satisfaction.IsSatisfied))
9911 continue;
9912
9913 Candidates.addDecl(Candidate);
9914 }
9915
9916 // If we have no viable candidates left after filtering, we are done.
9917 if (Candidates.empty())
9918 return false;
9919
9920 // Find the function that is more constrained than every other function it
9921 // has been compared to.
9922 UnresolvedSetIterator Best = Candidates.begin();
9923 CXXMethodDecl *BestMethod = nullptr;
9924 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9925 I != E; ++I) {
9926 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9927 if (I == Best ||
9928 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9929 Best = I;
9930 BestMethod = Method;
9931 }
9932 }
9933
9934 FoundInstantiation = *Best;
9935 Instantiation = BestMethod;
9936 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9937 MSInfo = BestMethod->getMemberSpecializationInfo();
9938
9939 // Make sure the best candidate is more constrained than all of the others.
9940 bool Ambiguous = false;
9941 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9942 I != E; ++I) {
9943 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9944 if (I != Best &&
9945 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9946 Ambiguous = true;
9947 break;
9948 }
9949 }
9950
9951 if (Ambiguous) {
9952 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9953 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9954 for (NamedDecl *Candidate : Candidates) {
9955 Candidate = Candidate->getUnderlyingDecl();
9956 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9957 << Candidate;
9958 }
9959 return true;
9960 }
9961 } else if (isa<VarDecl>(Member)) {
9962 VarDecl *PrevVar;
9963 if (Previous.isSingleResult() &&
9964 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9965 if (PrevVar->isStaticDataMember()) {
9966 FoundInstantiation = Previous.getRepresentativeDecl();
9967 Instantiation = PrevVar;
9968 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9969 MSInfo = PrevVar->getMemberSpecializationInfo();
9970 }
9971 } else if (isa<RecordDecl>(Member)) {
9972 CXXRecordDecl *PrevRecord;
9973 if (Previous.isSingleResult() &&
9974 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9975 FoundInstantiation = Previous.getRepresentativeDecl();
9976 Instantiation = PrevRecord;
9977 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9978 MSInfo = PrevRecord->getMemberSpecializationInfo();
9979 }
9980 } else if (isa<EnumDecl>(Member)) {
9981 EnumDecl *PrevEnum;
9982 if (Previous.isSingleResult() &&
9983 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9984 FoundInstantiation = Previous.getRepresentativeDecl();
9985 Instantiation = PrevEnum;
9986 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9987 MSInfo = PrevEnum->getMemberSpecializationInfo();
9988 }
9989 }
9990
9991 if (!Instantiation) {
9992 // There is no previous declaration that matches. Since member
9993 // specializations are always out-of-line, the caller will complain about
9994 // this mismatch later.
9995 return false;
9996 }
9997
9998 // A member specialization in a friend declaration isn't really declaring
9999 // an explicit specialization, just identifying a specific (possibly implicit)
10000 // specialization. Don't change the template specialization kind.
10001 //
10002 // FIXME: Is this really valid? Other compilers reject.
10003 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10004 // Preserve instantiation information.
10005 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10006 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10007 cast<CXXMethodDecl>(InstantiatedFrom),
10009 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10010 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10011 cast<CXXRecordDecl>(InstantiatedFrom),
10013 }
10014
10015 Previous.clear();
10016 Previous.addDecl(FoundInstantiation);
10017 return false;
10018 }
10019
10020 // Make sure that this is a specialization of a member.
10021 if (!InstantiatedFrom) {
10022 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10023 << Member;
10024 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10025 return true;
10026 }
10027
10028 // C++ [temp.expl.spec]p6:
10029 // If a template, a member template or the member of a class template is
10030 // explicitly specialized then that specialization shall be declared
10031 // before the first use of that specialization that would cause an implicit
10032 // instantiation to take place, in every translation unit in which such a
10033 // use occurs; no diagnostic is required.
10034 assert(MSInfo && "Member specialization info missing?");
10035
10036 bool HasNoEffect = false;
10039 Instantiation,
10041 MSInfo->getPointOfInstantiation(),
10042 HasNoEffect))
10043 return true;
10044
10045 // Check the scope of this explicit specialization.
10047 InstantiatedFrom,
10048 Instantiation, Member->getLocation(),
10049 false))
10050 return true;
10051
10052 // Note that this member specialization is an "instantiation of" the
10053 // corresponding member of the original template.
10054 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10055 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10056 if (InstantiationFunction->getTemplateSpecializationKind() ==
10058 // Explicit specializations of member functions of class templates do not
10059 // inherit '=delete' from the member function they are specializing.
10060 if (InstantiationFunction->isDeleted()) {
10061 // FIXME: This assert will not hold in the presence of modules.
10062 assert(InstantiationFunction->getCanonicalDecl() ==
10063 InstantiationFunction);
10064 // FIXME: We need an update record for this AST mutation.
10065 InstantiationFunction->setDeletedAsWritten(false);
10066 }
10067 }
10068
10069 MemberFunction->setInstantiationOfMemberFunction(
10071 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10072 MemberVar->setInstantiationOfStaticDataMember(
10073 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10074 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10075 MemberClass->setInstantiationOfMemberClass(
10077 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10078 MemberEnum->setInstantiationOfMemberEnum(
10079 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10080 } else {
10081 llvm_unreachable("unknown member specialization kind");
10082 }
10083
10084 // Save the caller the trouble of having to figure out which declaration
10085 // this specialization matches.
10086 Previous.clear();
10087 Previous.addDecl(FoundInstantiation);
10088 return false;
10089}
10090
10091/// Complete the explicit specialization of a member of a class template by
10092/// updating the instantiated member to be marked as an explicit specialization.
10093///
10094/// \param OrigD The member declaration instantiated from the template.
10095/// \param Loc The location of the explicit specialization of the member.
10096template<typename DeclT>
10097static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10098 SourceLocation Loc) {
10099 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10100 return;
10101
10102 // FIXME: Inform AST mutation listeners of this AST mutation.
10103 // FIXME: If there are multiple in-class declarations of the member (from
10104 // multiple modules, or a declaration and later definition of a member type),
10105 // should we update all of them?
10106 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10107 OrigD->setLocation(Loc);
10108}
10109
10112 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10113 if (Instantiation == Member)
10114 return;
10115
10116 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10117 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10118 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10119 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10120 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10121 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10122 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10123 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10124 else
10125 llvm_unreachable("unknown member specialization kind");
10126}
10127
10128/// Check the scope of an explicit instantiation.
10129///
10130/// \returns true if a serious error occurs, false otherwise.
10132 SourceLocation InstLoc,
10133 bool WasQualifiedName) {
10135 DeclContext *CurContext = S.CurContext->getRedeclContext();
10136
10137 if (CurContext->isRecord()) {
10138 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10139 << D;
10140 return true;
10141 }
10142
10143 // C++11 [temp.explicit]p3:
10144 // An explicit instantiation shall appear in an enclosing namespace of its
10145 // template. If the name declared in the explicit instantiation is an
10146 // unqualified name, the explicit instantiation shall appear in the
10147 // namespace where its template is declared or, if that namespace is inline
10148 // (7.3.1), any namespace from its enclosing namespace set.
10149 //
10150 // This is DR275, which we do not retroactively apply to C++98/03.
10151 if (WasQualifiedName) {
10152 if (CurContext->Encloses(OrigContext))
10153 return false;
10154 } else {
10155 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10156 return false;
10157 }
10158
10159 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10160 if (WasQualifiedName)
10161 S.Diag(InstLoc,
10162 S.getLangOpts().CPlusPlus11?
10163 diag::err_explicit_instantiation_out_of_scope :
10164 diag::warn_explicit_instantiation_out_of_scope_0x)
10165 << D << NS;
10166 else
10167 S.Diag(InstLoc,
10168 S.getLangOpts().CPlusPlus11?
10169 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10170 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10171 << D << NS;
10172 } else
10173 S.Diag(InstLoc,
10174 S.getLangOpts().CPlusPlus11?
10175 diag::err_explicit_instantiation_must_be_global :
10176 diag::warn_explicit_instantiation_must_be_global_0x)
10177 << D;
10178 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10179 return false;
10180}
10181
10182/// Common checks for whether an explicit instantiation of \p D is valid.
10184 SourceLocation InstLoc,
10185 bool WasQualifiedName,
10187 // C++ [temp.explicit]p13:
10188 // An explicit instantiation declaration shall not name a specialization of
10189 // a template with internal linkage.
10192 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10193 return true;
10194 }
10195
10196 // C++11 [temp.explicit]p3: [DR 275]
10197 // An explicit instantiation shall appear in an enclosing namespace of its
10198 // template.
10199 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10200 return true;
10201
10202 return false;
10203}
10204
10205/// Determine whether the given scope specifier has a template-id in it.
10207 // C++11 [temp.explicit]p3:
10208 // If the explicit instantiation is for a member function, a member class
10209 // or a static data member of a class template specialization, the name of
10210 // the class template specialization in the qualified-id for the member
10211 // name shall be a simple-template-id.
10212 //
10213 // C++98 has the same restriction, just worded differently.
10214 for (NestedNameSpecifier NNS = SS.getScopeRep();
10216 /**/) {
10217 const Type *T = NNS.getAsType();
10219 return true;
10220 NNS = T->getPrefix();
10221 }
10222 return false;
10223}
10224
10225/// Make a dllexport or dllimport attr on a class template specialization take
10226/// effect.
10229 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10230 assert(A && "dllExportImportClassTemplateSpecialization called "
10231 "on Def without dllexport or dllimport");
10232
10233 // We reject explicit instantiations in class scope, so there should
10234 // never be any delayed exported classes to worry about.
10235 assert(S.DelayedDllExportClasses.empty() &&
10236 "delayed exports present at explicit instantiation");
10238
10239 // Propagate attribute to base class templates.
10240 for (auto &B : Def->bases()) {
10241 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10242 B.getType()->getAsCXXRecordDecl()))
10244 }
10245
10247}
10248
10250 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10251 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10252 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10253 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10254 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10255 // Find the class template we're specializing
10256 TemplateName Name = TemplateD.get();
10257 TemplateDecl *TD = Name.getAsTemplateDecl();
10258 // Check that the specialization uses the same tag kind as the
10259 // original template.
10261 assert(Kind != TagTypeKind::Enum &&
10262 "Invalid enum tag in class template explicit instantiation!");
10263
10264 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10265
10266 if (!ClassTemplate) {
10267 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10268 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10269 Diag(TD->getLocation(), diag::note_previous_use);
10270 return true;
10271 }
10272
10273 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10274 Kind, /*isDefinition*/false, KWLoc,
10275 ClassTemplate->getIdentifier())) {
10276 Diag(KWLoc, diag::err_use_with_wrong_tag)
10277 << ClassTemplate
10279 ClassTemplate->getTemplatedDecl()->getKindName());
10280 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10281 diag::note_previous_use);
10282 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10283 }
10284
10285 // C++0x [temp.explicit]p2:
10286 // There are two forms of explicit instantiation: an explicit instantiation
10287 // definition and an explicit instantiation declaration. An explicit
10288 // instantiation declaration begins with the extern keyword. [...]
10289 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10292
10294 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10295 // Check for dllexport class template instantiation declarations,
10296 // except for MinGW mode.
10297 for (const ParsedAttr &AL : Attr) {
10298 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10299 Diag(ExternLoc,
10300 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10301 Diag(AL.getLoc(), diag::note_attribute);
10302 break;
10303 }
10304 }
10305
10306 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10307 Diag(ExternLoc,
10308 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10309 Diag(A->getLocation(), diag::note_attribute);
10310 }
10311 }
10312
10313 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10314 // instantiation declarations for most purposes.
10315 bool DLLImportExplicitInstantiationDef = false;
10317 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10318 // Check for dllimport class template instantiation definitions.
10319 bool DLLImport =
10320 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10321 for (const ParsedAttr &AL : Attr) {
10322 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10323 DLLImport = true;
10324 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10325 // dllexport trumps dllimport here.
10326 DLLImport = false;
10327 break;
10328 }
10329 }
10330 if (DLLImport) {
10332 DLLImportExplicitInstantiationDef = true;
10333 }
10334 }
10335
10336 // Translate the parser's template argument list in our AST format.
10337 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10338 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10339
10340 // Check that the template argument list is well-formed for this
10341 // template.
10343 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10344 /*DefaultArgs=*/{}, false, CTAI,
10345 /*UpdateArgsWithConversions=*/true,
10346 /*ConstraintsNotSatisfied=*/nullptr))
10347 return true;
10348
10349 // Find the class template specialization declaration that
10350 // corresponds to these arguments.
10351 void *InsertPos = nullptr;
10353 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10354
10355 TemplateSpecializationKind PrevDecl_TSK
10356 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10357
10358 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10359 Context.getTargetInfo().getTriple().isOSCygMing()) {
10360 // Check for dllexport class template instantiation definitions in MinGW
10361 // mode, if a previous declaration of the instantiation was seen.
10362 for (const ParsedAttr &AL : Attr) {
10363 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10364 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10365 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10366 } else {
10367 Diag(AL.getLoc(),
10368 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10369 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10370 }
10371 break;
10372 }
10373 }
10374 }
10375
10376 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10377 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10378 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10379 return AL.getKind() == ParsedAttr::AT_DLLExport;
10380 })) {
10381 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10382 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10383 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10384 }
10385 }
10386
10387 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10388 SS.isSet(), TSK))
10389 return true;
10390
10392
10393 bool HasNoEffect = false;
10394 if (PrevDecl) {
10395 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10396 PrevDecl, PrevDecl_TSK,
10397 PrevDecl->getPointOfInstantiation(),
10398 HasNoEffect))
10399 return PrevDecl;
10400
10401 // Even though HasNoEffect == true means that this explicit instantiation
10402 // has no effect on semantics, we go on to put its syntax in the AST.
10403
10404 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10405 PrevDecl_TSK == TSK_Undeclared) {
10406 // Since the only prior class template specialization with these
10407 // arguments was referenced but not declared, reuse that
10408 // declaration node as our own, updating the source location
10409 // for the template name to reflect our new declaration.
10410 // (Other source locations will be updated later.)
10411 Specialization = PrevDecl;
10412 Specialization->setLocation(TemplateNameLoc);
10413 PrevDecl = nullptr;
10414 }
10415
10416 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10417 DLLImportExplicitInstantiationDef) {
10418 // The new specialization might add a dllimport attribute.
10419 HasNoEffect = false;
10420 }
10421 }
10422
10423 if (!Specialization) {
10424 // Create a new class template specialization declaration node for
10425 // this explicit specialization.
10427 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10428 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10430
10431 // A MSInheritanceAttr attached to the previous declaration must be
10432 // propagated to the new node prior to instantiation.
10433 if (PrevDecl) {
10434 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10435 auto *Clone = A->clone(getASTContext());
10436 Clone->setInherited(true);
10437 Specialization->addAttr(Clone);
10438 Consumer.AssignInheritanceModel(Specialization);
10439 }
10440 }
10441
10442 if (!HasNoEffect && !PrevDecl) {
10443 // Insert the new specialization.
10444 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10445 }
10446 }
10447
10448 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10449
10450 // Set source locations for keywords.
10451 Specialization->setExternKeywordLoc(ExternLoc);
10452 Specialization->setTemplateKeywordLoc(TemplateLoc);
10453 Specialization->setBraceRange(SourceRange());
10454
10455 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10458
10459 // Add the explicit instantiation into its lexical context. However,
10460 // since explicit instantiations are never found by name lookup, we
10461 // just put it into the declaration context directly.
10462 Specialization->setLexicalDeclContext(CurContext);
10463 CurContext->addDecl(Specialization);
10464
10465 // Syntax is now OK, so return if it has no other effect on semantics.
10466 if (HasNoEffect) {
10467 // Set the template specialization kind.
10468 Specialization->setTemplateSpecializationKind(TSK);
10469
10471 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10472 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10473 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10474 Context.getCanonicalTagType(Specialization));
10476 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10477 TemplateNameLoc, TSI, TSK);
10478 return Specialization;
10479 }
10480
10481 // C++ [temp.explicit]p3:
10482 // A definition of a class template or class member template
10483 // shall be in scope at the point of the explicit instantiation of
10484 // the class template or class member template.
10485 //
10486 // This check comes when we actually try to perform the
10487 // instantiation.
10489 = cast_or_null<ClassTemplateSpecializationDecl>(
10490 Specialization->getDefinition());
10491 if (!Def)
10493 /*Complain=*/true,
10494 CTAI.StrictPackMatch);
10495 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10496 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10497 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10498 }
10499
10500 // Instantiate the members of this class template specialization.
10501 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10502 Specialization->getDefinition());
10503 if (Def) {
10505 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10506 // TSK_ExplicitInstantiationDefinition
10507 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10509 DLLImportExplicitInstantiationDef)) {
10510 // FIXME: Need to notify the ASTMutationListener that we did this.
10512
10513 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10514 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10515 // An explicit instantiation definition can add a dll attribute to a
10516 // template with a previous instantiation declaration. MinGW doesn't
10517 // allow this.
10518 auto *A = cast<InheritableAttr>(
10520 A->setInherited(true);
10521 Def->addAttr(A);
10523 }
10524 }
10525
10526 // Fix a TSK_ImplicitInstantiation followed by a
10527 // TSK_ExplicitInstantiationDefinition
10528 bool NewlyDLLExported =
10529 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10530 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10531 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10532 // An explicit instantiation definition can add a dll attribute to a
10533 // template with a previous implicit instantiation. MinGW doesn't allow
10534 // this. We limit clang to only adding dllexport, to avoid potentially
10535 // strange codegen behavior. For example, if we extend this conditional
10536 // to dllimport, and we have a source file calling a method on an
10537 // implicitly instantiated template class instance and then declaring a
10538 // dllimport explicit instantiation definition for the same template
10539 // class, the codegen for the method call will not respect the dllimport,
10540 // while it will with cl. The Def will already have the DLL attribute,
10541 // since the Def and Specialization will be the same in the case of
10542 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10543 // attribute to the Specialization; we just need to make it take effect.
10544 assert(Def == Specialization &&
10545 "Def and Specialization should match for implicit instantiation");
10547 }
10548
10549 // In MinGW mode, export the template instantiation if the declaration
10550 // was marked dllexport.
10551 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10552 Context.getTargetInfo().getTriple().isOSCygMing() &&
10553 PrevDecl->hasAttr<DLLExportAttr>()) {
10555 }
10556
10557 // Set the template specialization kind. Make sure it is set before
10558 // instantiating the members which will trigger ASTConsumer callbacks.
10559 Specialization->setTemplateSpecializationKind(TSK);
10560 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10561 } else {
10562
10563 // Set the template specialization kind.
10564 Specialization->setTemplateSpecializationKind(TSK);
10565 }
10566
10568 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10569 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10570 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10571 Context.getCanonicalTagType(Specialization));
10573 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10574 TemplateNameLoc, TSI, TSK);
10575 return Specialization;
10576}
10577
10580 SourceLocation TemplateLoc, unsigned TagSpec,
10581 SourceLocation KWLoc, CXXScopeSpec &SS,
10582 IdentifierInfo *Name, SourceLocation NameLoc,
10583 const ParsedAttributesView &Attr) {
10584
10585 bool Owned = false;
10586 bool IsDependent = false;
10587 Decl *TagD =
10588 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10589 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10590 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10591 false, TypeResult(), /*IsTypeSpecifier*/ false,
10592 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10593 .get();
10594 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10595
10596 if (!TagD)
10597 return true;
10598
10599 TagDecl *Tag = cast<TagDecl>(TagD);
10600 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10601
10602 if (Tag->isInvalidDecl())
10603 return true;
10604
10606 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10607 if (!Pattern) {
10608 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10609 << Context.getCanonicalTagType(Record);
10610 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10611 return true;
10612 }
10613
10614 // C++0x [temp.explicit]p2:
10615 // If the explicit instantiation is for a class or member class, the
10616 // elaborated-type-specifier in the declaration shall include a
10617 // simple-template-id.
10618 //
10619 // C++98 has the same restriction, just worded differently.
10621 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10622 << Record << SS.getRange();
10623
10624 // C++0x [temp.explicit]p2:
10625 // There are two forms of explicit instantiation: an explicit instantiation
10626 // definition and an explicit instantiation declaration. An explicit
10627 // instantiation declaration begins with the extern keyword. [...]
10631
10632 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10633
10634 // Verify that it is okay to explicitly instantiate here.
10635 CXXRecordDecl *PrevDecl
10636 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10637 if (!PrevDecl && Record->getDefinition())
10638 PrevDecl = Record;
10639 if (PrevDecl) {
10641 bool HasNoEffect = false;
10642 assert(MSInfo && "No member specialization information?");
10643 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10644 PrevDecl,
10646 MSInfo->getPointOfInstantiation(),
10647 HasNoEffect))
10648 return true;
10649 if (HasNoEffect) {
10653 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10654 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10655 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10656 TL.setElaboratedKeywordLoc(KWLoc);
10657 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10658 TL.setNameLoc(NameLoc);
10660 TemplateLoc, NestedNameSpecifierLoc(),
10661 nullptr, NameLoc, TSI, TSK);
10662 return TagD;
10663 }
10664 }
10665
10666 CXXRecordDecl *RecordDef
10667 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10668 if (!RecordDef) {
10669 // C++ [temp.explicit]p3:
10670 // A definition of a member class of a class template shall be in scope
10671 // at the point of an explicit instantiation of the member class.
10672 CXXRecordDecl *Def
10673 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10674 if (!Def) {
10675 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10676 << 0 << Record->getDeclName() << Record->getDeclContext();
10677 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10678 << Pattern;
10679 return true;
10680 } else {
10681 if (InstantiateClass(NameLoc, Record, Def,
10683 TSK))
10684 return true;
10685
10686 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10687 if (!RecordDef)
10688 return true;
10689 }
10690 }
10691
10692 // Instantiate all of the members of the class.
10693 InstantiateClassMembers(NameLoc, RecordDef,
10695
10697 MarkVTableUsed(NameLoc, RecordDef, true);
10698
10701 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10702 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10703 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10704 TL.setElaboratedKeywordLoc(KWLoc);
10705 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10706 TL.setNameLoc(NameLoc);
10708 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10709 NameLoc, TSI, TSK);
10710 return TagD;
10711}
10712
10714 SourceLocation ExternLoc,
10715 SourceLocation TemplateLoc,
10716 Declarator &D) {
10717 // Explicit instantiations always require a name.
10718 // TODO: check if/when DNInfo should replace Name.
10720 DeclarationName Name = NameInfo.getName();
10721 if (!Name) {
10722 if (!D.isInvalidType())
10724 diag::err_explicit_instantiation_requires_name)
10726
10727 return true;
10728 }
10729
10730 // Get the innermost enclosing declaration scope.
10731 S = S->getDeclParent();
10732
10733 // Determine the type of the declaration.
10735 QualType R = T->getType();
10736 if (R.isNull())
10737 return true;
10738
10739 // C++ [dcl.stc]p1:
10740 // A storage-class-specifier shall not be specified in [...] an explicit
10741 // instantiation (14.7.2) directive.
10743 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10744 << Name;
10745 return true;
10746 } else if (D.getDeclSpec().getStorageClassSpec()
10748 // Complain about then remove the storage class specifier.
10749 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10751
10753 }
10754
10755 // C++0x [temp.explicit]p1:
10756 // [...] An explicit instantiation of a function template shall not use the
10757 // inline or constexpr specifiers.
10758 // Presumably, this also applies to member functions of class templates as
10759 // well.
10763 diag::err_explicit_instantiation_inline :
10764 diag::warn_explicit_instantiation_inline_0x)
10766 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10767 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10768 // not already specified.
10770 diag::err_explicit_instantiation_constexpr);
10771
10772 // A deduction guide is not on the list of entities that can be explicitly
10773 // instantiated.
10775 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10776 << /*explicit instantiation*/ 0;
10777 return true;
10778 }
10779
10780 // C++0x [temp.explicit]p2:
10781 // There are two forms of explicit instantiation: an explicit instantiation
10782 // definition and an explicit instantiation declaration. An explicit
10783 // instantiation declaration begins with the extern keyword. [...]
10787
10788 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10790 /*ObjectType=*/QualType());
10791
10792 if (!R->isFunctionType()) {
10793 // C++ [temp.explicit]p1:
10794 // A [...] static data member of a class template can be explicitly
10795 // instantiated from the member definition associated with its class
10796 // template.
10797 // C++1y [temp.explicit]p1:
10798 // A [...] variable [...] template specialization can be explicitly
10799 // instantiated from its template.
10800 if (Previous.isAmbiguous())
10801 return true;
10802
10803 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10804 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10805 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10806
10807 if (!PrevTemplate) {
10808 if (!Prev || !Prev->isStaticDataMember()) {
10809 // We expect to see a static data member here.
10810 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10811 << Name;
10812 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10813 P != PEnd; ++P)
10814 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10815 return true;
10816 }
10817
10819 // FIXME: Check for explicit specialization?
10821 diag::err_explicit_instantiation_data_member_not_instantiated)
10822 << Prev;
10823 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10824 // FIXME: Can we provide a note showing where this was declared?
10825 return true;
10826 }
10827 } else {
10828 // Explicitly instantiate a variable template.
10829
10830 // C++1y [dcl.spec.auto]p6:
10831 // ... A program that uses auto or decltype(auto) in a context not
10832 // explicitly allowed in this section is ill-formed.
10833 //
10834 // This includes auto-typed variable template instantiations.
10835 if (R->isUndeducedType()) {
10836 Diag(T->getTypeLoc().getBeginLoc(),
10837 diag::err_auto_not_allowed_var_inst);
10838 return true;
10839 }
10840
10842 // C++1y [temp.explicit]p3:
10843 // If the explicit instantiation is for a variable, the unqualified-id
10844 // in the declaration shall be a template-id.
10846 diag::err_explicit_instantiation_without_template_id)
10847 << PrevTemplate;
10848 Diag(PrevTemplate->getLocation(),
10849 diag::note_explicit_instantiation_here);
10850 return true;
10851 }
10852
10853 // Translate the parser's template argument list into our AST format.
10854 TemplateArgumentListInfo TemplateArgs =
10856
10857 DeclResult Res =
10858 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10859 TemplateArgs, /*SetWrittenArgs=*/true);
10860 if (Res.isInvalid())
10861 return true;
10862
10863 if (!Res.isUsable()) {
10864 // We somehow specified dependent template arguments in an explicit
10865 // instantiation. This should probably only happen during error
10866 // recovery.
10867 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10868 return true;
10869 }
10870
10871 // Ignore access control bits, we don't need them for redeclaration
10872 // checking.
10873 Prev = cast<VarDecl>(Res.get());
10874 ArgsAsWritten =
10876 }
10877
10878 // C++0x [temp.explicit]p2:
10879 // If the explicit instantiation is for a member function, a member class
10880 // or a static data member of a class template specialization, the name of
10881 // the class template specialization in the qualified-id for the member
10882 // name shall be a simple-template-id.
10883 //
10884 // C++98 has the same restriction, just worded differently.
10885 //
10886 // This does not apply to variable template specializations, where the
10887 // template-id is in the unqualified-id instead.
10888 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10890 diag::ext_explicit_instantiation_without_qualified_id)
10891 << Prev << D.getCXXScopeSpec().getRange();
10892
10893 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10894
10895 // Verify that it is okay to explicitly instantiate here.
10898 bool HasNoEffect = false;
10900 PrevTSK, POI, HasNoEffect))
10901 return true;
10902
10903 if (!HasNoEffect) {
10904 // Instantiate static data member or variable template.
10906 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10907 VTSD->setExternKeywordLoc(ExternLoc);
10908 VTSD->setTemplateKeywordLoc(TemplateLoc);
10909 }
10910
10911 // Merge attributes.
10913 if (PrevTemplate)
10914 ProcessAPINotes(Prev);
10915
10918 }
10919
10920 // Check the new variable specialization against the parsed input.
10921 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10922 Diag(T->getTypeLoc().getBeginLoc(),
10923 diag::err_invalid_var_template_spec_type)
10924 << 0 << PrevTemplate << R << Prev->getType();
10925 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10926 << 2 << PrevTemplate->getDeclName();
10927 return true;
10928 }
10929
10931 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10932 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10933 D.getIdentifierLoc(), T, TSK);
10934 return (Decl *)nullptr;
10935 }
10936
10937 // If the declarator is a template-id, translate the parser's template
10938 // argument list into our AST format.
10939 bool HasExplicitTemplateArgs = false;
10940 TemplateArgumentListInfo TemplateArgs;
10942 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10943 HasExplicitTemplateArgs = true;
10944 }
10945
10946 // C++ [temp.explicit]p1:
10947 // A [...] function [...] can be explicitly instantiated from its template.
10948 // A member function [...] of a class template can be explicitly
10949 // instantiated from the member definition associated with its class
10950 // template.
10951 UnresolvedSet<8> TemplateMatches;
10952 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10954 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10955 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10956 P != PEnd; ++P) {
10957 NamedDecl *Prev = *P;
10958 if (!HasExplicitTemplateArgs) {
10959 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10960 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10961 /*AdjustExceptionSpec*/true);
10962 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10963 if (Method->getPrimaryTemplate()) {
10964 TemplateMatches.addDecl(Method, P.getAccess());
10965 } else {
10966 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10967 C.FoundDecl = P.getPair();
10968 C.Function = Method;
10969 C.Viable = true;
10971 if (Method->getTrailingRequiresClause() &&
10973 /*ForOverloadResolution=*/true) ||
10974 !S.IsSatisfied)) {
10975 C.Viable = false;
10977 }
10978 }
10979 }
10980 }
10981 }
10982
10983 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10984 if (!FunTmpl)
10985 continue;
10986
10987 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10988 FunctionDecl *Specialization = nullptr;
10990 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10991 Specialization, Info);
10993 // Keep track of almost-matches.
10994 FailedTemplateCandidates.addCandidate().set(
10995 P.getPair(), FunTmpl->getTemplatedDecl(),
10996 MakeDeductionFailureInfo(Context, TDK, Info));
10997 (void)TDK;
10998 continue;
10999 }
11000
11001 // Target attributes are part of the cuda function signature, so
11002 // the cuda target of the instantiated function must match that of its
11003 // template. Given that C++ template deduction does not take
11004 // target attributes into account, we reject candidates here that
11005 // have a different target.
11006 if (LangOpts.CUDA &&
11007 CUDA().IdentifyTarget(Specialization,
11008 /* IgnoreImplicitHDAttr = */ true) !=
11009 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11010 FailedTemplateCandidates.addCandidate().set(
11011 P.getPair(), FunTmpl->getTemplatedDecl(),
11014 continue;
11015 }
11016
11017 TemplateMatches.addDecl(Specialization, P.getAccess());
11018 }
11019
11020 FunctionDecl *Specialization = nullptr;
11021 if (!NonTemplateMatches.empty()) {
11022 unsigned Msg = 0;
11023 OverloadCandidateDisplayKind DisplayKind;
11025 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11026 Best)) {
11027 case OR_Success:
11028 case OR_Deleted:
11029 Specialization = cast<FunctionDecl>(Best->Function);
11030 break;
11031 case OR_Ambiguous:
11032 Msg = diag::err_explicit_instantiation_ambiguous;
11033 DisplayKind = OCD_AmbiguousCandidates;
11034 break;
11036 Msg = diag::err_explicit_instantiation_no_candidate;
11037 DisplayKind = OCD_AllCandidates;
11038 break;
11039 }
11040 if (Msg) {
11041 PartialDiagnostic Diag = PDiag(Msg) << Name;
11042 NonTemplateMatches.NoteCandidates(
11043 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11044 {});
11045 return true;
11046 }
11047 }
11048
11049 if (!Specialization) {
11050 // Find the most specialized function template specialization.
11052 TemplateMatches.begin(), TemplateMatches.end(),
11053 FailedTemplateCandidates, D.getIdentifierLoc(),
11054 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11055 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11056 PDiag(diag::note_explicit_instantiation_candidate));
11057
11058 if (Result == TemplateMatches.end())
11059 return true;
11060
11061 // Ignore access control bits, we don't need them for redeclaration checking.
11063 }
11064
11065 // C++11 [except.spec]p4
11066 // In an explicit instantiation an exception-specification may be specified,
11067 // but is not required.
11068 // If an exception-specification is specified in an explicit instantiation
11069 // directive, it shall be compatible with the exception-specifications of
11070 // other declarations of that function.
11071 if (auto *FPT = R->getAs<FunctionProtoType>())
11072 if (FPT->hasExceptionSpec()) {
11073 unsigned DiagID =
11074 diag::err_mismatched_exception_spec_explicit_instantiation;
11075 if (getLangOpts().MicrosoftExt)
11076 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11078 PDiag(DiagID) << Specialization->getType(),
11079 PDiag(diag::note_explicit_instantiation_here),
11080 Specialization->getType()->getAs<FunctionProtoType>(),
11081 Specialization->getLocation(), FPT, D.getBeginLoc());
11082 // In Microsoft mode, mismatching exception specifications just cause a
11083 // warning.
11084 if (!getLangOpts().MicrosoftExt && Result)
11085 return true;
11086 }
11087
11088 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11090 diag::err_explicit_instantiation_member_function_not_instantiated)
11092 << (Specialization->getTemplateSpecializationKind() ==
11094 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11095 return true;
11096 }
11097
11098 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11099 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11100 PrevDecl = Specialization;
11101
11102 if (PrevDecl) {
11103 bool HasNoEffect = false;
11105 PrevDecl,
11107 PrevDecl->getPointOfInstantiation(),
11108 HasNoEffect))
11109 return true;
11110
11111 if (HasNoEffect) {
11112 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11113 if (HasExplicitTemplateArgs)
11114 ArgsAsWritten =
11117 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11118 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11119 D.getIdentifierLoc(), T, TSK);
11120 return (Decl *)nullptr;
11121 }
11122 }
11123
11124 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11125 // functions
11126 // valarray<size_t>::valarray(size_t) and
11127 // valarray<size_t>::~valarray()
11128 // that it declared to have internal linkage with the internal_linkage
11129 // attribute. Ignore the explicit instantiation declaration in this case.
11130 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11132 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11133 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11134 RD->isInStdNamespace())
11135 return (Decl*) nullptr;
11136 }
11137
11140
11141 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11142 // instantiation declarations.
11144 Specialization->hasAttr<DLLImportAttr>() &&
11145 Context.getTargetInfo().getCXXABI().isMicrosoft())
11147
11148 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11149 if (Specialization->isDefined()) {
11150 // Let the ASTConsumer know that this function has been explicitly
11151 // instantiated now, and its linkage might have changed.
11152 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11153 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11154 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11155 // be explicitly instantiated.
11156 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11157 RD && RD->isLambda()) {
11158 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11159 << /*instantiation*/ 1;
11160 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11161 return (Decl *)nullptr;
11162 }
11164 }
11165
11166 // C++0x [temp.explicit]p2:
11167 // If the explicit instantiation is for a member function, a member class
11168 // or a static data member of a class template specialization, the name of
11169 // the class template specialization in the qualified-id for the member
11170 // name shall be a simple-template-id.
11171 //
11172 // C++98 has the same restriction, just worded differently.
11173 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11174 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11175 D.getCXXScopeSpec().isSet() &&
11178 diag::ext_explicit_instantiation_without_qualified_id)
11180
11182 *this,
11183 FunTmpl ? (NamedDecl *)FunTmpl
11184 : Specialization->getInstantiatedFromMemberFunction(),
11185 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11186
11187 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11188 if (HasExplicitTemplateArgs)
11189 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11191 TemplateLoc,
11193 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11194 return (Decl *)nullptr;
11195}
11196
11198 const CXXScopeSpec &SS,
11199 const IdentifierInfo *Name,
11200 SourceLocation TagLoc,
11201 SourceLocation NameLoc) {
11202 // This has to hold, because SS is expected to be defined.
11203 assert(Name && "Expected a name in a dependent tag");
11204
11206 if (!NNS)
11207 return true;
11208
11209 if (TUK == TagUseKind::Friend &&
11211 return true;
11212
11214
11215 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11216 Diag(NameLoc, diag::err_dependent_tag_decl)
11217 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11218 return true;
11219 }
11220
11221 // Create the resulting type.
11223 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11224
11225 // Create type-source location information for this type.
11226 TypeLocBuilder TLB;
11228 TL.setElaboratedKeywordLoc(TagLoc);
11230 TL.setNameLoc(NameLoc);
11232}
11233
11235 const CXXScopeSpec &SS,
11236 const IdentifierInfo &II,
11237 SourceLocation IdLoc,
11238 ImplicitTypenameContext IsImplicitTypename) {
11239 if (SS.isInvalid())
11240 return true;
11241
11242 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11243 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11244 << FixItHint::CreateRemoval(TypenameLoc);
11245
11247 TypeSourceInfo *TSI = nullptr;
11248 QualType T =
11251 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11252 /*DeducedTSTContext=*/true);
11253 if (T.isNull())
11254 return true;
11255 return CreateParsedType(T, TSI);
11256}
11257
11260 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11261 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11262 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11263 ASTTemplateArgsPtr TemplateArgsIn,
11264 SourceLocation RAngleLoc) {
11265 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11266 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11267 ? diag::compat_cxx11_typename_outside_of_template
11268 : diag::compat_pre_cxx11_typename_outside_of_template)
11269 << FixItHint::CreateRemoval(TypenameLoc);
11270
11271 // Strangely, non-type results are not ignored by this lookup, so the
11272 // program is ill-formed if it finds an injected-class-name.
11273 if (TypenameLoc.isValid()) {
11274 auto *LookupRD =
11275 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11276 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11277 Diag(TemplateIILoc,
11278 diag::ext_out_of_line_qualified_id_type_names_constructor)
11279 << TemplateII << 0 /*injected-class-name used as template name*/
11280 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11281 }
11282 }
11283
11284 // Translate the parser's template argument list in our AST format.
11285 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11286 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11287
11291 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11292 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11293 if (T.isNull())
11294 return true;
11295
11296 // Provide source-location information for the template specialization type.
11297 TypeLocBuilder Builder;
11299 = Builder.push<TemplateSpecializationTypeLoc>(T);
11300 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11301 TemplateIILoc, TemplateArgs);
11302 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11303 return CreateParsedType(T, TSI);
11304}
11305
11306/// Determine whether this failed name lookup should be treated as being
11307/// disabled by a usage of std::enable_if.
11309 SourceRange &CondRange, Expr *&Cond) {
11310 // We must be looking for a ::type...
11311 if (!II.isStr("type"))
11312 return false;
11313
11314 // ... within an explicitly-written template specialization...
11316 return false;
11317
11318 // FIXME: Look through sugar.
11319 auto EnableIfTSTLoc =
11321 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11322 return false;
11323 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11324
11325 // ... which names a complete class template declaration...
11326 const TemplateDecl *EnableIfDecl =
11327 EnableIfTST->getTemplateName().getAsTemplateDecl();
11328 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11329 return false;
11330
11331 // ... called "enable_if".
11332 const IdentifierInfo *EnableIfII =
11333 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11334 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11335 return false;
11336
11337 // Assume the first template argument is the condition.
11338 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11339
11340 // Dig out the condition.
11341 Cond = nullptr;
11342 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11344 return true;
11345
11346 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11347
11348 // Ignore Boolean literals; they add no value.
11349 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11350 Cond = nullptr;
11351
11352 return true;
11353}
11354
11357 SourceLocation KeywordLoc,
11358 NestedNameSpecifierLoc QualifierLoc,
11359 const IdentifierInfo &II,
11360 SourceLocation IILoc,
11361 TypeSourceInfo **TSI,
11362 bool DeducedTSTContext) {
11363 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11364 DeducedTSTContext);
11365 if (T.isNull())
11366 return QualType();
11367
11368 TypeLocBuilder TLB;
11370 auto TL = TLB.push<DependentNameTypeLoc>(T);
11371 TL.setElaboratedKeywordLoc(KeywordLoc);
11372 TL.setQualifierLoc(QualifierLoc);
11373 TL.setNameLoc(IILoc);
11376 TL.setElaboratedKeywordLoc(KeywordLoc);
11377 TL.setQualifierLoc(QualifierLoc);
11378 TL.setNameLoc(IILoc);
11379 } else if (isa<TemplateTypeParmType>(T)) {
11380 // FIXME: There might be a 'typename' keyword here, but we just drop it
11381 // as it can't be represented.
11382 assert(!QualifierLoc);
11383 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11384 } else if (isa<TagType>(T)) {
11385 auto TL = TLB.push<TagTypeLoc>(T);
11386 TL.setElaboratedKeywordLoc(KeywordLoc);
11387 TL.setQualifierLoc(QualifierLoc);
11388 TL.setNameLoc(IILoc);
11389 } else if (isa<TypedefType>(T)) {
11390 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11391 } else {
11392 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11393 }
11394 *TSI = TLB.getTypeSourceInfo(Context, T);
11395 return T;
11396}
11397
11398/// Build the type that describes a C++ typename specifier,
11399/// e.g., "typename T::type".
11402 SourceLocation KeywordLoc,
11403 NestedNameSpecifierLoc QualifierLoc,
11404 const IdentifierInfo &II,
11405 SourceLocation IILoc, bool DeducedTSTContext) {
11406 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11407
11408 CXXScopeSpec SS;
11409 SS.Adopt(QualifierLoc);
11410
11411 DeclContext *Ctx = nullptr;
11412 if (QualifierLoc) {
11413 Ctx = computeDeclContext(SS);
11414 if (!Ctx) {
11415 // If the nested-name-specifier is dependent and couldn't be
11416 // resolved to a type, build a typename type.
11417 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11418 return Context.getDependentNameType(Keyword,
11419 QualifierLoc.getNestedNameSpecifier(),
11420 &II);
11421 }
11422
11423 // If the nested-name-specifier refers to the current instantiation,
11424 // the "typename" keyword itself is superfluous. In C++03, the
11425 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11426 // allows such extraneous "typename" keywords, and we retroactively
11427 // apply this DR to C++03 code with only a warning. In any case we continue.
11428
11429 if (RequireCompleteDeclContext(SS, Ctx))
11430 return QualType();
11431 }
11432
11433 DeclarationName Name(&II);
11434 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11435 if (Ctx)
11436 LookupQualifiedName(Result, Ctx, SS);
11437 else
11438 LookupName(Result, CurScope);
11439 unsigned DiagID = 0;
11440 Decl *Referenced = nullptr;
11441 switch (Result.getResultKind()) {
11443 // If we're looking up 'type' within a template named 'enable_if', produce
11444 // a more specific diagnostic.
11445 SourceRange CondRange;
11446 Expr *Cond = nullptr;
11447 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11448 // If we have a condition, narrow it down to the specific failed
11449 // condition.
11450 if (Cond) {
11451 Expr *FailedCond;
11452 std::string FailedDescription;
11453 std::tie(FailedCond, FailedDescription) =
11455
11456 Diag(FailedCond->getExprLoc(),
11457 diag::err_typename_nested_not_found_requirement)
11458 << FailedDescription
11459 << FailedCond->getSourceRange();
11460 return QualType();
11461 }
11462
11463 Diag(CondRange.getBegin(),
11464 diag::err_typename_nested_not_found_enable_if)
11465 << Ctx << CondRange;
11466 return QualType();
11467 }
11468
11469 DiagID = Ctx ? diag::err_typename_nested_not_found
11470 : diag::err_unknown_typename;
11471 break;
11472 }
11473
11475 // We found a using declaration that is a value. Most likely, the using
11476 // declaration itself is meant to have the 'typename' keyword.
11477 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11478 IILoc);
11479 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11480 << Name << Ctx << FullRange;
11481 if (UnresolvedUsingValueDecl *Using
11482 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11483 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11484 Diag(Loc, diag::note_using_value_decl_missing_typename)
11485 << FixItHint::CreateInsertion(Loc, "typename ");
11486 }
11487 }
11488 // Fall through to create a dependent typename type, from which we can
11489 // recover better.
11490 [[fallthrough]];
11491
11493 // Okay, it's a member of an unknown instantiation.
11494 return Context.getDependentNameType(Keyword,
11495 QualifierLoc.getNestedNameSpecifier(),
11496 &II);
11497
11499 // FXIME: Missing support for UsingShadowDecl on this path?
11500 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11501 // C++ [class.qual]p2:
11502 // In a lookup in which function names are not ignored and the
11503 // nested-name-specifier nominates a class C, if the name specified
11504 // after the nested-name-specifier, when looked up in C, is the
11505 // injected-class-name of C [...] then the name is instead considered
11506 // to name the constructor of class C.
11507 //
11508 // Unlike in an elaborated-type-specifier, function names are not ignored
11509 // in typename-specifier lookup. However, they are ignored in all the
11510 // contexts where we form a typename type with no keyword (that is, in
11511 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11512 //
11513 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11514 // ignore functions, but that appears to be an oversight.
11519 Type, IILoc);
11520 // FIXME: This appears to be the only case where a template type parameter
11521 // can have an elaborated keyword. We should preserve it somehow.
11524 assert(!QualifierLoc);
11526 }
11527 return Context.getTypeDeclType(
11528 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11529 }
11530
11531 // C++ [dcl.type.simple]p2:
11532 // A type-specifier of the form
11533 // typename[opt] nested-name-specifier[opt] template-name
11534 // is a placeholder for a deduced class type [...].
11535 if (getLangOpts().CPlusPlus17) {
11536 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11537 if (!DeducedTSTContext) {
11538 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11539 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11540 Diag(IILoc, diag::err_dependent_deduced_tst)
11542 << QualType(Qualifier.getAsType(), 0);
11543 else
11544 Diag(IILoc, diag::err_deduced_tst)
11547 return QualType();
11548 }
11549 TemplateName Name = Context.getQualifiedTemplateName(
11550 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11551 TemplateName(TD));
11552 return Context.getDeducedTemplateSpecializationType(
11553 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11554 Name);
11555 }
11556 }
11557
11558 DiagID = Ctx ? diag::err_typename_nested_not_type
11559 : diag::err_typename_not_type;
11560 Referenced = Result.getFoundDecl();
11561 break;
11562
11564 DiagID = Ctx ? diag::err_typename_nested_not_type
11565 : diag::err_typename_not_type;
11566 Referenced = *Result.begin();
11567 break;
11568
11570 return QualType();
11571 }
11572
11573 // If we get here, it's because name lookup did not find a
11574 // type. Emit an appropriate diagnostic and return an error.
11575 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11576 IILoc);
11577 if (Ctx)
11578 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11579 else
11580 Diag(IILoc, DiagID) << FullRange << Name;
11581 if (Referenced)
11582 Diag(Referenced->getLocation(),
11583 Ctx ? diag::note_typename_member_refers_here
11584 : diag::note_typename_refers_here)
11585 << Name;
11586 return QualType();
11587}
11588
11589namespace {
11590 // See Sema::RebuildTypeInCurrentInstantiation
11591 class CurrentInstantiationRebuilder
11592 : public TreeTransform<CurrentInstantiationRebuilder> {
11593 SourceLocation Loc;
11594 DeclarationName Entity;
11595
11596 public:
11598
11599 CurrentInstantiationRebuilder(Sema &SemaRef,
11600 SourceLocation Loc,
11601 DeclarationName Entity)
11602 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11603 Loc(Loc), Entity(Entity) { }
11604
11605 /// Determine whether the given type \p T has already been
11606 /// transformed.
11607 ///
11608 /// For the purposes of type reconstruction, a type has already been
11609 /// transformed if it is NULL or if it is not dependent.
11610 bool AlreadyTransformed(QualType T) {
11611 return T.isNull() || !T->isInstantiationDependentType();
11612 }
11613
11614 /// Returns the location of the entity whose type is being
11615 /// rebuilt.
11616 SourceLocation getBaseLocation() { return Loc; }
11617
11618 /// Returns the name of the entity whose type is being rebuilt.
11619 DeclarationName getBaseEntity() { return Entity; }
11620
11621 /// Sets the "base" location and entity when that
11622 /// information is known based on another transformation.
11623 void setBase(SourceLocation Loc, DeclarationName Entity) {
11624 this->Loc = Loc;
11625 this->Entity = Entity;
11626 }
11627
11628 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11629 // Lambdas never need to be transformed.
11630 return E;
11631 }
11632 };
11633} // end anonymous namespace
11634
11636 SourceLocation Loc,
11637 DeclarationName Name) {
11638 if (!T || !T->getType()->isInstantiationDependentType())
11639 return T;
11640
11641 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11642 return Rebuilder.TransformType(T);
11643}
11644
11646 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11647 DeclarationName());
11648 return Rebuilder.TransformExpr(E);
11649}
11650
11652 if (SS.isInvalid())
11653 return true;
11654
11656 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11657 DeclarationName());
11659 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11660 if (!Rebuilt)
11661 return true;
11662
11663 SS.Adopt(Rebuilt);
11664 return false;
11665}
11666
11668 TemplateParameterList *Params) {
11669 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11670 Decl *Param = Params->getParam(I);
11671
11672 // There is nothing to rebuild in a type parameter.
11673 if (isa<TemplateTypeParmDecl>(Param))
11674 continue;
11675
11676 // Rebuild the template parameter list of a template template parameter.
11678 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11680 TTP->getTemplateParameters()))
11681 return true;
11682
11683 continue;
11684 }
11685
11686 // Rebuild the type of a non-type template parameter.
11688 TypeSourceInfo *NewTSI
11690 NTTP->getLocation(),
11691 NTTP->getDeclName());
11692 if (!NewTSI)
11693 return true;
11694
11695 if (NewTSI->getType()->isUndeducedType()) {
11696 // C++17 [temp.dep.expr]p3:
11697 // An id-expression is type-dependent if it contains
11698 // - an identifier associated by name lookup with a non-type
11699 // template-parameter declared with a type that contains a
11700 // placeholder type (7.1.7.4),
11701 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11702 }
11703
11704 if (NewTSI != NTTP->getTypeSourceInfo()) {
11705 NTTP->setTypeSourceInfo(NewTSI);
11706 NTTP->setType(NewTSI->getType());
11707 }
11708 }
11709
11710 return false;
11711}
11712
11713std::string
11715 const TemplateArgumentList &Args) {
11716 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11717}
11718
11719std::string
11721 const TemplateArgument *Args,
11722 unsigned NumArgs) {
11723 SmallString<128> Str;
11724 llvm::raw_svector_ostream Out(Str);
11725
11726 if (!Params || Params->size() == 0 || NumArgs == 0)
11727 return std::string();
11728
11729 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11730 if (I >= NumArgs)
11731 break;
11732
11733 if (I == 0)
11734 Out << "[with ";
11735 else
11736 Out << ", ";
11737
11738 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11739 Out << Id->getName();
11740 } else {
11741 Out << '$' << I;
11742 }
11743
11744 Out << " = ";
11745 Args[I].print(getPrintingPolicy(), Out,
11747 getPrintingPolicy(), Params, I));
11748 }
11749
11750 Out << ']';
11751 return std::string(Out.str());
11752}
11753
11755 CachedTokens &Toks) {
11756 if (!FD)
11757 return;
11758
11759 auto LPT = std::make_unique<LateParsedTemplate>();
11760
11761 // Take tokens to avoid allocations
11762 LPT->Toks.swap(Toks);
11763 LPT->D = FnD;
11764 LPT->FPO = getCurFPFeatures();
11765 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11766
11767 FD->setLateTemplateParsed(true);
11768}
11769
11771 if (!FD)
11772 return;
11773 FD->setLateTemplateParsed(false);
11774}
11775
11777 DeclContext *DC = CurContext;
11778
11779 while (DC) {
11780 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11781 const FunctionDecl *FD = RD->isLocalClass();
11782 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11783 } else if (DC->isTranslationUnit() || DC->isNamespace())
11784 return false;
11785
11786 DC = DC->getParent();
11787 }
11788 return false;
11789}
11790
11791namespace {
11792/// Walk the path from which a declaration was instantiated, and check
11793/// that every explicit specialization along that path is visible. This enforces
11794/// C++ [temp.expl.spec]/6:
11795///
11796/// If a template, a member template or a member of a class template is
11797/// explicitly specialized then that specialization shall be declared before
11798/// the first use of that specialization that would cause an implicit
11799/// instantiation to take place, in every translation unit in which such a
11800/// use occurs; no diagnostic is required.
11801///
11802/// and also C++ [temp.class.spec]/1:
11803///
11804/// A partial specialization shall be declared before the first use of a
11805/// class template specialization that would make use of the partial
11806/// specialization as the result of an implicit or explicit instantiation
11807/// in every translation unit in which such a use occurs; no diagnostic is
11808/// required.
11809class ExplicitSpecializationVisibilityChecker {
11810 Sema &S;
11811 SourceLocation Loc;
11814
11815public:
11816 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11818 : S(S), Loc(Loc), Kind(Kind) {}
11819
11820 void check(NamedDecl *ND) {
11821 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11822 return checkImpl(FD);
11823 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11824 return checkImpl(RD);
11825 if (auto *VD = dyn_cast<VarDecl>(ND))
11826 return checkImpl(VD);
11827 if (auto *ED = dyn_cast<EnumDecl>(ND))
11828 return checkImpl(ED);
11829 }
11830
11831private:
11832 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11833 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11834 : Sema::MissingImportKind::ExplicitSpecialization;
11835 const bool Recover = true;
11836
11837 // If we got a custom set of modules (because only a subset of the
11838 // declarations are interesting), use them, otherwise let
11839 // diagnoseMissingImport intelligently pick some.
11840 if (Modules.empty())
11841 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11842 else
11843 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11844 }
11845
11846 bool CheckMemberSpecialization(const NamedDecl *D) {
11847 return Kind == Sema::AcceptableKind::Visible
11850 }
11851
11852 bool CheckExplicitSpecialization(const NamedDecl *D) {
11853 return Kind == Sema::AcceptableKind::Visible
11856 }
11857
11858 bool CheckDeclaration(const NamedDecl *D) {
11859 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11861 }
11862
11863 // Check a specific declaration. There are three problematic cases:
11864 //
11865 // 1) The declaration is an explicit specialization of a template
11866 // specialization.
11867 // 2) The declaration is an explicit specialization of a member of an
11868 // templated class.
11869 // 3) The declaration is an instantiation of a template, and that template
11870 // is an explicit specialization of a member of a templated class.
11871 //
11872 // We don't need to go any deeper than that, as the instantiation of the
11873 // surrounding class / etc is not triggered by whatever triggered this
11874 // instantiation, and thus should be checked elsewhere.
11875 template<typename SpecDecl>
11876 void checkImpl(SpecDecl *Spec) {
11877 bool IsHiddenExplicitSpecialization = false;
11878 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11879 // Some invalid friend declarations are written as specializations but are
11880 // instantiated implicitly.
11881 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11882 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11883 if (SpecKind == TSK_ExplicitSpecialization) {
11884 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11885 ? !CheckMemberSpecialization(Spec)
11886 : !CheckExplicitSpecialization(Spec);
11887 } else {
11888 checkInstantiated(Spec);
11889 }
11890
11891 if (IsHiddenExplicitSpecialization)
11892 diagnose(Spec->getMostRecentDecl(), false);
11893 }
11894
11895 void checkInstantiated(FunctionDecl *FD) {
11896 if (auto *TD = FD->getPrimaryTemplate())
11897 checkTemplate(TD);
11898 }
11899
11900 void checkInstantiated(CXXRecordDecl *RD) {
11901 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11902 if (!SD)
11903 return;
11904
11905 auto From = SD->getSpecializedTemplateOrPartial();
11906 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11907 checkTemplate(TD);
11908 else if (auto *TD =
11909 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11910 if (!CheckDeclaration(TD))
11911 diagnose(TD, true);
11912 checkTemplate(TD);
11913 }
11914 }
11915
11916 void checkInstantiated(VarDecl *RD) {
11917 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11918 if (!SD)
11919 return;
11920
11921 auto From = SD->getSpecializedTemplateOrPartial();
11922 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11923 checkTemplate(TD);
11924 else if (auto *TD =
11925 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11926 if (!CheckDeclaration(TD))
11927 diagnose(TD, true);
11928 checkTemplate(TD);
11929 }
11930 }
11931
11932 void checkInstantiated(EnumDecl *FD) {}
11933
11934 template<typename TemplDecl>
11935 void checkTemplate(TemplDecl *TD) {
11936 if (TD->isMemberSpecialization()) {
11937 if (!CheckMemberSpecialization(TD))
11938 diagnose(TD->getMostRecentDecl(), false);
11939 }
11940 }
11941};
11942} // end anonymous namespace
11943
11945 if (!getLangOpts().Modules)
11946 return;
11947
11948 ExplicitSpecializationVisibilityChecker(*this, Loc,
11950 .check(Spec);
11951}
11952
11954 NamedDecl *Spec) {
11955 if (!getLangOpts().CPlusPlusModules)
11956 return checkSpecializationVisibility(Loc, Spec);
11957
11958 ExplicitSpecializationVisibilityChecker(*this, Loc,
11960 .check(Spec);
11961}
11962
11965 return N->getLocation();
11966 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11968 return FD->getLocation();
11971 return N->getLocation();
11972 }
11973 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11974 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11975 continue;
11976 return CSC.PointOfInstantiation;
11977 }
11978 return N->getLocation();
11979}
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)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
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.
Result
Implement __builtin_bit_cast and related operations.
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 void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
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, bool IsSpecified, 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:1018
APSInt & getInt()
Definition APValue.h:511
APSInt & getComplexIntImag()
Definition APValue.h:549
ValueKind getKind() const
Definition APValue.h:482
APFixedPoint & getFixedPoint()
Definition APValue.h:533
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1101
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
bool isMemberPointer() const
Definition APValue.h:499
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:991
@ 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:1054
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
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:981
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
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.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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:4006
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:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2424
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2466
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8356
Pointer to a block type.
Definition TypeBase.h:3656
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:3241
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:2113
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:739
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3921
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:1583
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
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:133
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:2032
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:2062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2039
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2073
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
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:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
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:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
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:1072
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.
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:3355
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:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
bool isFileContext() const
Definition DeclBase.h:2197
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:2219
bool isTranslationUnit() const
Definition DeclBase.h:2202
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
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:1281
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1382
ValueDecl * getDecl()
Definition Expr.h:1349
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:655
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
bool isNoreturnSpecified() const
Definition DeclSpec.h:668
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:669
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:661
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
bool isInlineSpecified() const
Definition DeclSpec.h:644
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:656
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:843
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
bool hasExplicitSpecifier() const
Definition DeclSpec.h:658
bool hasConstexprSpecifier() const
Definition DeclSpec.h:844
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:1078
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:824
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:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2823
bool isInvalidDecl() const
Definition DeclBase.h:596
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
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:935
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
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
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4175
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3561
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:575
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4125
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4215
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4587
static DependentTemplateIdExpr * Create(const ASTContext &Context, const DeclarationNameInfo &NameInfo, TemplateName Name, const TemplateArgumentListInfo &TemplateArgs)
Definition ExprCXX.cpp:422
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3509
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4341
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:4145
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4417
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5217
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
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:3106
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:447
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:3101
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:838
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:3081
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:4082
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4381
Represents a member of a struct/union/class.
Definition Decl.h:3294
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1003
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1082
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
Represents a function declaration or definition.
Definition Decl.h:2058
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2602
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4248
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4577
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4356
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4215
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3790
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2666
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4187
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:4421
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2488
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4460
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3157
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4208
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4999
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
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:4957
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:3864
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:4023
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5319
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:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
Represents a linkage specification.
Definition DeclCXX.h:3040
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
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
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
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
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
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4428
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
QualType getPointeeType() const
Definition TypeBase.h:3785
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:240
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:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
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:1683
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
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.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
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:8066
Represents a pointer to an Objective C object.
Definition TypeBase.h:8122
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:1189
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1161
@ CSK_Normal
Normal lookup.
Definition Overload.h:1165
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1377
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:1424
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:4414
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2193
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:8322
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
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:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3718
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8504
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:8689
QualType getCanonicalType() const
Definition TypeBase.h:8556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8598
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3711
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
bool ValidateCandidate(const TypoCorrection &Candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
QualifiedLookupValidatorCCC(bool HasQualifier)
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3749
Represents a struct/union/class.
Definition Decl.h:4459
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4643
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5464
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
QualType getPointeeType() const
Definition TypeBase.h:3705
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:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:318
@ 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
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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:13754
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8466
A RAII object to temporarily push a declaration context.
Definition Sema.h:3533
Whether and why a template name is required in this lookup.
Definition Sema.h:11485
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11493
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12543
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12577
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7736
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:13701
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13152
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2691
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:9360
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9364
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9372
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9367
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:9676
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:1472
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 RebuildExprInCurrentInstantiation(Expr *E)
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:4212
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:2080
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:11456
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12054
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12057
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12061
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
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:1305
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...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:933
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:936
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:777
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:1209
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)
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:12233
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12251
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12241
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12261
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:11506
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11513
@ None
This is not assumed to be a template name.
Definition Sema.h:11508
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11510
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:11442
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
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:931
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
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:14548
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14536
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14545
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14539
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14563
const LangOptions & getLangOpts() const
Definition Sema.h:929
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:1304
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:1303
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)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
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:1445
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,...
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
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 isSFINAEContext() const
Definition Sema.h:13792
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:15563
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 ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1306
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:4710
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:6756
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6735
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:14059
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.
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, const TemplateArgumentListInfo *TemplateArgs)
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:11483
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:523
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:11666
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11676
@ TPC_FriendFunctionTemplate
Definition Sema.h:11674
@ TPC_ClassTemplateMember
Definition Sema.h:11672
@ TPC_FunctionTemplate
Definition Sema.h:11671
@ TPC_FriendClassTemplate
Definition Sema.h:11673
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11675
friend class InitializationSequence
Definition Sema.h:1587
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)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
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:6359
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.
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, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
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...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6443
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1297
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
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:3526
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11448
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:149
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:9685
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12995
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:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8679
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13789
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:367
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:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4715
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3851
StringRef getKindName() const
Definition Decl.h:4047
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4969
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5105
TagKind getTagKind() const
Definition Decl.h:4051
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:650
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)
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.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
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)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
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:3822
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:3647
const Type * getTypeForDecl() const
Definition Decl.h:3672
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3681
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:890
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:6332
A container of type source information.
Definition TypeBase.h:8475
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8486
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBooleanType() const
Definition TypeBase.h:9250
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2387
bool isRValueReferenceType() const
Definition TypeBase.h:8773
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8840
bool isPointerType() const
Definition TypeBase.h:8741
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
bool isEnumeralType() const
Definition TypeBase.h:8872
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2186
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:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9235
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8928
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2976
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2867
bool isLValueReferenceType() const
Definition TypeBase.h:8769
bool isBitIntType() const
Definition TypeBase.h:9016
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8864
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2139
bool isMemberPointerType() const
Definition TypeBase.h:8822
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2877
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9256
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:5065
bool isPointerOrReferenceType() const
Definition TypeBase.h:8745
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
bool isFunctionType() const
Definition TypeBase.h:8737
bool isVectorType() const
Definition TypeBase.h:8880
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
bool isNullPtrType() const
Definition TypeBase.h:9150
bool isRecordType() const
Definition TypeBase.h:8868
QualType getUnderlyingType() const
Definition Decl.h:3751
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4207
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:2255
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1071
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1251
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1067
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3372
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:463
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:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6137
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3965
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3424
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3488
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
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2743
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:2878
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:2771
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:2750
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2869
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)
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:4080
Represents a GCC generic vector type.
Definition TypeBase.h:4289
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.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
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,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1935
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:825
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:921
@ 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:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:599
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
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:249
@ SC_Extern
Definition Specifiers.h:252
@ TSCS_unspecified
Definition Specifiers.h:237
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:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:446
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6045
@ Enum
The "enum" keyword.
Definition TypeBase.h:6059
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:557
@ Type
The name was classified as a type.
Definition Sema.h:559
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
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
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:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
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:375
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:423
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:427
@ Success
Template argument deduction was successful.
Definition Sema.h:377
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:429
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
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:1256
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:836
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:837
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:846
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:6020
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6041
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6034
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6038
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
CharacterLiteralKind
Definition Expr.h:1614
#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:657
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:659
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:641
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:616
Extra information about a function prototype.
Definition TypeBase.h:5506
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3417
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3434
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3399
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:934
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:12092
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12088
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12081
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12078
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12078
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13203
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13307
A stack object to be created when performing template instantiation.
Definition Sema.h:13397
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13550
NamedDecl * Previous
Definition Sema.h:362
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:1050