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 = TN.getAsTemplateTemplateParmDecl()) {
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, TN,
1205 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
1206 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1207 ConstrainedParameter, EllipsisLoc);
1208}
1209
1210template <typename ArgumentLocAppender>
1213 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1214 SourceLocation RAngleLoc, QualType ConstrainedType,
1215 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1216 SourceLocation EllipsisLoc) {
1217
1218 TemplateArgumentListInfo ConstraintArgs;
1219 ConstraintArgs.addArgument(
1221 /*NTTPType=*/QualType(), ParamNameLoc));
1222
1223 ConstraintArgs.setRAngleLoc(RAngleLoc);
1224 ConstraintArgs.setLAngleLoc(LAngleLoc);
1225 Appender(ConstraintArgs);
1226
1227 // C++2a [temp.param]p4:
1228 // [...] This constraint-expression E is called the immediately-declared
1229 // constraint of T. [...]
1230 CXXScopeSpec SS;
1231 SS.Adopt(NS);
1232 ExprResult ImmediatelyDeclaredConstraint;
1233 if (auto *CD =
1234 dyn_cast_if_present<ConceptDecl>(NamedConcept.getAsTemplateDecl())) {
1235 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1236 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1237 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1238 /*DoCheckConstraintSatisfaction=*/
1240 }
1241 // We have a template template parameter
1242 else {
1243 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1244 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1245 NameInfo, NamedConcept, &ConstraintArgs);
1246 }
1247 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1248 return ImmediatelyDeclaredConstraint;
1249
1250 // C++2a [temp.param]p4:
1251 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1252 //
1253 // We have the following case:
1254 //
1255 // template<typename T> concept C1 = true;
1256 // template<C1... T> struct s1;
1257 //
1258 // The constraint: (C1<T> && ...)
1259 //
1260 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1261 // any unqualified lookups for 'operator&&' here.
1262 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1263 /*LParenLoc=*/SourceLocation(),
1264 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1265 EllipsisLoc, /*RHS=*/nullptr,
1266 /*RParenLoc=*/SourceLocation(),
1267 /*NumExpansions=*/std::nullopt);
1268}
1269
1271 DeclarationNameInfo NameInfo,
1272 TemplateName NamedConcept, 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(),
1334 /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1335 BuildDecltypeType(Ref), 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 &&
2114 !isTagRedeclarationInScope(Previous.getRepresentativeDecl(),
2115 SemanticContext, S, SS.isValid()))
2116 PrevDecl = PrevClassTemplate = nullptr;
2117
2118 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2119 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2120 if (SS.isEmpty() &&
2121 !(PrevClassTemplate &&
2122 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2123 SemanticContext->getRedeclContext()))) {
2124 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2125 Diag(Shadow->getTargetDecl()->getLocation(),
2126 diag::note_using_decl_target);
2127 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2128 // Recover by ignoring the old declaration.
2129 PrevDecl = PrevClassTemplate = nullptr;
2130 }
2131 }
2132
2133 if (PrevClassTemplate) {
2134 // Ensure that the template parameter lists are compatible. Skip this check
2135 // for a friend in a dependent context: the template parameter list itself
2136 // could be dependent.
2137 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2139 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2140 : CurContext,
2141 CurContext, KWLoc),
2142 TemplateParams, PrevClassTemplate,
2143 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2145 return true;
2146
2147 // C++ [temp.class]p4:
2148 // In a redeclaration, partial specialization, explicit
2149 // specialization or explicit instantiation of a class template,
2150 // the class-key shall agree in kind with the original class
2151 // template declaration (7.1.5.3).
2152 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2154 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2155 Diag(KWLoc, diag::err_use_with_wrong_tag)
2156 << Name
2157 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2158 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2159 Kind = PrevRecordDecl->getTagKind();
2160 }
2161
2162 // Check for redefinition of this class template.
2163 if (TUK == TagUseKind::Definition) {
2164 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2165 // If we have a prior definition that is not visible, treat this as
2166 // simply making that previous definition visible.
2167 NamedDecl *Hidden = nullptr;
2168 bool HiddenDefVisible = false;
2169 if (SkipBody &&
2170 isRedefinitionAllowedFor(Def, NameLoc, &Hidden, HiddenDefVisible)) {
2171 SkipBody->ShouldSkip = true;
2172 SkipBody->Previous = Def;
2173 if (!HiddenDefVisible && Hidden) {
2174 auto *Tmpl =
2175 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2176 assert(Tmpl && "original definition of a class template is not a "
2177 "class template?");
2180 }
2181 } else {
2182 Diag(NameLoc, diag::err_redefinition) << Name;
2183 Diag(Def->getLocation(), diag::note_previous_definition);
2184 // FIXME: Would it make sense to try to "forget" the previous
2185 // definition, as part of error recovery?
2186 return true;
2187 }
2188 }
2189 }
2190 } else if (PrevDecl) {
2191 // C++ [temp]p5:
2192 // A class template shall not have the same name as any other
2193 // template, class, function, object, enumeration, enumerator,
2194 // namespace, or type in the same scope (3.3), except as specified
2195 // in (14.5.4).
2196 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2197 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2198 return true;
2199 }
2200
2201 // Check the template parameter list of this declaration, possibly
2202 // merging in the template parameter list from the previous class
2203 // template declaration. Skip this check for a friend in a dependent
2204 // context, because the template parameter list might be dependent.
2205 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2207 TemplateParams,
2208 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2209 : nullptr,
2210 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2211 SemanticContext->isDependentContext())
2214 : TPC_Other,
2215 SkipBody))
2216 Invalid = true;
2217
2218 if (SS.isSet()) {
2219 // If the name of the template was qualified, we must be defining the
2220 // template out-of-line.
2221 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2222 return Diag(NameLoc, TUK == TagUseKind::Friend
2223 ? diag::err_friend_decl_does_not_match
2224 : diag::err_member_decl_does_not_match)
2225 << Name << SemanticContext << /*IsDefinition*/ true
2226 << SS.getRange();
2227 }
2228
2229 // If this is a templated friend in a dependent context we should not put it
2230 // on the redecl chain. In some cases, the templated friend can be the most
2231 // recent declaration tricking the template instantiator to make substitutions
2232 // there.
2233 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2234 bool ShouldAddRedecl =
2235 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2236
2238 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2239 PrevClassTemplate && ShouldAddRedecl
2240 ? PrevClassTemplate->getTemplatedDecl()
2241 : nullptr);
2242 SetNestedNameSpecifier(*this, NewClass, SS);
2243 if (NumOuterTemplateParamLists > 0)
2245 Context,
2246 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2247
2248 // Add alignment attributes if necessary; these attributes are checked when
2249 // the ASTContext lays out the structure.
2250 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2251 if (LangOpts.HLSL)
2252 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2255 }
2256
2257 ClassTemplateDecl *NewTemplate
2258 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2259 DeclarationName(Name), TemplateParams,
2260 NewClass);
2261
2262 if (ShouldAddRedecl)
2263 NewTemplate->setPreviousDecl(PrevClassTemplate);
2264
2265 NewClass->setDescribedClassTemplate(NewTemplate);
2266
2267 if (ModulePrivateLoc.isValid())
2268 NewTemplate->setModulePrivate();
2269
2270 if (IsMemberSpecialization) {
2271 assert(PrevClassTemplate &&
2272 "Member specialization without a primary template?");
2273 NewTemplate->setMemberSpecialization();
2274 }
2275
2276 // Set the access specifier.
2277 if (!Invalid && TUK != TagUseKind::Friend &&
2278 NewTemplate->getDeclContext()->isRecord())
2279 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2280
2281 // Set the lexical context of these templates
2283 NewTemplate->setLexicalDeclContext(CurContext);
2284
2285 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2286 NewClass->startDefinition();
2287
2288 ProcessDeclAttributeList(S, NewClass, Attr);
2289
2290 if (PrevClassTemplate) {
2291 mergeDeclAttributes(NewTemplate, PrevClassTemplate);
2292 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2293 }
2294
2298
2299 if (TUK != TagUseKind::Friend) {
2300 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2301 Scope *Outer = S;
2302 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2303 Outer = Outer->getParent();
2304 PushOnScopeChains(NewTemplate, Outer);
2305 } else {
2306 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2307 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2308 NewClass->setAccess(PrevClassTemplate->getAccess());
2309 }
2310
2311 NewTemplate->setObjectOfFriendDecl();
2312
2313 // Friend templates are visible in fairly strange ways.
2314 if (!CurContext->isDependentContext()) {
2315 DeclContext *DC = SemanticContext->getRedeclContext();
2316 DC->makeDeclVisibleInContext(NewTemplate);
2317 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2318 PushOnScopeChains(NewTemplate, EnclosingScope,
2319 /* AddToContext = */ false);
2320 }
2321
2323 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2324 Friend->setAccess(AS_public);
2325 CurContext->addDecl(Friend);
2326 }
2327
2328 if (PrevClassTemplate)
2329 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2330
2331 if (Invalid) {
2332 NewTemplate->setInvalidDecl();
2333 NewClass->setInvalidDecl();
2334 }
2335
2336 ActOnDocumentableDecl(NewTemplate);
2337
2338 if (SkipBody && SkipBody->ShouldSkip)
2339 return SkipBody->Previous;
2340
2341 return NewTemplate;
2342}
2343
2344/// Diagnose the presence of a default template argument on a
2345/// template parameter, which is ill-formed in certain contexts.
2346///
2347/// \returns true if the default template argument should be dropped.
2350 SourceLocation ParamLoc,
2351 SourceRange DefArgRange) {
2352 switch (TPC) {
2353 case Sema::TPC_Other:
2355 return false;
2356
2359 // C++ [temp.param]p9:
2360 // A default template-argument shall not be specified in a
2361 // function template declaration or a function template
2362 // definition [...]
2363 // If a friend function template declaration specifies a default
2364 // template-argument, that declaration shall be a definition and shall be
2365 // the only declaration of the function template in the translation unit.
2366 // (C++98/03 doesn't have this wording; see DR226).
2367 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2368 << DefArgRange;
2369 return false;
2370
2372 // C++0x [temp.param]p9:
2373 // A default template-argument shall not be specified in the
2374 // template-parameter-lists of the definition of a member of a
2375 // class template that appears outside of the member's class.
2376 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2377 << DefArgRange;
2378 return true;
2379
2382 // C++ [temp.param]p9:
2383 // A default template-argument shall not be specified in a
2384 // friend template declaration.
2385 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2386 << DefArgRange;
2387 return true;
2388
2389 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2390 // for friend function templates if there is only a single
2391 // declaration (and it is a definition). Strange!
2392 }
2393
2394 llvm_unreachable("Invalid TemplateParamListContext!");
2395}
2396
2397/// Check for unexpanded parameter packs within the template parameters
2398/// of a template template parameter, recursively.
2401 // A template template parameter which is a parameter pack is also a pack
2402 // expansion.
2403 if (TTP->isParameterPack())
2404 return false;
2405
2407 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2408 NamedDecl *P = Params->getParam(I);
2409 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2410 if (!TTP->isParameterPack())
2411 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2412 if (TC->hasExplicitTemplateArgs())
2413 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2416 return true;
2417 continue;
2418 }
2419
2420 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2421 if (!NTTP->isParameterPack() &&
2422 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2423 NTTP->getTypeSourceInfo(),
2425 return true;
2426
2427 continue;
2428 }
2429
2430 if (TemplateTemplateParmDecl *InnerTTP
2431 = dyn_cast<TemplateTemplateParmDecl>(P))
2432 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2433 return true;
2434 }
2435
2436 return false;
2437}
2438
2440 TemplateParameterList *OldParams,
2442 SkipBodyInfo *SkipBody) {
2443 bool Invalid = false;
2444
2445 // C++ [temp.param]p10:
2446 // The set of default template-arguments available for use with a
2447 // template declaration or definition is obtained by merging the
2448 // default arguments from the definition (if in scope) and all
2449 // declarations in scope in the same way default function
2450 // arguments are (8.3.6).
2451 bool SawDefaultArgument = false;
2452 SourceLocation PreviousDefaultArgLoc;
2453
2454 // Dummy initialization to avoid warnings.
2455 TemplateParameterList::iterator OldParam = NewParams->end();
2456 if (OldParams)
2457 OldParam = OldParams->begin();
2458
2459 bool RemoveDefaultArguments = false;
2460 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2461 NewParamEnd = NewParams->end();
2462 NewParam != NewParamEnd; ++NewParam) {
2463 // Whether we've seen a duplicate default argument in the same translation
2464 // unit.
2465 bool RedundantDefaultArg = false;
2466 // Whether we've found inconsis inconsitent default arguments in different
2467 // translation unit.
2468 bool InconsistentDefaultArg = false;
2469 // The name of the module which contains the inconsistent default argument.
2470 std::string PrevModuleName;
2471
2472 SourceLocation OldDefaultLoc;
2473 SourceLocation NewDefaultLoc;
2474
2475 // Variable used to diagnose missing default arguments
2476 bool MissingDefaultArg = false;
2477
2478 // Variable used to diagnose non-final parameter packs
2479 bool SawParameterPack = false;
2480
2481 if (TemplateTypeParmDecl *NewTypeParm
2482 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2483 // Check the presence of a default argument here.
2484 if (NewTypeParm->hasDefaultArgument() &&
2486 *this, TPC, NewTypeParm->getLocation(),
2487 NewTypeParm->getDefaultArgument().getSourceRange()))
2488 NewTypeParm->removeDefaultArgument();
2489
2490 // Merge default arguments for template type parameters.
2491 TemplateTypeParmDecl *OldTypeParm
2492 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2493 if (NewTypeParm->isParameterPack()) {
2494 assert(!NewTypeParm->hasDefaultArgument() &&
2495 "Parameter packs can't have a default argument!");
2496 SawParameterPack = true;
2497 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2498 NewTypeParm->hasDefaultArgument() &&
2499 (!SkipBody || !SkipBody->ShouldSkip)) {
2500 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2501 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2502 SawDefaultArgument = true;
2503
2504 if (!OldTypeParm->getOwningModule())
2505 RedundantDefaultArg = true;
2506 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2507 NewTypeParm)) {
2508 InconsistentDefaultArg = true;
2509 PrevModuleName =
2511 }
2512 PreviousDefaultArgLoc = NewDefaultLoc;
2513 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2514 // Merge the default argument from the old declaration to the
2515 // new declaration.
2516 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2517 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2518 } else if (NewTypeParm->hasDefaultArgument()) {
2519 SawDefaultArgument = true;
2520 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2521 } else if (SawDefaultArgument)
2522 MissingDefaultArg = true;
2523 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2524 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2525 // Check for unexpanded parameter packs, except in a template template
2526 // parameter pack, as in those any unexpanded packs should be expanded
2527 // along with the parameter itself.
2529 !NewNonTypeParm->isParameterPack() &&
2530 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2531 NewNonTypeParm->getTypeSourceInfo(),
2533 Invalid = true;
2534 continue;
2535 }
2536
2537 // Check the presence of a default argument here.
2538 if (NewNonTypeParm->hasDefaultArgument() &&
2540 *this, TPC, NewNonTypeParm->getLocation(),
2541 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2542 NewNonTypeParm->removeDefaultArgument();
2543 }
2544
2545 // Merge default arguments for non-type template parameters
2546 NonTypeTemplateParmDecl *OldNonTypeParm
2547 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2548 if (NewNonTypeParm->isParameterPack()) {
2549 assert(!NewNonTypeParm->hasDefaultArgument() &&
2550 "Parameter packs can't have a default argument!");
2551 if (!NewNonTypeParm->isPackExpansion())
2552 SawParameterPack = true;
2553 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2554 NewNonTypeParm->hasDefaultArgument() &&
2555 (!SkipBody || !SkipBody->ShouldSkip)) {
2556 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2557 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2558 SawDefaultArgument = true;
2559 if (!OldNonTypeParm->getOwningModule())
2560 RedundantDefaultArg = true;
2561 else if (!getASTContext().isSameDefaultTemplateArgument(
2562 OldNonTypeParm, NewNonTypeParm)) {
2563 InconsistentDefaultArg = true;
2564 PrevModuleName =
2565 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2566 }
2567 PreviousDefaultArgLoc = NewDefaultLoc;
2568 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2569 // Merge the default argument from the old declaration to the
2570 // new declaration.
2571 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2572 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2573 } else if (NewNonTypeParm->hasDefaultArgument()) {
2574 SawDefaultArgument = true;
2575 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2576 } else if (SawDefaultArgument)
2577 MissingDefaultArg = true;
2578 } else {
2579 TemplateTemplateParmDecl *NewTemplateParm
2580 = cast<TemplateTemplateParmDecl>(*NewParam);
2581
2582 // Check for unexpanded parameter packs, recursively.
2583 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2584 Invalid = true;
2585 continue;
2586 }
2587
2588 // Check the presence of a default argument here.
2589 if (NewTemplateParm->hasDefaultArgument() &&
2591 NewTemplateParm->getLocation(),
2592 NewTemplateParm->getDefaultArgument().getSourceRange()))
2593 NewTemplateParm->removeDefaultArgument();
2594
2595 // Merge default arguments for template template parameters
2596 TemplateTemplateParmDecl *OldTemplateParm
2597 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2598 if (NewTemplateParm->isParameterPack()) {
2599 assert(!NewTemplateParm->hasDefaultArgument() &&
2600 "Parameter packs can't have a default argument!");
2601 if (!NewTemplateParm->isPackExpansion())
2602 SawParameterPack = true;
2603 } else if (OldTemplateParm &&
2604 hasVisibleDefaultArgument(OldTemplateParm) &&
2605 NewTemplateParm->hasDefaultArgument() &&
2606 (!SkipBody || !SkipBody->ShouldSkip)) {
2607 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2608 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2609 SawDefaultArgument = true;
2610 if (!OldTemplateParm->getOwningModule())
2611 RedundantDefaultArg = true;
2612 else if (!getASTContext().isSameDefaultTemplateArgument(
2613 OldTemplateParm, NewTemplateParm)) {
2614 InconsistentDefaultArg = true;
2615 PrevModuleName =
2616 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2617 }
2618 PreviousDefaultArgLoc = NewDefaultLoc;
2619 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2620 // Merge the default argument from the old declaration to the
2621 // new declaration.
2622 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2623 PreviousDefaultArgLoc
2624 = OldTemplateParm->getDefaultArgument().getLocation();
2625 } else if (NewTemplateParm->hasDefaultArgument()) {
2626 SawDefaultArgument = true;
2627 PreviousDefaultArgLoc
2628 = NewTemplateParm->getDefaultArgument().getLocation();
2629 } else if (SawDefaultArgument)
2630 MissingDefaultArg = true;
2631 }
2632
2633 // C++11 [temp.param]p11:
2634 // If a template parameter of a primary class template or alias template
2635 // is a template parameter pack, it shall be the last template parameter.
2636 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2637 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2638 Diag((*NewParam)->getLocation(),
2639 diag::err_template_param_pack_must_be_last_template_parameter);
2640 Invalid = true;
2641 }
2642
2643 // [basic.def.odr]/13:
2644 // There can be more than one definition of a
2645 // ...
2646 // default template argument
2647 // ...
2648 // in a program provided that each definition appears in a different
2649 // translation unit and the definitions satisfy the [same-meaning
2650 // criteria of the ODR].
2651 //
2652 // Simply, the design of modules allows the definition of template default
2653 // argument to be repeated across translation unit. Note that the ODR is
2654 // checked elsewhere. But it is still not allowed to repeat template default
2655 // argument in the same translation unit.
2656 if (RedundantDefaultArg) {
2657 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2658 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2659 Invalid = true;
2660 } else if (InconsistentDefaultArg) {
2661 // We could only diagnose about the case that the OldParam is imported.
2662 // The case NewParam is imported should be handled in ASTReader.
2663 Diag(NewDefaultLoc,
2664 diag::err_template_param_default_arg_inconsistent_redefinition);
2665 Diag(OldDefaultLoc,
2666 diag::note_template_param_prev_default_arg_in_other_module)
2667 << PrevModuleName;
2668 Invalid = true;
2669 } else if (MissingDefaultArg &&
2670 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2671 TPC == TPC_FriendClassTemplate)) {
2672 // C++ 23[temp.param]p14:
2673 // If a template-parameter of a class template, variable template, or
2674 // alias template has a default template argument, each subsequent
2675 // template-parameter shall either have a default template argument
2676 // supplied or be a template parameter pack.
2677 Diag((*NewParam)->getLocation(),
2678 diag::err_template_param_default_arg_missing);
2679 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2680 Invalid = true;
2681 RemoveDefaultArguments = true;
2682 }
2683
2684 // If we have an old template parameter list that we're merging
2685 // in, move on to the next parameter.
2686 if (OldParams)
2687 ++OldParam;
2688 }
2689
2690 // We were missing some default arguments at the end of the list, so remove
2691 // all of the default arguments.
2692 if (RemoveDefaultArguments) {
2693 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2694 NewParamEnd = NewParams->end();
2695 NewParam != NewParamEnd; ++NewParam) {
2696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2697 TTP->removeDefaultArgument();
2698 else if (NonTypeTemplateParmDecl *NTTP
2699 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2700 NTTP->removeDefaultArgument();
2701 else
2702 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2703 }
2704 }
2705
2706 return Invalid;
2707}
2708
2709namespace {
2710
2711/// A class which looks for a use of a certain level of template
2712/// parameter.
2713struct DependencyChecker : DynamicRecursiveASTVisitor {
2714 unsigned Depth;
2715
2716 // Whether we're looking for a use of a template parameter that makes the
2717 // overall construct type-dependent / a dependent type. This is strictly
2718 // best-effort for now; we may fail to match at all for a dependent type
2719 // in some cases if this is set.
2720 bool IgnoreNonTypeDependent;
2721
2722 bool Match;
2723 SourceLocation MatchLoc;
2724
2725 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2726 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2727 Match(false) {}
2728
2729 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2730 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2731 NamedDecl *ND = Params->getParam(0);
2732 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2733 Depth = PD->getDepth();
2734 } else if (NonTypeTemplateParmDecl *PD =
2735 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2736 Depth = PD->getDepth();
2737 } else {
2738 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2739 }
2740 }
2741
2742 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2743 if (ParmDepth >= Depth) {
2744 Match = true;
2745 MatchLoc = Loc;
2746 return true;
2747 }
2748 return false;
2749 }
2750
2751 bool TraverseStmt(Stmt *S) override {
2752 // Prune out non-type-dependent expressions if requested. This can
2753 // sometimes result in us failing to find a template parameter reference
2754 // (if a value-dependent expression creates a dependent type), but this
2755 // mode is best-effort only.
2756 if (auto *E = dyn_cast_or_null<Expr>(S))
2757 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2758 return true;
2760 }
2761
2762 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2763 if (IgnoreNonTypeDependent && !TL.isNull() &&
2764 !TL.getType()->isDependentType())
2765 return true;
2766 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2767 }
2768
2769 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2770 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2771 }
2772
2773 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2774 // For a best-effort search, keep looking until we find a location.
2775 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2776 }
2777
2778 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2779 if (TemplateTemplateParmDecl *PD =
2780 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2781 if (Matches(PD->getDepth()))
2782 return false;
2784 TraverseQualifier);
2785 }
2786
2787 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2788 if (NonTypeTemplateParmDecl *PD =
2789 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2790 if (Matches(PD->getDepth(), E->getExprLoc()))
2791 return false;
2792 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2793 }
2794
2795 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2796 if (Matches(E->getParameter()->getDepth(), E->getExprLoc()))
2797 return false;
2798 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(E);
2799 }
2800
2801 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2802 return TraverseType(T->getReplacementType());
2803 }
2804
2805 bool VisitSubstTemplateTypeParmPackType(
2806 SubstTemplateTypeParmPackType *T) override {
2807 return TraverseTemplateArgument(T->getArgumentPack());
2808 }
2809
2810 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2811 bool TraverseQualifier) override {
2812 // An InjectedClassNameType will never have a dependent template name,
2813 // so no need to traverse it.
2814 return TraverseTemplateArguments(
2815 T->getTemplateArgs(T->getDecl()->getASTContext()));
2816 }
2817};
2818} // end anonymous namespace
2819
2820/// Determines whether a given type depends on the given parameter
2821/// list.
2822static bool
2824 if (!Params->size())
2825 return false;
2826
2827 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2828 Checker.TraverseType(T);
2829 return Checker.Match;
2830}
2831
2832// Find the source range corresponding to the named type in the given
2833// nested-name-specifier, if any.
2835 QualType T,
2836 const CXXScopeSpec &SS) {
2838 for (;;) {
2841 break;
2842 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2843 return NNSLoc.castAsTypeLoc().getSourceRange();
2844 // FIXME: This will always be empty.
2845 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2846 }
2847
2848 return SourceRange();
2849}
2850
2852 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2853 TemplateIdAnnotation *TemplateId,
2854 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2855 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2856 IsMemberSpecialization = false;
2857 Invalid = false;
2858
2859 // The sequence of nested types to which we will match up the template
2860 // parameter lists. We first build this list by starting with the type named
2861 // by the nested-name-specifier and walking out until we run out of types.
2862 SmallVector<QualType, 4> NestedTypes;
2863 QualType T;
2864 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2865 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2866 if (CXXRecordDecl *Record =
2867 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2868 T = Context.getCanonicalTagType(Record);
2869 else
2870 T = QualType(Qualifier.getAsType(), 0);
2871 }
2872
2873 // If we found an explicit specialization that prevents us from needing
2874 // 'template<>' headers, this will be set to the location of that
2875 // explicit specialization.
2876 SourceLocation ExplicitSpecLoc;
2877
2878 while (!T.isNull()) {
2879 NestedTypes.push_back(T);
2880
2881 // Retrieve the parent of a record type.
2882 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2883 // If this type is an explicit specialization, we're done.
2885 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2887 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2888 ExplicitSpecLoc = Spec->getLocation();
2889 break;
2890 }
2891 } else if (Record->getTemplateSpecializationKind()
2893 ExplicitSpecLoc = Record->getLocation();
2894 break;
2895 }
2896
2897 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2898 T = Context.getTypeDeclType(Parent);
2899 else
2900 T = QualType();
2901 continue;
2902 }
2903
2904 if (const TemplateSpecializationType *TST
2905 = T->getAs<TemplateSpecializationType>()) {
2906 TemplateName Name = TST->getTemplateName();
2907 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2908 // Look one step prior in a dependent template specialization type.
2909 if (NestedNameSpecifier NNS = DTS->getQualifier();
2911 T = QualType(NNS.getAsType(), 0);
2912 else
2913 T = QualType();
2914 continue;
2915 }
2916 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2917 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2918 T = Context.getTypeDeclType(Parent);
2919 else
2920 T = QualType();
2921 continue;
2922 }
2923 }
2924
2925 // Look one step prior in a dependent name type.
2926 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2927 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2929 T = QualType(NNS.getAsType(), 0);
2930 else
2931 T = QualType();
2932 continue;
2933 }
2934
2935 // Retrieve the parent of an enumeration type.
2936 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2937 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2938 // check here.
2939 EnumDecl *Enum = EnumT->getDecl();
2940
2941 // Get to the parent type.
2942 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2943 T = Context.getCanonicalTypeDeclType(Parent);
2944 else
2945 T = QualType();
2946 continue;
2947 }
2948
2949 T = QualType();
2950 }
2951 // Reverse the nested types list, since we want to traverse from the outermost
2952 // to the innermost while checking template-parameter-lists.
2953 std::reverse(NestedTypes.begin(), NestedTypes.end());
2954
2955 // C++0x [temp.expl.spec]p17:
2956 // A member or a member template may be nested within many
2957 // enclosing class templates. In an explicit specialization for
2958 // such a member, the member declaration shall be preceded by a
2959 // template<> for each enclosing class template that is
2960 // explicitly specialized.
2961 bool SawNonEmptyTemplateParameterList = false;
2962
2963 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2964 if (SawNonEmptyTemplateParameterList) {
2965 if (!SuppressDiagnostic)
2966 Diag(DeclLoc, diag::err_specialize_member_of_template)
2967 << !Recovery << Range;
2968 Invalid = true;
2969 IsMemberSpecialization = false;
2970 return true;
2971 }
2972
2973 return false;
2974 };
2975
2976 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2977 // Check that we can have an explicit specialization here.
2978 if (CheckExplicitSpecialization(Range, true))
2979 return true;
2980
2981 // We don't have a template header, but we should.
2982 SourceLocation ExpectedTemplateLoc;
2983 if (!ParamLists.empty())
2984 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2985 else
2986 ExpectedTemplateLoc = DeclStartLoc;
2987
2988 if (!SuppressDiagnostic)
2989 Diag(DeclLoc, diag::err_template_spec_needs_header)
2990 << Range
2991 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2992 return false;
2993 };
2994
2995 unsigned ParamIdx = 0;
2996 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2997 ++TypeIdx) {
2998 T = NestedTypes[TypeIdx];
2999
3000 // Whether we expect a 'template<>' header.
3001 bool NeedEmptyTemplateHeader = false;
3002
3003 // Whether we expect a template header with parameters.
3004 bool NeedNonemptyTemplateHeader = false;
3005
3006 // For a dependent type, the set of template parameters that we
3007 // expect to see.
3008 TemplateParameterList *ExpectedTemplateParams = nullptr;
3009
3010 // C++0x [temp.expl.spec]p15:
3011 // A member or a member template may be nested within many enclosing
3012 // class templates. In an explicit specialization for such a member, the
3013 // member declaration shall be preceded by a template<> for each
3014 // enclosing class template that is explicitly specialized.
3015 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3017 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3018 ExpectedTemplateParams = Partial->getTemplateParameters();
3019 NeedNonemptyTemplateHeader = true;
3020 } else if (Record->isDependentType()) {
3021 if (Record->getDescribedClassTemplate()) {
3022 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3023 ->getTemplateParameters();
3024 NeedNonemptyTemplateHeader = true;
3025 }
3026 } else if (ClassTemplateSpecializationDecl *Spec
3027 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3028 // C++0x [temp.expl.spec]p4:
3029 // Members of an explicitly specialized class template are defined
3030 // in the same manner as members of normal classes, and not using
3031 // the template<> syntax.
3032 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3033 NeedEmptyTemplateHeader = true;
3034 else
3035 continue;
3036 } else if (Record->getTemplateSpecializationKind()) {
3037 if (Record->getTemplateSpecializationKind()
3039 TypeIdx == NumTypes - 1)
3040 IsMemberSpecialization = true;
3041
3042 continue;
3043 }
3044 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3045 TemplateName Name = TST->getTemplateName();
3046 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3047 ExpectedTemplateParams = Template->getTemplateParameters();
3048 NeedNonemptyTemplateHeader = true;
3049 } else if (Name.getAsDependentTemplateName()) {
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDeducedTemplateName()) {
3052 // FIXME: We actually could/should check the template arguments here
3053 // against the corresponding template parameter list.
3054 NeedNonemptyTemplateHeader = false;
3055 }
3056 }
3057
3058 // C++ [temp.expl.spec]p16:
3059 // In an explicit specialization declaration for a member of a class
3060 // template or a member template that appears in namespace scope, the
3061 // member template and some of its enclosing class templates may remain
3062 // unspecialized, except that the declaration shall not explicitly
3063 // specialize a class member template if its enclosing class templates
3064 // are not explicitly specialized as well.
3065 if (ParamIdx < ParamLists.size()) {
3066 if (ParamLists[ParamIdx]->size() == 0) {
3067 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3068 false))
3069 return nullptr;
3070 } else
3071 SawNonEmptyTemplateParameterList = true;
3072 }
3073
3074 if (NeedEmptyTemplateHeader) {
3075 // If we're on the last of the types, and we need a 'template<>' header
3076 // here, then it's a member specialization.
3077 if (TypeIdx == NumTypes - 1)
3078 IsMemberSpecialization = true;
3079
3080 if (ParamIdx < ParamLists.size()) {
3081 if (ParamLists[ParamIdx]->size() > 0) {
3082 // The header has template parameters when it shouldn't. Complain.
3083 if (!SuppressDiagnostic)
3084 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3085 diag::err_template_param_list_matches_nontemplate)
3086 << T
3087 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3088 ParamLists[ParamIdx]->getRAngleLoc())
3090 Invalid = true;
3091 return nullptr;
3092 }
3093
3094 // Consume this template header.
3095 ++ParamIdx;
3096 continue;
3097 }
3098
3099 if (!IsFriend)
3100 if (DiagnoseMissingExplicitSpecialization(
3102 return nullptr;
3103
3104 continue;
3105 }
3106
3107 if (NeedNonemptyTemplateHeader) {
3108 // In friend declarations we can have template-ids which don't
3109 // depend on the corresponding template parameter lists. But
3110 // assume that empty parameter lists are supposed to match this
3111 // template-id.
3112 if (IsFriend && T->isDependentType()) {
3113 if (ParamIdx < ParamLists.size() &&
3115 ExpectedTemplateParams = nullptr;
3116 else
3117 continue;
3118 }
3119
3120 if (ParamIdx < ParamLists.size()) {
3121 // Check the template parameter list, if we can.
3122 if (ExpectedTemplateParams &&
3124 ExpectedTemplateParams,
3125 !SuppressDiagnostic, TPL_TemplateMatch))
3126 Invalid = true;
3127
3128 if (!Invalid &&
3129 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3131 Invalid = true;
3132
3133 ++ParamIdx;
3134 continue;
3135 }
3136
3137 if (!SuppressDiagnostic)
3138 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3139 << T
3141 Invalid = true;
3142 continue;
3143 }
3144 }
3145
3146 // If there were at least as many template-ids as there were template
3147 // parameter lists, then there are no template parameter lists remaining for
3148 // the declaration itself.
3149 if (ParamIdx >= ParamLists.size()) {
3150 if (TemplateId && !IsFriend) {
3151 // We don't have a template header for the declaration itself, but we
3152 // should.
3153 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3154 TemplateId->RAngleLoc));
3155
3156 // Fabricate an empty template parameter list for the invented header.
3158 SourceLocation(), {},
3159 SourceLocation(), nullptr);
3160 }
3161
3162 return nullptr;
3163 }
3164
3165 // If there were too many template parameter lists, complain about that now.
3166 if (ParamIdx < ParamLists.size() - 1) {
3167 bool HasAnyExplicitSpecHeader = false;
3168 bool AllExplicitSpecHeaders = true;
3169 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3170 if (ParamLists[I]->size() == 0)
3171 HasAnyExplicitSpecHeader = true;
3172 else
3173 AllExplicitSpecHeaders = false;
3174 }
3175
3176 if (!SuppressDiagnostic)
3177 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3178 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3179 : diag::err_template_spec_extra_headers)
3180 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3181 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3182
3183 // If there was a specialization somewhere, such that 'template<>' is
3184 // not required, and there were any 'template<>' headers, note where the
3185 // specialization occurred.
3186 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3187 !SuppressDiagnostic)
3188 Diag(ExplicitSpecLoc,
3189 diag::note_explicit_template_spec_does_not_need_header)
3190 << NestedTypes.back();
3191
3192 // We have a template parameter list with no corresponding scope, which
3193 // means that the resulting template declaration can't be instantiated
3194 // properly (we'll end up with dependent nodes when we shouldn't).
3195 if (!AllExplicitSpecHeaders)
3196 Invalid = true;
3197 }
3198
3199 // C++ [temp.expl.spec]p16:
3200 // In an explicit specialization declaration for a member of a class
3201 // template or a member template that ap- pears in namespace scope, the
3202 // member template and some of its enclosing class templates may remain
3203 // unspecialized, except that the declaration shall not explicitly
3204 // specialize a class member template if its en- closing class templates
3205 // are not explicitly specialized as well.
3206 if (ParamLists.back()->size() == 0 &&
3207 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3208 false))
3209 return nullptr;
3210
3211 // Return the last template parameter list, which corresponds to the
3212 // entity being declared.
3213 return ParamLists.back();
3214}
3215
3217 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3218 Diag(Template->getLocation(), diag::note_template_declared_here)
3220 ? 0
3222 ? 1
3224 ? 2
3226 << Template->getDeclName();
3227 return;
3228 }
3229
3231 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3232 IEnd = OST->end();
3233 I != IEnd; ++I)
3234 Diag((*I)->getLocation(), diag::note_template_declared_here)
3235 << 0 << (*I)->getDeclName();
3236
3237 return;
3238 }
3239}
3240
3242 TemplateName BaseTemplate,
3243 SourceLocation TemplateLoc,
3245 auto lookUpCommonType = [&](TemplateArgument T1,
3246 TemplateArgument T2) -> QualType {
3247 // Don't bother looking for other specializations if both types are
3248 // builtins - users aren't allowed to specialize for them
3249 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3250 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3251 {T1, T2});
3252
3256 Args.addArgument(TemplateArgumentLoc(
3257 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3258
3259 EnterExpressionEvaluationContext UnevaluatedContext(
3261 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3263
3264 QualType BaseTemplateInst = S.CheckTemplateIdType(
3265 Keyword, BaseTemplate, TemplateLoc, Args,
3266 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3267
3268 if (SFINAE.hasErrorOccurred())
3269 return QualType();
3270
3271 return BaseTemplateInst;
3272 };
3273
3274 // Note A: For the common_type trait applied to a template parameter pack T of
3275 // types, the member type shall be either defined or not present as follows:
3276 switch (Ts.size()) {
3277
3278 // If sizeof...(T) is zero, there shall be no member type.
3279 case 0:
3280 return QualType();
3281
3282 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3283 // pack T. The member typedef-name type shall denote the same type, if any, as
3284 // common_type_t<T0, T0>; otherwise there shall be no member type.
3285 case 1:
3286 return lookUpCommonType(Ts[0], Ts[0]);
3287
3288 // If sizeof...(T) is two, let the first and second types constituting T be
3289 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3290 // as decay_t<T1> and decay_t<T2>, respectively.
3291 case 2: {
3292 QualType T1 = Ts[0].getAsType();
3293 QualType T2 = Ts[1].getAsType();
3294 QualType D1 = S.BuiltinDecay(T1, {});
3295 QualType D2 = S.BuiltinDecay(T2, {});
3296
3297 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3298 // the same type, if any, as common_type_t<D1, D2>.
3299 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3300 return lookUpCommonType(D1, D2);
3301
3302 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3303 // denotes a valid type, let C denote that type.
3304 {
3305 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3306 EnterExpressionEvaluationContext UnevaluatedContext(
3308 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3310
3311 // false
3313 VK_PRValue);
3314 ExprResult Cond = &CondExpr;
3315
3316 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3317 if (ConstRefQual) {
3318 D1.addConst();
3319 D2.addConst();
3320 }
3321
3322 // declval<D1>()
3323 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3324 ExprResult LHS = &LHSExpr;
3325
3326 // declval<D2>()
3327 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3328 ExprResult RHS = &RHSExpr;
3329
3332
3333 // decltype(false ? declval<D1>() : declval<D2>())
3335 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3336
3337 if (Result.isNull() || SFINAE.hasErrorOccurred())
3338 return QualType();
3339
3340 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3341 return S.BuiltinDecay(Result, TemplateLoc);
3342 };
3343
3344 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3345 return Res;
3346
3347 // Let:
3348 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3349 // COND-RES(X, Y) be
3350 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3351
3352 // C++20 only
3353 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3354 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3355 if (!S.Context.getLangOpts().CPlusPlus20)
3356 return QualType();
3357 return CheckConditionalOperands(true);
3358 }
3359 }
3360
3361 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3362 // denote the first, second, and (pack of) remaining types constituting T. Let
3363 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3364 // a type C, the member typedef-name type shall denote the same type, if any,
3365 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3366 default: {
3367 QualType Result = Ts.front().getAsType();
3368 for (auto T : llvm::drop_begin(Ts)) {
3369 Result = lookUpCommonType(Result, T.getAsType());
3370 if (Result.isNull())
3371 return QualType();
3372 }
3373 return Result;
3374 }
3375 }
3376}
3377
3378static bool isInVkNamespace(const RecordType *RT) {
3379 DeclContext *DC = RT->getDecl()->getDeclContext();
3380 if (!DC)
3381 return false;
3382
3383 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3384 if (!ND)
3385 return false;
3386
3387 return ND->getQualifiedNameAsString() == "hlsl::vk";
3388}
3389
3390static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3391 QualType OperandArg,
3392 SourceLocation Loc) {
3393 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3394 bool Literal = false;
3395 SourceLocation LiteralLoc;
3396 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3397 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3398 assert(SpecDecl);
3399
3400 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3401 QualType ConstantType = LiteralArgs[0].getAsType();
3402 RT = ConstantType->getAsCanonical<RecordType>();
3403 Literal = true;
3404 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3405 }
3406
3407 if (RT && isInVkNamespace(RT) &&
3408 RT->getDecl()->getName() == "integral_constant") {
3409 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3410 assert(SpecDecl);
3411
3412 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3413
3414 QualType ConstantType = ConstantArgs[0].getAsType();
3415 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3416
3417 if (Literal)
3418 return SpirvOperand::createLiteral(Value);
3419 return SpirvOperand::createConstant(ConstantType, Value);
3420 } else if (Literal) {
3421 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3422 return SpirvOperand();
3423 }
3424 }
3425 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3426 diag::err_call_incomplete_argument))
3427 return SpirvOperand();
3428 return SpirvOperand::createType(OperandArg);
3429}
3430
3433 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3434 TemplateArgumentListInfo &TemplateArgs) {
3435 ASTContext &Context = SemaRef.getASTContext();
3436
3437 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3438 "Builtin template arguments do not match its parameters");
3439
3440 switch (BTD->getBuiltinTemplateKind()) {
3441 case BTK__make_integer_seq: {
3442 // Specializations of __make_integer_seq<S, T, N> are treated like
3443 // S<T, 0, ..., N-1>.
3444
3445 QualType OrigType = Converted[1].getAsType();
3446 // C++14 [inteseq.intseq]p1:
3447 // T shall be an integer type.
3448 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3449 SemaRef.Diag(TemplateArgs[1].getLocation(),
3450 diag::err_integer_sequence_integral_element_type);
3451 return QualType();
3452 }
3453
3454 TemplateArgument NumArgsArg = Converted[2];
3455 if (NumArgsArg.isDependent())
3456 return QualType();
3457
3458 TemplateArgumentListInfo SyntheticTemplateArgs;
3459 // The type argument, wrapped in substitution sugar, gets reused as the
3460 // first template argument in the synthetic template argument list.
3461 SyntheticTemplateArgs.addArgument(
3464 OrigType, TemplateArgs[1].getLocation())));
3465
3466 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3467 // Expand N into 0 ... N-1.
3468 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3469 I < NumArgs; ++I) {
3470 TemplateArgument TA(Context, I, OrigType);
3471 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3472 TA, OrigType, TemplateArgs[2].getLocation()));
3473 }
3474 } else {
3475 // C++14 [inteseq.make]p1:
3476 // If N is negative the program is ill-formed.
3477 SemaRef.Diag(TemplateArgs[2].getLocation(),
3478 diag::err_integer_sequence_negative_length);
3479 return QualType();
3480 }
3481
3482 // The first template argument will be reused as the template decl that
3483 // our synthetic template arguments will be applied to.
3484 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3485 TemplateLoc, SyntheticTemplateArgs,
3486 /*Scope=*/nullptr,
3487 /*ForNestedNameSpecifier=*/false);
3488 }
3489
3490 case BTK__type_pack_element: {
3491 // Specializations of
3492 // __type_pack_element<Index, T_1, ..., T_N>
3493 // are treated like T_Index.
3494 assert(Converted.size() == 2 &&
3495 "__type_pack_element should be given an index and a parameter pack");
3496
3497 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3498 if (IndexArg.isDependent() || Ts.isDependent())
3499 return QualType();
3500
3501 llvm::APSInt Index = IndexArg.getAsIntegral();
3502 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3503 "type std::size_t, and hence be non-negative");
3504 // If the Index is out of bounds, the program is ill-formed.
3505 if (Index >= Ts.pack_size()) {
3506 SemaRef.Diag(TemplateArgs[0].getLocation(),
3507 diag::err_type_pack_element_out_of_bounds);
3508 return QualType();
3509 }
3510
3511 // We simply return the type at index `Index`.
3512 int64_t N = Index.getExtValue();
3513 return Ts.getPackAsArray()[N].getAsType();
3514 }
3515
3516 case BTK__builtin_common_type: {
3517 assert(Converted.size() == 4);
3518 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3519 return QualType();
3520
3521 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3522 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3523 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3524 TemplateLoc, Ts);
3525 !CT.isNull()) {
3529 CT, TemplateArgs[1].getLocation())));
3530 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3531 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3532 TAs, /*Scope=*/nullptr,
3533 /*ForNestedNameSpecifier=*/false);
3534 }
3535 QualType HasNoTypeMember = Converted[2].getAsType();
3536 return HasNoTypeMember;
3537 }
3538
3539 case BTK__hlsl_spirv_type: {
3540 assert(Converted.size() == 4);
3541
3542 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3543 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3544 }
3545
3546 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3547 return QualType();
3548
3549 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3550 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3551 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3552
3553 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3554
3556
3557 for (auto &OperandTA : OperandArgs) {
3558 QualType OperandArg = OperandTA.getAsType();
3559 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3560 TemplateArgs[3].getLocation());
3561 if (!Operand.isValid())
3562 return QualType();
3563 Operands.push_back(Operand);
3564 }
3565
3566 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3567 }
3568 case BTK__builtin_dedup_pack: {
3569 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3570 "a parameter pack");
3571 TemplateArgument Ts = Converted[0];
3572 // Delay the computation until we can compute the final result. We choose
3573 // not to remove the duplicates upfront before substitution to keep the code
3574 // simple.
3575 if (Ts.isDependent())
3576 return QualType();
3577 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3579 llvm::SmallDenseSet<QualType> Seen;
3580 // Synthesize a new template argument list, removing duplicates.
3581 for (auto T : Ts.getPackAsArray()) {
3582 assert(T.getKind() == clang::TemplateArgument::Type);
3583 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3584 continue;
3585 OutArgs.push_back(T);
3586 }
3587 return Context.getSubstBuiltinTemplatePack(
3588 TemplateArgument::CreatePackCopy(Context, OutArgs));
3589 }
3590 }
3591 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3592}
3593
3594/// Determine whether this alias template is "enable_if_t".
3595/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3597 return AliasTemplate->getName() == "enable_if_t" ||
3598 AliasTemplate->getName() == "__enable_if_t";
3599}
3600
3601/// Collect all of the separable terms in the given condition, which
3602/// might be a conjunction.
3603///
3604/// FIXME: The right answer is to convert the logical expression into
3605/// disjunctive normal form, so we can find the first failed term
3606/// within each possible clause.
3607static void collectConjunctionTerms(Expr *Clause,
3608 SmallVectorImpl<Expr *> &Terms) {
3609 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3610 if (BinOp->getOpcode() == BO_LAnd) {
3611 collectConjunctionTerms(BinOp->getLHS(), Terms);
3612 collectConjunctionTerms(BinOp->getRHS(), Terms);
3613 return;
3614 }
3615 }
3616
3617 Terms.push_back(Clause);
3618}
3619
3620// The ranges-v3 library uses an odd pattern of a top-level "||" with
3621// a left-hand side that is value-dependent but never true. Identify
3622// the idiom and ignore that term.
3624 // Top-level '||'.
3625 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3626 if (!BinOp) return Cond;
3627
3628 if (BinOp->getOpcode() != BO_LOr) return Cond;
3629
3630 // With an inner '==' that has a literal on the right-hand side.
3631 Expr *LHS = BinOp->getLHS();
3632 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3633 if (!InnerBinOp) return Cond;
3634
3635 if (InnerBinOp->getOpcode() != BO_EQ ||
3636 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3637 return Cond;
3638
3639 // If the inner binary operation came from a macro expansion named
3640 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3641 // of the '||', which is the real, user-provided condition.
3642 SourceLocation Loc = InnerBinOp->getExprLoc();
3643 if (!Loc.isMacroID()) return Cond;
3644
3645 StringRef MacroName = PP.getImmediateMacroName(Loc);
3646 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3647 return BinOp->getRHS();
3648
3649 return Cond;
3650}
3651
3652namespace {
3653
3654// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3655// within failing boolean expression, such as substituting template parameters
3656// for actual types.
3657class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3658public:
3659 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3660 : Policy(P) {}
3661
3662 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3663 const auto *DR = dyn_cast<DeclRefExpr>(E);
3664 if (DR && DR->getQualifier()) {
3665 // If this is a qualified name, expand the template arguments in nested
3666 // qualifiers.
3667 DR->getQualifier().print(OS, Policy, true);
3668 // Then print the decl itself.
3669 const ValueDecl *VD = DR->getDecl();
3670 OS << *VD;
3671 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3672 // This is a template variable, print the expanded template arguments.
3673 printTemplateArgumentList(
3674 OS, IV->getTemplateArgs().asArray(), Policy,
3675 IV->getSpecializedTemplate()->getTemplateParameters());
3676 }
3677 return true;
3678 }
3679 return false;
3680 }
3681
3682private:
3683 const PrintingPolicy Policy;
3684};
3685
3686} // end anonymous namespace
3687
3688std::pair<Expr *, std::string>
3690 Cond = lookThroughRangesV3Condition(PP, Cond);
3691
3692 // Separate out all of the terms in a conjunction.
3694 collectConjunctionTerms(Cond, Terms);
3695
3696 // Determine which term failed.
3697 Expr *FailedCond = nullptr;
3698 for (Expr *Term : Terms) {
3699 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3700
3701 // Literals are uninteresting.
3702 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3703 isa<IntegerLiteral>(TermAsWritten))
3704 continue;
3705
3706 // The initialization of the parameter from the argument is
3707 // a constant-evaluated context.
3710
3711 bool Succeeded;
3712 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3713 !Succeeded) {
3714 FailedCond = TermAsWritten;
3715 break;
3716 }
3717 }
3718 if (!FailedCond)
3719 FailedCond = Cond->IgnoreParenImpCasts();
3720
3721 std::string Description;
3722 {
3723 llvm::raw_string_ostream Out(Description);
3725 Policy.PrintAsCanonical = true;
3726 FailedBooleanConditionPrinterHelper Helper(Policy);
3727 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3728 }
3729 return { FailedCond, Description };
3730}
3731
3732static TemplateName
3734 const AssumedTemplateStorage *ATN,
3735 SourceLocation NameLoc) {
3736 // We assumed this undeclared identifier to be an (ADL-only) function
3737 // template name, but it was used in a context where a type was required.
3738 // Try to typo-correct it now.
3739 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3740 struct CandidateCallback : CorrectionCandidateCallback {
3741 bool ValidateCandidate(const TypoCorrection &TC) override {
3742 return TC.getCorrectionDecl() &&
3744 }
3745 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3746 return std::make_unique<CandidateCallback>(*this);
3747 }
3748 } FilterCCC;
3749
3750 TypoCorrection Corrected =
3751 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3752 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3753 if (Corrected && Corrected.getFoundDecl()) {
3754 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3755 << ATN->getDeclName());
3757 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3759 }
3760
3761 return TemplateName();
3762}
3763
3765 TemplateName Name,
3766 SourceLocation TemplateLoc,
3767 TemplateArgumentListInfo &TemplateArgs,
3768 Scope *Scope, bool ForNestedNameSpecifier) {
3769 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3770
3771 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3772 if (!Template) {
3773 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3774 Template = S->getParameterPack();
3775 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3776 Template = PI->getParameterPack();
3777 if (!Template)
3778 Template = PI->getPattern().getAsTemplateDecl();
3779 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3780 if (DTN->getName().getIdentifier())
3781 // When building a template-id where the template-name is dependent,
3782 // assume the template is a type template. Either our assumption is
3783 // correct, or the code is ill-formed and will be diagnosed when the
3784 // dependent name is substituted.
3785 return Context.getTemplateSpecializationType(Keyword, Name,
3786 TemplateArgs.arguments(),
3787 /*CanonicalArgs=*/{});
3788 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3790 *this, Scope, ATN, TemplateLoc);
3791 CorrectedName.isNull()) {
3792 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3793 return QualType();
3794 } else {
3795 Name = CorrectedName;
3796 Template = Name.getAsTemplateDecl();
3797 }
3798 }
3799 }
3800 if (!Template ||
3802 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3803 if (ForNestedNameSpecifier)
3804 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3805 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3806 else
3807 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3809 return QualType();
3810 }
3811
3812 // Check that the template argument list is well-formed for this
3813 // template.
3815 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3816 DefaultArgs, /*PartialTemplateArgs=*/false,
3817 CTAI,
3818 /*UpdateArgsWithConversions=*/true))
3819 return QualType();
3820
3821 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3822 // and there are no diagnsotics currently implemented for TemplateDecls,
3823 // so avoid doing it for now.
3824 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3825
3826 QualType CanonType;
3827
3829 // We might have a substituted template template parameter pack. If so,
3830 // build a template specialization type for it.
3832 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3833
3834 // C++0x [dcl.type.elab]p2:
3835 // If the identifier resolves to a typedef-name or the simple-template-id
3836 // resolves to an alias template specialization, the
3837 // elaborated-type-specifier is ill-formed.
3840 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3843 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3844 }
3845
3846 // Find the canonical type for this type alias template specialization.
3847 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3848
3849 // Diagnose uses of the pattern of this template.
3850 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3851 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3852
3853 if (Pattern->isInvalidDecl())
3854 return QualType();
3855
3856 // Only substitute for the innermost template argument list.
3857 MultiLevelTemplateArgumentList TemplateArgLists;
3859 /*Final=*/true);
3860 TemplateArgLists.addOuterRetainedLevels(
3861 AliasTemplate->getTemplateParameters()->getDepth());
3862
3864
3865 // FIXME: The TemplateArgs passed here are not used for the context note,
3866 // nor they should, because this note will be pointing to the specialization
3867 // anyway. These arguments are needed for a hack for instantiating lambdas
3868 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3869 // arguments will be used for collating the template arguments needed to
3870 // instantiate the lambda.
3871 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3872 /*Entity=*/AliasTemplate,
3873 /*TemplateArgs=*/CTAI.SugaredConverted);
3874 if (Inst.isInvalid())
3875 return QualType();
3876
3877 std::optional<ContextRAII> SavedContext;
3878 if (!AliasTemplate->getDeclContext()->isFileContext())
3879 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3880
3881 CanonType =
3882 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3883 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3884 if (CanonType.isNull()) {
3885 // If this was enable_if and we failed to find the nested type
3886 // within enable_if in a SFINAE context, dig out the specific
3887 // enable_if condition that failed and present that instead.
3889 if (SFINAETrap *Trap = getSFINAEContext();
3890 TemplateDeductionInfo *DeductionInfo =
3891 Trap ? Trap->getDeductionInfo() : nullptr) {
3892 if (DeductionInfo->hasSFINAEDiagnostic() &&
3893 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3894 diag::err_typename_nested_not_found_enable_if &&
3895 TemplateArgs[0].getArgument().getKind() ==
3897 Expr *FailedCond;
3898 std::string FailedDescription;
3899 std::tie(FailedCond, FailedDescription) =
3900 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3901
3902 // Remove the old SFINAE diagnostic.
3903 PartialDiagnosticAt OldDiag =
3905 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3906
3907 // Add a new SFINAE diagnostic specifying which condition
3908 // failed.
3909 DeductionInfo->addSFINAEDiagnostic(
3910 OldDiag.first,
3911 PDiag(diag::err_typename_nested_not_found_requirement)
3912 << FailedDescription << FailedCond->getSourceRange());
3913 }
3914 }
3915 }
3916
3917 return QualType();
3918 }
3919 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3920 CanonType = checkBuiltinTemplateIdType(
3921 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3922 } else if (Name.isDependent() ||
3923 TemplateSpecializationType::anyDependentTemplateArguments(
3924 TemplateArgs, CTAI.CanonicalConverted)) {
3925 // This class template specialization is a dependent
3926 // type. Therefore, its canonical type is another class template
3927 // specialization type that contains all of the converted
3928 // arguments in canonical form. This ensures that, e.g., A<T> and
3929 // A<T, T> have identical types when A is declared as:
3930 //
3931 // template<typename T, typename U = T> struct A;
3932 CanonType = Context.getCanonicalTemplateSpecializationType(
3934 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3935 CTAI.CanonicalConverted);
3936 assert(CanonType->isCanonicalUnqualified());
3937
3938 // This might work out to be a current instantiation, in which
3939 // case the canonical type needs to be the InjectedClassNameType.
3940 //
3941 // TODO: in theory this could be a simple hashtable lookup; most
3942 // changes to CurContext don't change the set of current
3943 // instantiations.
3945 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3946 // If we get out to a namespace, we're done.
3947 if (Ctx->isFileContext()) break;
3948
3949 // If this isn't a record, keep looking.
3950 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3951 if (!Record) continue;
3952
3953 // Look for one of the two cases with InjectedClassNameTypes
3954 // and check whether it's the same template.
3956 !Record->getDescribedClassTemplate())
3957 continue;
3958
3959 // Fetch the injected class name type and check whether its
3960 // injected type is equal to the type we just built.
3961 CanQualType ICNT = Context.getCanonicalTagType(Record);
3962 CanQualType Injected =
3963 Record->getCanonicalTemplateSpecializationType(Context);
3964
3965 if (CanonType != Injected)
3966 continue;
3967
3968 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3969 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3970
3971 // If so, the canonical type of this TST is the injected
3972 // class name type of the record we just found.
3973 CanonType = ICNT;
3974 break;
3975 }
3976 }
3977 } else if (ClassTemplateDecl *ClassTemplate =
3978 dyn_cast<ClassTemplateDecl>(Template)) {
3979 // Find the class template specialization declaration that
3980 // corresponds to these arguments.
3981 llvm::FoldingSetInsertToken InsertToken;
3983 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
3984 if (!Decl) {
3985 // This is the first time we have referenced this class template
3986 // specialization. Create the canonical declaration and add it to
3987 // the set of specializations.
3989 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3990 ClassTemplate->getDeclContext(),
3991 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3992 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3993 CTAI.StrictPackMatch, nullptr);
3994 ClassTemplate->AddSpecialization(Decl, InsertToken);
3995 if (ClassTemplate->isOutOfLine())
3996 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3997 }
3998
3999 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4000 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4001 NonSFINAEContext _(*this);
4002 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4003 if (!Inst.isInvalid()) {
4005 CTAI.CanonicalConverted,
4006 /*Final=*/false);
4007 InstantiateAttrsForDecl(TemplateArgLists,
4008 ClassTemplate->getTemplatedDecl(), Decl);
4009 }
4010 }
4011
4012 // Diagnose uses of this specialization.
4013 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4014 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4015
4016 CanonType = Context.getCanonicalTagType(Decl);
4017 assert(isa<RecordType>(CanonType) &&
4018 "type of non-dependent specialization is not a RecordType");
4019 } else {
4020 llvm_unreachable("Unhandled template kind");
4021 }
4022
4023 // Build the fully-sugared type for this class template
4024 // specialization, which refers back to the class template
4025 // specialization we created or found.
4026 return Context.getTemplateSpecializationType(
4027 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4028 CanonType);
4029}
4030
4032 TemplateNameKind &TNK,
4033 SourceLocation NameLoc,
4034 IdentifierInfo *&II) {
4035 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4036
4037 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4038 assert(ATN && "not an assumed template name");
4039 II = ATN->getDeclName().getAsIdentifierInfo();
4040
4041 if (TemplateName Name =
4042 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4043 !Name.isNull()) {
4044 // Resolved to a type template name.
4045 ParsedName = TemplateTy::make(Name);
4046 TNK = TNK_Type_template;
4047 }
4048}
4049
4051 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4052 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4053 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4054 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4055 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4056 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4057 ImplicitTypenameContext AllowImplicitTypename) {
4058 if (SS.isInvalid())
4059 return true;
4060
4061 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4062 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4063
4064 // C++ [temp.res]p3:
4065 // A qualified-id that refers to a type and in which the
4066 // nested-name-specifier depends on a template-parameter (14.6.2)
4067 // shall be prefixed by the keyword typename to indicate that the
4068 // qualified-id denotes a type, forming an
4069 // elaborated-type-specifier (7.1.5.3).
4070 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4071 // C++2a relaxes some of those restrictions in [temp.res]p5.
4072 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4073 SS.getScopeRep(), TemplateII);
4075 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4076 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4077 << NNS;
4078 if (!getLangOpts().CPlusPlus20)
4079 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4080 } else
4081 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4082
4083 // FIXME: This is not quite correct recovery as we don't transform SS
4084 // into the corresponding dependent form (and we don't diagnose missing
4085 // 'template' keywords within SS as a result).
4086 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4087 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4088 TemplateArgsIn, RAngleLoc);
4089 }
4090
4091 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4092 // it's not actually allowed to be used as a type in most cases. Because
4093 // we annotate it before we know whether it's valid, we have to check for
4094 // this case here.
4095 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4096 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4097 Diag(TemplateIILoc,
4098 TemplateKWLoc.isInvalid()
4099 ? diag::err_out_of_line_qualified_id_type_names_constructor
4100 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4101 << TemplateII << 0 /*injected-class-name used as template name*/
4102 << 1 /*if any keyword was present, it was 'template'*/;
4103 }
4104 }
4105
4106 // Translate the parser's template argument list in our AST format.
4107 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4108 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4109
4111 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4112 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4113 if (SpecTy.isNull())
4114 return true;
4115
4116 // Build type-source information.
4117 TypeLocBuilder TLB;
4118 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4119 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4120 TemplateIILoc, TemplateArgs);
4121 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4122}
4123
4125 TypeSpecifierType TagSpec,
4126 SourceLocation TagLoc,
4127 CXXScopeSpec &SS,
4128 SourceLocation TemplateKWLoc,
4129 TemplateTy TemplateD,
4130 SourceLocation TemplateLoc,
4131 SourceLocation LAngleLoc,
4132 ASTTemplateArgsPtr TemplateArgsIn,
4133 SourceLocation RAngleLoc) {
4134 if (SS.isInvalid())
4135 return TypeResult(true);
4136
4137 // Translate the parser's template argument list in our AST format.
4138 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4139 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4140
4141 // Determine the tag kind
4145
4147 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4149 if (Result.isNull())
4150 return TypeResult(true);
4151
4152 // Check the tag kind
4153 if (const RecordType *RT = Result->getAs<RecordType>()) {
4154 RecordDecl *D = RT->getDecl();
4155
4156 IdentifierInfo *Id = D->getIdentifier();
4157 assert(Id && "templated class must have an identifier");
4158
4160 TagLoc, Id)) {
4161 Diag(TagLoc, diag::err_use_with_wrong_tag)
4162 << Result
4164 Diag(D->getLocation(), diag::note_previous_use);
4165 }
4166 }
4167
4168 // Provide source-location information for the template specialization.
4169 TypeLocBuilder TLB;
4171 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4172 TemplateArgs);
4174}
4175
4176static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4177 NamedDecl *PrevDecl,
4178 SourceLocation Loc,
4180
4182
4184 unsigned Depth,
4185 unsigned Index) {
4186 switch (Arg.getKind()) {
4194 return false;
4195
4197 QualType Type = Arg.getAsType();
4198 const TemplateTypeParmType *TPT =
4199 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4200 return TPT && !Type.hasQualifiers() &&
4201 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4202 }
4203
4205 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4206 if (!DRE || !DRE->getDecl())
4207 return false;
4208 const NonTypeTemplateParmDecl *NTTP =
4209 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4210 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4211 }
4212
4214 const TemplateTemplateParmDecl *TTP =
4215 dyn_cast_or_null<TemplateTemplateParmDecl>(
4217 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4218 }
4219 llvm_unreachable("unexpected kind of template argument");
4220}
4221
4223 TemplateParameterList *SpecParams,
4225 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4226 return false;
4227
4228 unsigned Depth = Params->getDepth();
4229
4230 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4231 TemplateArgument Arg = Args[I];
4232
4233 // If the parameter is a pack expansion, the argument must be a pack
4234 // whose only element is a pack expansion.
4235 if (Params->getParam(I)->isParameterPack()) {
4236 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4237 !Arg.pack_begin()->isPackExpansion())
4238 return false;
4239 Arg = Arg.pack_begin()->getPackExpansionPattern();
4240 }
4241
4242 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4243 return false;
4244
4245 // For NTTPs further specialization is allowed via deduced types, so
4246 // we need to make sure to only reject here if primary template and
4247 // specialization use the same type for the NTTP.
4248 if (auto *SpecNTTP =
4249 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4250 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4251 if (!NTTP || NTTP->getType().getCanonicalType() !=
4252 SpecNTTP->getType().getCanonicalType())
4253 return false;
4254 }
4255 }
4256
4257 return true;
4258}
4259
4260template<typename PartialSpecDecl>
4261static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4262 if (Partial->getDeclContext()->isDependentContext())
4263 return;
4264
4265 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4266 // for non-substitution-failure issues?
4267 TemplateDeductionInfo Info(Partial->getLocation());
4268 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4269 return;
4270
4271 auto *Template = Partial->getSpecializedTemplate();
4272 S.Diag(Partial->getLocation(),
4273 diag::ext_partial_spec_not_more_specialized_than_primary)
4275
4276 if (Info.hasSFINAEDiagnostic()) {
4280 SmallString<128> SFINAEArgString;
4281 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4282 S.Diag(Diag.first,
4283 diag::note_partial_spec_not_more_specialized_than_primary)
4284 << SFINAEArgString;
4285 }
4286
4288 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4289 Template->getAssociatedConstraints(TemplateAC);
4290 Partial->getAssociatedConstraints(PartialAC);
4292 TemplateAC);
4293}
4294
4295static void
4297 const llvm::SmallBitVector &DeducibleParams) {
4298 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4299 if (!DeducibleParams[I]) {
4300 NamedDecl *Param = TemplateParams->getParam(I);
4301 if (Param->getDeclName())
4302 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4303 << Param->getDeclName();
4304 else
4305 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4306 << "(anonymous)";
4307 }
4308 }
4309}
4310
4311
4312template<typename PartialSpecDecl>
4314 PartialSpecDecl *Partial) {
4315 // C++1z [temp.class.spec]p8: (DR1495)
4316 // - The specialization shall be more specialized than the primary
4317 // template (14.5.5.2).
4319
4320 // C++ [temp.class.spec]p8: (DR1315)
4321 // - Each template-parameter shall appear at least once in the
4322 // template-id outside a non-deduced context.
4323 // C++1z [temp.class.spec.match]p3 (P0127R2)
4324 // If the template arguments of a partial specialization cannot be
4325 // deduced because of the structure of its template-parameter-list
4326 // and the template-id, the program is ill-formed.
4327 auto *TemplateParams = Partial->getTemplateParameters();
4328 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4329 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4330 TemplateParams->getDepth(), DeducibleParams);
4331
4332 if (!DeducibleParams.all()) {
4333 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4334 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4336 << (NumNonDeducible > 1)
4337 << SourceRange(Partial->getLocation(),
4338 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4339 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4340 }
4341}
4342
4347
4352
4354 // C++1z [temp.param]p11:
4355 // A template parameter of a deduction guide template that does not have a
4356 // default-argument shall be deducible from the parameter-type-list of the
4357 // deduction guide template.
4358 auto *TemplateParams = TD->getTemplateParameters();
4359 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4360 MarkDeducedTemplateParameters(TD, DeducibleParams);
4361 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4362 // A parameter pack is deducible (to an empty pack).
4363 auto *Param = TemplateParams->getParam(I);
4364 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4365 DeducibleParams[I] = true;
4366 }
4367
4368 if (!DeducibleParams.all()) {
4369 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4370 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4371 << (NumNonDeducible > 1);
4372 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4378 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4380 // D must be variable template id.
4382 "Variable template specialization is declared with a template id.");
4383
4384 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4385 TemplateArgumentListInfo TemplateArgs =
4386 makeTemplateArgumentListInfo(*this, *TemplateId);
4387 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4388 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4389 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4390
4391 TemplateName Name = TemplateId->Template.get();
4392
4393 // The template-id must name a variable template.
4395 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4396 if (!VarTemplate) {
4397 NamedDecl *FnTemplate;
4398 if (auto *OTS = Name.getAsOverloadedTemplate())
4399 FnTemplate = *OTS->begin();
4400 else
4401 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4402 if (FnTemplate)
4403 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4404 << FnTemplate->getDeclName();
4405 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4407 }
4408
4409 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4410 auto Message = DSA->getMessage();
4411 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4412 << VarTemplate << !Message.empty() << Message;
4413 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4414 }
4415
4416 // Check for unexpanded parameter packs in any of the template arguments.
4417 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4418 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4422 return true;
4423
4424 // Check that the template argument list is well-formed for this
4425 // template.
4427 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4428 /*DefaultArgs=*/{},
4429 /*PartialTemplateArgs=*/false, CTAI,
4430 /*UpdateArgsWithConversions=*/true))
4431 return true;
4432
4433 // Find the variable template (partial) specialization declaration that
4434 // corresponds to these arguments.
4437 TemplateArgs.size(),
4438 CTAI.CanonicalConverted))
4439 return true;
4440
4441 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4442 // we also do them during instantiation.
4443 if (!Name.isDependent() &&
4444 !TemplateSpecializationType::anyDependentTemplateArguments(
4445 TemplateArgs, CTAI.CanonicalConverted)) {
4446 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4447 << VarTemplate->getDeclName();
4449 }
4450
4451 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4452 TemplateParams, CTAI.CanonicalConverted) &&
4453 (!Context.getLangOpts().CPlusPlus20 ||
4454 !TemplateParams->hasAssociatedConstraints())) {
4455 // C++ [temp.class.spec]p9b3:
4456 //
4457 // -- The argument list of the specialization shall not be identical
4458 // to the implicit argument list of the primary template.
4459 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4460 << /*variable template*/ 1
4461 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4462 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4463 // FIXME: Recover from this by treating the declaration as a
4464 // redeclaration of the primary template.
4465 return true;
4466 }
4467 }
4468
4469 llvm::FoldingSetInsertToken InsertToken;
4470 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4471
4473 PrevDecl = VarTemplate->findPartialSpecialization(
4474 CTAI.CanonicalConverted, TemplateParams, InsertToken);
4475 else
4476 PrevDecl =
4477 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4478
4480
4481 // Check whether we can declare a variable template specialization in
4482 // the current scope.
4483 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4484 TemplateNameLoc,
4486 return true;
4487
4488 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4489 // Since the only prior variable template specialization with these
4490 // arguments was referenced but not declared, reuse that
4491 // declaration node as our own, updating its source location and
4492 // the list of outer template parameters to reflect our new declaration.
4493 Specialization = PrevDecl;
4494 Specialization->setLocation(TemplateNameLoc);
4495 PrevDecl = nullptr;
4496 } else if (IsPartialSpecialization) {
4497 // Create a new class template partial specialization declaration node.
4499 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4502 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4503 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4504 SC, CTAI.CanonicalConverted);
4505 Partial->setTemplateArgsAsWritten(TemplateArgs);
4506
4507 if (!PrevPartial)
4508 VarTemplate->AddPartialSpecialization(Partial, InsertToken);
4509 Specialization = Partial;
4510
4512 } else {
4513 // Create a new class template specialization declaration node for
4514 // this explicit specialization or friend declaration.
4516 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4517 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4518 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4519
4520 if (!PrevDecl)
4521 VarTemplate->AddSpecialization(Specialization, InsertToken);
4522 }
4523
4524 // C++ [temp.expl.spec]p6:
4525 // If a template, a member template or the member of a class template is
4526 // explicitly specialized then that specialization shall be declared
4527 // before the first use of that specialization that would cause an implicit
4528 // instantiation to take place, in every translation unit in which such a
4529 // use occurs; no diagnostic is required.
4530 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4531 bool Okay = false;
4532 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4533 // Is there any previous explicit specialization declaration?
4535 Okay = true;
4536 break;
4537 }
4538 }
4539
4540 if (!Okay) {
4541 SourceRange Range(TemplateNameLoc, RAngleLoc);
4542 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4543 << Name << Range;
4544
4545 Diag(PrevDecl->getPointOfInstantiation(),
4546 diag::note_instantiation_required_here)
4547 << (PrevDecl->getTemplateSpecializationKind() !=
4549 return true;
4550 }
4551 }
4552
4553 Specialization->setLexicalDeclContext(CurContext);
4554
4555 // Add the specialization into its lexical context, so that it can
4556 // be seen when iterating through the list of declarations in that
4557 // context. However, specializations are not found by name lookup.
4558 CurContext->addDecl(Specialization);
4559
4560 // Note that this is an explicit specialization.
4561 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4562
4563 Previous.clear();
4564 if (PrevDecl)
4565 Previous.addDecl(PrevDecl);
4566 else if (Specialization->isStaticDataMember() &&
4567 Specialization->isOutOfLine())
4568 Specialization->setAccess(VarTemplate->getAccess());
4569
4570 return Specialization;
4571}
4572
4573namespace {
4574/// A partial specialization whose template arguments have matched
4575/// a given template-id.
4576struct PartialSpecMatchResult {
4579};
4580
4581// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4582// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4583static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4584 if (Var->getName() != "format_kind" ||
4585 !Var->getDeclContext()->isStdNamespace())
4586 return false;
4587
4588 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4589 // release in which users can access std::format_kind.
4590 // We can use 20250520 as the final date, see the following commits.
4591 // GCC releases/gcc-15 branch:
4592 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4593 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4594 // GCC master branch:
4595 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4596 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4597 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4598}
4599} // end anonymous namespace
4600
4603 SourceLocation TemplateNameLoc,
4604 const TemplateArgumentListInfo &TemplateArgs,
4605 bool SetWrittenArgs) {
4606 assert(Template && "A variable template id without template?");
4607
4608 // Check that the template argument list is well-formed for this template.
4611 Template, TemplateNameLoc,
4612 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4613 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4614 /*UpdateArgsWithConversions=*/true))
4615 return true;
4616
4617 // Produce a placeholder value if the specialization is dependent.
4618 if (Template->getDeclContext()->isDependentContext() ||
4619 TemplateSpecializationType::anyDependentTemplateArguments(
4620 TemplateArgs, CTAI.CanonicalConverted)) {
4621 if (ParsingInitForAutoVars.empty())
4622 return DeclResult();
4623
4624 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4625 const TemplateArgument &Arg2) {
4626 return Context.isSameTemplateArgument(Arg1, Arg2);
4627 };
4628
4629 if (VarDecl *Var = Template->getTemplatedDecl();
4630 ParsingInitForAutoVars.count(Var) &&
4631 // See comments on this function definition
4632 !IsLibstdcxxStdFormatKind(PP, Var) &&
4633 llvm::equal(
4634 CTAI.CanonicalConverted,
4635 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4636 IsSameTemplateArg)) {
4637 Diag(TemplateNameLoc,
4638 diag::err_auto_variable_cannot_appear_in_own_initializer)
4639 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4640 return true;
4641 }
4642
4644 Template->getPartialSpecializations(PartialSpecs);
4645 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4646 if (ParsingInitForAutoVars.count(Partial) &&
4647 llvm::equal(CTAI.CanonicalConverted,
4648 Partial->getTemplateArgs().asArray(),
4649 IsSameTemplateArg)) {
4650 Diag(TemplateNameLoc,
4651 diag::err_auto_variable_cannot_appear_in_own_initializer)
4652 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4653 << Partial->getType();
4654 return true;
4655 }
4656
4657 return DeclResult();
4658 }
4659
4660 // Find the variable template specialization declaration that
4661 // corresponds to these arguments.
4662 llvm::FoldingSetInsertToken InsertToken;
4664 Template->findSpecialization(CTAI.CanonicalConverted, InsertToken)) {
4665 checkSpecializationReachability(TemplateNameLoc, Spec);
4666 if (Spec->getType()->isUndeducedType()) {
4667 if (ParsingInitForAutoVars.count(Spec))
4668 Diag(TemplateNameLoc,
4669 diag::err_auto_variable_cannot_appear_in_own_initializer)
4670 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4671 << Spec->getType();
4672 else
4673 // We are substituting the initializer of this variable template
4674 // specialization.
4675 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4676 << Spec << Spec->getType();
4677
4678 return true;
4679 }
4680 // If we already have a variable template specialization, return it.
4681 return Spec;
4682 }
4683
4684 // This is the first time we have referenced this variable template
4685 // specialization. Create the canonical declaration and add it to
4686 // the set of specializations, based on the closest partial specialization
4687 // that it represents. That is,
4688 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4689 const TemplateArgumentList *PartialSpecArgs = nullptr;
4690 bool AmbiguousPartialSpec = false;
4691 typedef PartialSpecMatchResult MatchResult;
4693 SourceLocation PointOfInstantiation = TemplateNameLoc;
4694 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4695 /*ForTakingAddress=*/false);
4696
4697 // 1. Attempt to find the closest partial specialization that this
4698 // specializes, if any.
4699 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4700 // Perhaps better after unification of DeduceTemplateArguments() and
4701 // getMoreSpecializedPartialSpecialization().
4703 Template->getPartialSpecializations(PartialSpecs);
4704
4705 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4706 // C++ [temp.spec.partial.member]p2:
4707 // If the primary member template is explicitly specialized for a given
4708 // (implicit) specialization of the enclosing class template, the partial
4709 // specializations of the member template are ignored for this
4710 // specialization of the enclosing class template. If a partial
4711 // specialization of the member template is explicitly specialized for a
4712 // given (implicit) specialization of the enclosing class template, the
4713 // primary member template and its other partial specializations are still
4714 // considered for this specialization of the enclosing class template.
4715 if (Template->isMemberSpecialization() &&
4716 !Partial->isMemberSpecialization())
4717 continue;
4718
4719 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4720
4722 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4724 // Store the failed-deduction information for use in diagnostics, later.
4725 // TODO: Actually use the failed-deduction info?
4726 FailedCandidates.addCandidate().set(
4729 (void)Result;
4730 } else {
4731 Matched.push_back(PartialSpecMatchResult());
4732 Matched.back().Partial = Partial;
4733 Matched.back().Args = Info.takeSugared();
4734 }
4735 }
4736
4737 if (Matched.size() >= 1) {
4738 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4739 if (Matched.size() == 1) {
4740 // -- If exactly one matching specialization is found, the
4741 // instantiation is generated from that specialization.
4742 // We don't need to do anything for this.
4743 } else {
4744 // -- If more than one matching specialization is found, the
4745 // partial order rules (14.5.4.2) are used to determine
4746 // whether one of the specializations is more specialized
4747 // than the others. If none of the specializations is more
4748 // specialized than all of the other matching
4749 // specializations, then the use of the variable template is
4750 // ambiguous and the program is ill-formed.
4751 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4752 PEnd = Matched.end();
4753 P != PEnd; ++P) {
4754 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4755 PointOfInstantiation) ==
4756 P->Partial)
4757 Best = P;
4758 }
4759
4760 // Determine if the best partial specialization is more specialized than
4761 // the others.
4762 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4763 PEnd = Matched.end();
4764 P != PEnd; ++P) {
4766 P->Partial, Best->Partial,
4767 PointOfInstantiation) != Best->Partial) {
4768 AmbiguousPartialSpec = true;
4769 break;
4770 }
4771 }
4772 }
4773
4774 // Instantiate using the best variable template partial specialization.
4775 InstantiationPattern = Best->Partial;
4776 PartialSpecArgs = Best->Args;
4777 } else {
4778 // -- If no match is found, the instantiation is generated
4779 // from the primary template.
4780 // InstantiationPattern = Template->getTemplatedDecl();
4781 }
4782
4783 // 2. Create the canonical declaration.
4784 // Note that we do not instantiate a definition until we see an odr-use
4785 // in DoMarkVarDeclReferenced().
4786 // FIXME: LateAttrs et al.?
4787 if (AmbiguousPartialSpec) {
4788 // Partial ordering did not produce a clear winner. Complain.
4789 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4790 << Template;
4791 // Print the matching partial specializations.
4792 for (MatchResult P : Matched)
4793 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4794 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4795 *P.Args);
4796 return true;
4797 }
4798
4800 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4801 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4802 if (!Decl)
4803 return true;
4804 if (SetWrittenArgs)
4805 Decl->setTemplateArgsAsWritten(TemplateArgs);
4806
4808 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4809 Decl->setInstantiationOf(D, PartialSpecArgs);
4810
4811 checkSpecializationReachability(TemplateNameLoc, Decl);
4812
4813 assert(Decl && "No variable template specialization?");
4814 return Decl;
4815}
4816
4818 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4819 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4820 const TemplateArgumentListInfo *TemplateArgs) {
4821
4822 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4823 *TemplateArgs, /*SetWrittenArgs=*/false);
4824 if (Decl.isInvalid())
4825 return ExprError();
4826
4827 if (!Decl.get())
4828 return ExprResult();
4829
4830 VarDecl *Var = cast<VarDecl>(Decl.get());
4833 NameInfo.getLoc());
4834
4835 // Build an ordinary singleton decl ref.
4836 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4837}
4838
4840 const DeclarationNameInfo &NameInfo, TemplateName Template,
4841 const TemplateArgumentListInfo *TemplateArgs) {
4843 Template.getAsTemplateTemplateParmDecl();
4844 assert(Parameter && "A variable template id without template?");
4845
4846 if (Parameter->templateParameterKind() !=
4848 Parameter->templateParameterKind() !=
4850 return ExprResult();
4851
4852 // Check that the template argument list is well-formed for this template.
4855 Parameter, /*Template kw loc=*/{},
4856 // FIXME: TemplateArgs will not be modified because
4857 // UpdateArgsWithConversions is false, however, we should
4858 // CheckTemplateArgumentList to be const-correct.
4859 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4860 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4861 /*UpdateArgsWithConversions=*/false))
4862 return true;
4863
4865 *TemplateArgs);
4866}
4867
4869 SourceLocation Loc) {
4870 Diag(Loc, diag::err_template_missing_args)
4871 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4872 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4873 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4874 }
4875}
4876
4878 bool TemplateKeyword,
4879 TemplateDecl *TD,
4880 SourceLocation Loc) {
4881 TemplateName Name = Context.getQualifiedTemplateName(
4882 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4884}
4885
4887 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4888 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4889 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4890 bool DoCheckConstraintSatisfaction) {
4891 assert(NamedConcept && "A concept template id without a template?");
4892
4893 if (NamedConcept->isInvalidDecl())
4894 return ExprError();
4895
4898 NamedConcept, ConceptNameInfo.getLoc(),
4899 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4900 /*DefaultArgs=*/{},
4901 /*PartialTemplateArgs=*/false, CTAI,
4902 /*UpdateArgsWithConversions=*/false))
4903 return ExprError();
4904
4905 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4906
4907 // There's a bug with CTAI.CanonicalConverted.
4908 // If the template argument contains a DependentDecltypeType that includes a
4909 // TypeAliasType, and the same written type had occurred previously in the
4910 // source, then the DependentDecltypeType would be canonicalized to that
4911 // previous type which would mess up the substitution.
4912 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4914 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4915 CTAI.SugaredConverted);
4916 ConstraintSatisfaction Satisfaction;
4917 bool AreArgsDependent =
4918 TemplateSpecializationType::anyDependentTemplateArguments(
4919 *TemplateArgs, CTAI.SugaredConverted);
4920 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4921 /*Final=*/false);
4923 Context,
4925 TemplateKWLoc, ConceptNameInfo, FoundDecl, TemplateName(NamedConcept),
4927
4928 bool Error = false;
4929 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4930 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4931 DoCheckConstraintSatisfaction) {
4932
4934
4937
4939 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4940 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4941 TemplateArgs->getRAngleLoc()),
4942 Satisfaction, CL);
4943 Satisfaction.ContainsErrors = Error;
4944 }
4945
4946 if (Error)
4947 return ExprError();
4948
4950 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4951}
4952
4954 SourceLocation TemplateKWLoc,
4955 LookupResult &R,
4956 bool RequiresADL,
4957 const TemplateArgumentListInfo *TemplateArgs) {
4958 // FIXME: Can we do any checking at this point? I guess we could check the
4959 // template arguments that we have against the template name, if the template
4960 // name refers to a single template. That's not a terribly common case,
4961 // though.
4962 // foo<int> could identify a single function unambiguously
4963 // This approach does NOT work, since f<int>(1);
4964 // gets resolved prior to resorting to overload resolution
4965 // i.e., template<class T> void f(double);
4966 // vs template<class T, class U> void f(U);
4967
4968 // These should be filtered out by our callers.
4969 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4970
4971 // Non-function templates require a template argument list.
4972 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4973 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4975 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4976 return ExprError();
4977 }
4978 }
4979 bool KnownDependent = false;
4980 // In C++1y, check variable template ids.
4981 if (R.getAsSingle<VarTemplateDecl>()) {
4983 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4984 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4985 if (Res.isInvalid() || Res.isUsable())
4986 return Res;
4987 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4988 KnownDependent = true;
4989 }
4990
4991 // We don't want lookup warnings at this point.
4992 R.suppressDiagnostics();
4993
4994 if (R.getAsSingle<ConceptDecl>()) {
4995 assert(TemplateKWLoc.isInvalid() &&
4996 "template keyword in front of a concept id?");
4997 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4998 R.getRepresentativeDecl(),
4999 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5000 }
5001
5002 // Check variable template ids (C++17) and concept template parameters
5003 // (C++26).
5005 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5006 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5007 assert(TemplateKWLoc.isInvalid() &&
5008 "template keyword in front of a template parameter?");
5010 R.getLookupNameInfo(),
5011 TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5012 }
5013
5014 // Function templates
5016 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5017 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5018 R.begin(), R.end(), KnownDependent,
5019 /*KnownInstantiationDependent=*/false);
5020 // Model the templates with UnresolvedTemplateTy. The expression should then
5021 // either be transformed in an instantiation or be diagnosed in
5022 // CheckPlaceholderExpr.
5023 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5024 !R.getFoundDecl()->getAsFunction())
5025 ULE->setType(Context.UnresolvedTemplateTy);
5026
5027 return ULE;
5028}
5029
5031 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5032 const DeclarationNameInfo &NameInfo,
5033 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5034 assert(TemplateArgs || TemplateKWLoc.isValid());
5035
5036 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5037 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5038 /*EnteringContext=*/false, TemplateKWLoc))
5039 return ExprError();
5040
5041 if (R.isAmbiguous())
5042 return ExprError();
5043
5044 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5045 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5046
5047 if (R.empty()) {
5049 Diag(NameInfo.getLoc(), diag::err_no_member)
5050 << NameInfo.getName() << DC << SS.getRange();
5051 return ExprError();
5052 }
5053
5054 // If necessary, build an implicit class member access.
5055 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5056 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5057 /*S=*/nullptr);
5058
5059 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5060}
5061
5063 CXXScopeSpec &SS,
5064 SourceLocation TemplateKWLoc,
5065 const UnqualifiedId &Name,
5066 ParsedType ObjectType,
5067 bool EnteringContext,
5069 bool AllowInjectedClassName) {
5070 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5071 DiagCompat(TemplateKWLoc, diag_compat::template_outside_of_template)
5072 << FixItHint::CreateRemoval(TemplateKWLoc);
5073
5074 if (SS.isInvalid())
5075 return TNK_Non_template;
5076
5077 // Figure out where isTemplateName is going to look.
5078 DeclContext *LookupCtx = nullptr;
5079 if (SS.isNotEmpty())
5080 LookupCtx = computeDeclContext(SS, EnteringContext);
5081 else if (ObjectType)
5082 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5083
5084 // C++0x [temp.names]p5:
5085 // If a name prefixed by the keyword template is not the name of
5086 // a template, the program is ill-formed. [Note: the keyword
5087 // template may not be applied to non-template members of class
5088 // templates. -end note ] [ Note: as is the case with the
5089 // typename prefix, the template prefix is allowed in cases
5090 // where it is not strictly necessary; i.e., when the
5091 // nested-name-specifier or the expression on the left of the ->
5092 // or . is not dependent on a template-parameter, or the use
5093 // does not appear in the scope of a template. -end note]
5094 //
5095 // Note: C++03 was more strict here, because it banned the use of
5096 // the "template" keyword prior to a template-name that was not a
5097 // dependent name. C++ DR468 relaxed this requirement (the
5098 // "template" keyword is now permitted). We follow the C++0x
5099 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5100 bool MemberOfUnknownSpecialization;
5101 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5102 ObjectType, EnteringContext, Result,
5103 MemberOfUnknownSpecialization);
5104 if (TNK != TNK_Non_template) {
5105 // We resolved this to a (non-dependent) template name. Return it.
5106 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5107 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5109 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5110 // C++14 [class.qual]p2:
5111 // In a lookup in which function names are not ignored and the
5112 // nested-name-specifier nominates a class C, if the name specified
5113 // [...] is the injected-class-name of C, [...] the name is instead
5114 // considered to name the constructor
5115 //
5116 // We don't get here if naming the constructor would be valid, so we
5117 // just reject immediately and recover by treating the
5118 // injected-class-name as naming the template.
5119 Diag(Name.getBeginLoc(),
5120 diag::ext_out_of_line_qualified_id_type_names_constructor)
5121 << Name.Identifier
5122 << 0 /*injected-class-name used as template name*/
5123 << TemplateKWLoc.isValid();
5124 }
5125 return TNK;
5126 }
5127
5128 if (!MemberOfUnknownSpecialization) {
5129 // Didn't find a template name, and the lookup wasn't dependent.
5130 // Do the lookup again to determine if this is a "nothing found" case or
5131 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5132 // need to do this.
5134 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5136 // Tell LookupTemplateName that we require a template so that it diagnoses
5137 // cases where it finds a non-template.
5138 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5139 ? RequiredTemplateKind(TemplateKWLoc)
5141 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5142 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5143 !R.isAmbiguous()) {
5144 if (LookupCtx)
5145 Diag(Name.getBeginLoc(), diag::err_no_member)
5146 << DNI.getName() << LookupCtx << SS.getRange();
5147 else
5148 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5149 << DNI.getName() << SS.getRange();
5150 }
5151 return TNK_Non_template;
5152 }
5153
5154 NestedNameSpecifier Qualifier = SS.getScopeRep();
5155
5156 switch (Name.getKind()) {
5158 Result = TemplateTy::make(Context.getDependentTemplateName(
5159 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5161
5163 Result = TemplateTy::make(Context.getDependentTemplateName(
5164 {Qualifier, Name.OperatorFunctionId.Operator,
5165 TemplateKWLoc.isValid()}));
5166 return TNK_Function_template;
5167
5169 // This is a kind of template name, but can never occur in a dependent
5170 // scope (literal operators can only be declared at namespace scope).
5171 break;
5172
5173 default:
5174 break;
5175 }
5176
5177 // This name cannot possibly name a dependent template. Diagnose this now
5178 // rather than building a dependent template name that can never be valid.
5179 Diag(Name.getBeginLoc(),
5180 diag::err_template_kw_refers_to_dependent_non_template)
5182 << TemplateKWLoc.isValid() << TemplateKWLoc;
5183 return TNK_Non_template;
5184}
5185
5188 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5189 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5190 const TemplateArgument &Arg = AL.getArgument();
5192 TypeSourceInfo *TSI = nullptr;
5193
5194 // Check template type parameter.
5195 switch(Arg.getKind()) {
5197 // C++ [temp.arg.type]p1:
5198 // A template-argument for a template-parameter which is a
5199 // type shall be a type-id.
5200 ArgType = Arg.getAsType();
5201 TSI = AL.getTypeSourceInfo();
5202 break;
5205 // We have a template type parameter but the template argument
5206 // is a template without any arguments.
5207 SourceRange SR = AL.getSourceRange();
5210 return true;
5211 }
5213 // We have a template type parameter but the template argument is an
5214 // expression; see if maybe it is missing the "typename" keyword.
5215 CXXScopeSpec SS;
5216 DeclarationNameInfo NameInfo;
5217
5218 if (DependentScopeDeclRefExpr *ArgExpr =
5219 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5220 SS.Adopt(ArgExpr->getQualifierLoc());
5221 NameInfo = ArgExpr->getNameInfo();
5222 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5223 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5224 if (ArgExpr->isImplicitAccess()) {
5225 SS.Adopt(ArgExpr->getQualifierLoc());
5226 NameInfo = ArgExpr->getMemberNameInfo();
5227 }
5228 }
5229
5230 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5231 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5232 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5233
5234 if (Result.getAsSingle<TypeDecl>() ||
5235 Result.wasNotFoundInCurrentInstantiation()) {
5236 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5237 // Suggest that the user add 'typename' before the NNS.
5239 Diag(Loc, getLangOpts().MSVCCompat
5240 ? diag::ext_ms_template_type_arg_missing_typename
5241 : diag::err_template_arg_must_be_type_suggest)
5242 << FixItHint::CreateInsertion(Loc, "typename ");
5244
5245 // Recover by synthesizing a type using the location information that we
5246 // already have.
5247 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5248 SS.getScopeRep(), II);
5249 TypeLocBuilder TLB;
5251 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5253 TL.setNameLoc(NameInfo.getLoc());
5254 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5255
5256 // Overwrite our input TemplateArgumentLoc so that we can recover
5257 // properly.
5260
5261 break;
5262 }
5263 }
5264 // fallthrough
5265 [[fallthrough]];
5266 }
5267 default: {
5268 // We allow instantiating a template with template argument packs when
5269 // building deduction guides or mapping constraint template parameters.
5270 if (Arg.getKind() == TemplateArgument::Pack &&
5271 (CodeSynthesisContexts.back().Kind ==
5274 SugaredConverted.push_back(Arg);
5275 CanonicalConverted.push_back(Arg);
5276 return false;
5277 }
5278 // We have a template type parameter but the template argument
5279 // is not a type.
5280 SourceRange SR = AL.getSourceRange();
5281 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5283
5284 return true;
5285 }
5286 }
5287
5288 if (CheckTemplateArgument(TSI))
5289 return true;
5290
5291 // Objective-C ARC:
5292 // If an explicitly-specified template argument type is a lifetime type
5293 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5294 if (getLangOpts().ObjCAutoRefCount &&
5295 ArgType->isObjCLifetimeType() &&
5296 !ArgType.getObjCLifetime()) {
5297 Qualifiers Qs;
5299 ArgType = Context.getQualifiedType(ArgType, Qs);
5300 }
5301
5302 SugaredConverted.push_back(TemplateArgument(ArgType));
5303 CanonicalConverted.push_back(
5304 TemplateArgument(Context.getCanonicalType(ArgType)));
5305 return false;
5306}
5307
5308/// Substitute template arguments into the default template argument for
5309/// the given template type parameter.
5310///
5311/// \param SemaRef the semantic analysis object for which we are performing
5312/// the substitution.
5313///
5314/// \param Template the template that we are synthesizing template arguments
5315/// for.
5316///
5317/// \param TemplateLoc the location of the template name that started the
5318/// template-id we are checking.
5319///
5320/// \param RAngleLoc the location of the right angle bracket ('>') that
5321/// terminates the template-id.
5322///
5323/// \param Param the template template parameter whose default we are
5324/// substituting into.
5325///
5326/// \param Converted the list of template arguments provided for template
5327/// parameters that precede \p Param in the template parameter list.
5328///
5329/// \param Output the resulting substituted template argument.
5330///
5331/// \returns true if an error occurred.
5333 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5334 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5335 ArrayRef<TemplateArgument> SugaredConverted,
5336 ArrayRef<TemplateArgument> CanonicalConverted,
5337 TemplateArgumentLoc &Output) {
5338 Output = Param->getDefaultArgument();
5339
5340 // If the argument type is dependent, instantiate it now based
5341 // on the previously-computed template arguments.
5342 if (Output.getArgument().isInstantiationDependent()) {
5343 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5344 SugaredConverted,
5345 SourceRange(TemplateLoc, RAngleLoc));
5346 if (Inst.isInvalid())
5347 return true;
5348
5349 // Only substitute for the innermost template argument list.
5350 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5351 /*Final=*/true);
5352 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5353 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5354
5355 bool ForLambdaCallOperator = false;
5356 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5357 ForLambdaCallOperator = Rec->isLambda();
5358 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5359 !ForLambdaCallOperator);
5360
5361 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5362 Param->getDefaultArgumentLoc(),
5363 Param->getDeclName()))
5364 return true;
5365 }
5366
5367 return false;
5368}
5369
5370/// Substitute template arguments into the default template argument for
5371/// the given non-type template parameter.
5372///
5373/// \param SemaRef the semantic analysis object for which we are performing
5374/// the substitution.
5375///
5376/// \param Template the template that we are synthesizing template arguments
5377/// for.
5378///
5379/// \param TemplateLoc the location of the template name that started the
5380/// template-id we are checking.
5381///
5382/// \param RAngleLoc the location of the right angle bracket ('>') that
5383/// terminates the template-id.
5384///
5385/// \param Param the non-type template parameter whose default we are
5386/// substituting into.
5387///
5388/// \param Converted the list of template arguments provided for template
5389/// parameters that precede \p Param in the template parameter list.
5390///
5391/// \returns the substituted template argument, or NULL if an error occurred.
5393 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5394 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5395 ArrayRef<TemplateArgument> SugaredConverted,
5396 ArrayRef<TemplateArgument> CanonicalConverted,
5397 TemplateArgumentLoc &Output) {
5398 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5399 SugaredConverted,
5400 SourceRange(TemplateLoc, RAngleLoc));
5401 if (Inst.isInvalid())
5402 return true;
5403
5404 // Only substitute for the innermost template argument list.
5405 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5406 /*Final=*/true);
5407 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5408 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5409
5410 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5411 EnterExpressionEvaluationContext ConstantEvaluated(
5413 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5414 TemplateArgLists, Output);
5415}
5416
5417/// Substitute template arguments into the default template argument for
5418/// the given template template parameter.
5419///
5420/// \param SemaRef the semantic analysis object for which we are performing
5421/// the substitution.
5422///
5423/// \param Template the template that we are synthesizing template arguments
5424/// for.
5425///
5426/// \param TemplateLoc the location of the template name that started the
5427/// template-id we are checking.
5428///
5429/// \param RAngleLoc the location of the right angle bracket ('>') that
5430/// terminates the template-id.
5431///
5432/// \param Param the template template parameter whose default we are
5433/// substituting into.
5434///
5435/// \param Converted the list of template arguments provided for template
5436/// parameters that precede \p Param in the template parameter list.
5437///
5438/// \param QualifierLoc Will be set to the nested-name-specifier (with
5439/// source-location information) that precedes the template name.
5440///
5441/// \returns the substituted template argument, or NULL if an error occurred.
5443 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5444 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5446 ArrayRef<TemplateArgument> SugaredConverted,
5447 ArrayRef<TemplateArgument> CanonicalConverted,
5448 NestedNameSpecifierLoc &QualifierLoc) {
5450 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5451 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5452 if (Inst.isInvalid())
5453 return TemplateName();
5454
5455 // Only substitute for the innermost template argument list.
5456 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5457 /*Final=*/true);
5458 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5459 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5460
5461 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5462
5463 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5464 QualifierLoc = A.getTemplateQualifierLoc();
5465 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5467 A.getTemplateNameLoc(), TemplateArgLists);
5468}
5469
5471 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5472 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5473 ArrayRef<TemplateArgument> SugaredConverted,
5474 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5475 HasDefaultArg = false;
5476
5477 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5478 if (!hasReachableDefaultArgument(TypeParm))
5479 return TemplateArgumentLoc();
5480
5481 HasDefaultArg = true;
5482 TemplateArgumentLoc Output;
5483 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5484 RAngleLoc, TypeParm, SugaredConverted,
5485 CanonicalConverted, Output))
5486 return TemplateArgumentLoc();
5487 return Output;
5488 }
5489
5490 if (NonTypeTemplateParmDecl *NonTypeParm
5491 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5492 if (!hasReachableDefaultArgument(NonTypeParm))
5493 return TemplateArgumentLoc();
5494
5495 HasDefaultArg = true;
5496 TemplateArgumentLoc Output;
5497 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5498 RAngleLoc, NonTypeParm, SugaredConverted,
5499 CanonicalConverted, Output))
5500 return TemplateArgumentLoc();
5501 return Output;
5502 }
5503
5504 TemplateTemplateParmDecl *TempTempParm
5506 if (!hasReachableDefaultArgument(TempTempParm))
5507 return TemplateArgumentLoc();
5508
5509 HasDefaultArg = true;
5510 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5511 NestedNameSpecifierLoc QualifierLoc;
5513 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5514 SugaredConverted, CanonicalConverted, QualifierLoc);
5515 if (TName.isNull())
5516 return TemplateArgumentLoc();
5517
5518 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5519 QualifierLoc, A.getTemplateNameLoc());
5520}
5521
5522/// Convert a template-argument that we parsed as a type into a template, if
5523/// possible. C++ permits injected-class-names to perform dual service as
5524/// template template arguments and as template type arguments.
5527 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5528 if (!TagLoc)
5529 return TemplateArgumentLoc();
5530
5531 // If this type was written as an injected-class-name, it can be used as a
5532 // template template argument.
5533 // If this type was written as an injected-class-name, it may have been
5534 // converted to a RecordType during instantiation. If the RecordType is
5535 // *not* wrapped in a TemplateSpecializationType and denotes a class
5536 // template specialization, it must have come from an injected-class-name.
5537
5538 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5539 if (Name.isNull())
5540 return TemplateArgumentLoc();
5541
5542 return TemplateArgumentLoc(Context, Name,
5543 /*TemplateKWLoc=*/SourceLocation(),
5544 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5545}
5546
5549 SourceLocation TemplateLoc,
5550 SourceLocation RAngleLoc,
5551 unsigned ArgumentPackIndex,
5554 // Check template type parameters.
5555 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5556 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5557 CTAI.CanonicalConverted);
5558
5559 const TemplateArgument &Arg = ArgLoc.getArgument();
5560 // Check non-type template parameters.
5561 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5562 // Do substitution on the type of the non-type template parameter
5563 // with the template arguments we've seen thus far. But if the
5564 // template has a dependent context then we cannot substitute yet.
5565 QualType NTTPType = NTTP->getType();
5566 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5567 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5568
5569 if (NTTPType->isInstantiationDependentType()) {
5570 // Do substitution on the type of the non-type template parameter.
5571 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5572 CTAI.SugaredConverted,
5573 SourceRange(TemplateLoc, RAngleLoc));
5574 if (Inst.isInvalid())
5575 return true;
5576
5578 /*Final=*/true);
5579 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5580 // If the parameter is a pack expansion, expand this slice of the pack.
5581 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5582 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5583 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5584 NTTP->getDeclName());
5585 } else {
5586 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5587 NTTP->getDeclName());
5588 }
5589
5590 // If that worked, check the non-type template parameter type
5591 // for validity.
5592 if (!NTTPType.isNull())
5593 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5594 NTTP->getLocation());
5595 if (NTTPType.isNull())
5596 return true;
5597 }
5598
5599 auto checkExpr = [&](Expr *E) -> Expr * {
5600 TemplateArgument SugaredResult, CanonicalResult;
5602 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5603 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5604 // If the current template argument causes an error, give up now.
5605 if (Res.isInvalid())
5606 return nullptr;
5607 CTAI.SugaredConverted.push_back(SugaredResult);
5608 CTAI.CanonicalConverted.push_back(CanonicalResult);
5609 return Res.get();
5610 };
5611
5612 switch (Arg.getKind()) {
5614 llvm_unreachable("Should never see a NULL template argument here");
5615
5617 Expr *E = Arg.getAsExpr();
5618 Expr *R = checkExpr(E);
5619 if (!R)
5620 return true;
5621 // If the resulting expression is new, then use it in place of the
5622 // old expression in the template argument.
5623 if (R != E) {
5624 TemplateArgument TA(R, /*IsCanonical=*/false);
5625 ArgLoc = TemplateArgumentLoc(TA, R);
5626 }
5627 break;
5628 }
5629
5630 // As for the converted NTTP kinds, they still might need another
5631 // conversion, as the new corresponding parameter might be different.
5632 // Ideally, we would always perform substitution starting with sugared types
5633 // and never need these, as we would still have expressions. Since these are
5634 // needed so rarely, it's probably a better tradeoff to just convert them
5635 // back to expressions.
5640 // FIXME: StructuralValue is untested here.
5641 ExprResult R =
5643 assert(R.isUsable());
5644 if (!checkExpr(R.get()))
5645 return true;
5646 break;
5647 }
5648
5651 // We were given a template template argument. It may not be ill-formed;
5652 // see below.
5655 // We have a template argument such as \c T::template X, which we
5656 // parsed as a template template argument. However, since we now
5657 // know that we need a non-type template argument, convert this
5658 // template name into an expression.
5659
5660 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5661 ArgLoc.getTemplateNameLoc());
5662
5663 CXXScopeSpec SS;
5664 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5665 // FIXME: the template-template arg was a DependentTemplateName,
5666 // so it was provided with a template keyword. However, its source
5667 // location is not stored in the template argument structure.
5668 SourceLocation TemplateKWLoc;
5670 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5671 nullptr);
5672
5673 // If we parsed the template argument as a pack expansion, create a
5674 // pack expansion expression.
5677 if (E.isInvalid())
5678 return true;
5679 }
5680
5681 TemplateArgument SugaredResult, CanonicalResult;
5683 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5684 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5685 if (E.isInvalid())
5686 return true;
5687
5688 CTAI.SugaredConverted.push_back(SugaredResult);
5689 CTAI.CanonicalConverted.push_back(CanonicalResult);
5690 break;
5691 }
5692
5693 // We have a template argument that actually does refer to a class
5694 // template, alias template, or template template parameter, and
5695 // therefore cannot be a non-type template argument.
5696 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5697 << ArgLoc.getSourceRange();
5699
5700 return true;
5701
5703 // We have a non-type template parameter but the template
5704 // argument is a type.
5705
5706 // C++ [temp.arg]p2:
5707 // In a template-argument, an ambiguity between a type-id and
5708 // an expression is resolved to a type-id, regardless of the
5709 // form of the corresponding template-parameter.
5710 //
5711 // We warn specifically about this case, since it can be rather
5712 // confusing for users.
5713 QualType T = Arg.getAsType();
5714 SourceRange SR = ArgLoc.getSourceRange();
5715 if (T->isFunctionType())
5716 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5717 else
5718 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5720 return true;
5721 }
5722
5724 llvm_unreachable("Caller must expand template argument packs");
5725 }
5726
5727 return false;
5728 }
5729
5730
5731 // Check template template parameters.
5733
5734 TemplateParameterList *Params = TempParm->getTemplateParameters();
5735 if (TempParm->isExpandedParameterPack())
5736 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5737
5738 // Substitute into the template parameter list of the template
5739 // template parameter, since previously-supplied template arguments
5740 // may appear within the template template parameter.
5741 //
5742 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5743 {
5744 // Set up a template instantiation context.
5746 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5747 CTAI.SugaredConverted,
5748 SourceRange(TemplateLoc, RAngleLoc));
5749 if (Inst.isInvalid())
5750 return true;
5751
5752 Params = SubstTemplateParams(
5753 Params, CurContext,
5755 /*Final=*/true),
5756 /*EvaluateConstraints=*/false);
5757 if (!Params)
5758 return true;
5759 }
5760
5761 // C++1z [temp.local]p1: (DR1004)
5762 // When [the injected-class-name] is used [...] as a template-argument for
5763 // a template template-parameter [...] it refers to the class template
5764 // itself.
5765 if (Arg.getKind() == TemplateArgument::Type) {
5767 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5768 if (!ConvertedArg.getArgument().isNull())
5769 ArgLoc = ConvertedArg;
5770 }
5771
5772 switch (Arg.getKind()) {
5774 llvm_unreachable("Should never see a NULL template argument here");
5775
5778 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5779 CTAI.PartialOrdering,
5780 &CTAI.StrictPackMatch))
5781 return true;
5782
5783 CTAI.SugaredConverted.push_back(Arg);
5784 CTAI.CanonicalConverted.push_back(
5785 Context.getCanonicalTemplateArgument(Arg));
5786 break;
5787
5790 auto Kind = 0;
5791 switch (TempParm->templateParameterKind()) {
5793 Kind = 1;
5794 break;
5796 Kind = 2;
5797 break;
5798 default:
5799 break;
5800 }
5801
5802 // We have a template template parameter but the template
5803 // argument does not refer to a template.
5804 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5805 << Kind << getLangOpts().CPlusPlus11;
5806 return true;
5807 }
5808
5813 llvm_unreachable("non-type argument with template template parameter");
5814
5816 llvm_unreachable("Caller must expand template argument packs");
5817 }
5818
5819 return false;
5820}
5821
5822/// Diagnose a missing template argument.
5823template<typename TemplateParmDecl>
5825 TemplateDecl *TD,
5826 const TemplateParmDecl *D,
5828 // Dig out the most recent declaration of the template parameter; there may be
5829 // declarations of the template that are more recent than TD.
5831 ->getTemplateParameters()
5832 ->getParam(D->getIndex()));
5833
5834 // If there's a default argument that's not reachable, diagnose that we're
5835 // missing a module import.
5837 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5839 D->getDefaultArgumentLoc(), Modules,
5841 /*Recover*/true);
5842 return true;
5843 }
5844
5845 // FIXME: If there's a more recent default argument that *is* visible,
5846 // diagnose that it was declared too late.
5847
5849
5850 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5851 << /*not enough args*/0
5853 << TD;
5854 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5855 return true;
5856}
5857
5858/// Check that the given template argument list is well-formed
5859/// for specializing the given template.
5861 TemplateDecl *Template, SourceLocation TemplateLoc,
5862 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5863 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5864 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5866 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5867 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5869}
5870
5871/// Check that the given template argument list is well-formed
5872/// for specializing the given template.
5875 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5876 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5877 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5879
5881 *ConstraintsNotSatisfied = false;
5882
5883 // Make a copy of the template arguments for processing. Only make the
5884 // changes at the end when successful in matching the arguments to the
5885 // template.
5886 TemplateArgumentListInfo NewArgs = TemplateArgs;
5887
5888 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5889
5890 // C++23 [temp.arg.general]p1:
5891 // [...] The type and form of each template-argument specified in
5892 // a template-id shall match the type and form specified for the
5893 // corresponding parameter declared by the template in its
5894 // template-parameter-list.
5895 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5896 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5897 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5898 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5899 LocalInstantiationScope InstScope(*this, true);
5900 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5901 ParamEnd = Params->end(),
5902 Param = ParamBegin;
5903 Param != ParamEnd;
5904 /* increment in loop */) {
5905 if (size_t ParamIdx = Param - ParamBegin;
5906 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5907 // All written arguments should have been consumed by this point.
5908 assert(ArgIdx == NumArgs && "bad default argument deduction");
5909 if (ParamIdx == DefaultArgs.StartPos) {
5910 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5911 // Default arguments from a DeducedTemplateName are already converted.
5912 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5913 CTAI.SugaredConverted.push_back(DefArg);
5914 CTAI.CanonicalConverted.push_back(
5915 Context.getCanonicalTemplateArgument(DefArg));
5916 ++Param;
5917 }
5918 continue;
5919 }
5920 }
5921
5922 // If we have an expanded parameter pack, make sure we don't have too
5923 // many arguments.
5924 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5925 if (*Expansions == SugaredArgumentPack.size()) {
5926 // We're done with this parameter pack. Pack up its arguments and add
5927 // them to the list.
5928 CTAI.SugaredConverted.push_back(
5929 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5930 SugaredArgumentPack.clear();
5931
5932 CTAI.CanonicalConverted.push_back(
5933 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5934 CanonicalArgumentPack.clear();
5935
5936 // This argument is assigned to the next parameter.
5937 ++Param;
5938 continue;
5939 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5940 // Not enough arguments for this parameter pack.
5941 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5942 << /*not enough args*/0
5944 << Template;
5946 return true;
5947 }
5948 }
5949
5950 // Check for builtins producing template packs in this context, we do not
5951 // support them yet.
5952 if (const NonTypeTemplateParmDecl *NTTP =
5953 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5954 NTTP && NTTP->isPackExpansion()) {
5955 auto TL = NTTP->getTypeSourceInfo()
5956 ->getTypeLoc()
5959 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5960 for (const auto &UPP : Unexpanded) {
5961 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5962 if (!TST)
5963 continue;
5964 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5965 // Expanding a built-in pack in this context is not yet supported.
5966 Diag(TL.getEllipsisLoc(),
5967 diag::err_unsupported_builtin_template_pack_expansion)
5968 << TST->getTemplateName();
5969 return true;
5970 }
5971 }
5972
5973 if (ArgIdx < NumArgs) {
5974 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5975 bool NonPackParameter =
5976 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5977 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5978
5979 if (ArgIsExpansion && CTAI.MatchingTTP) {
5980 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5981 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5982 ++Param) {
5983 TemplateArgument &Arg = Args[Param - First];
5984 Arg = ArgLoc.getArgument();
5985 if (!(*Param)->isTemplateParameterPack() ||
5986 getExpandedPackSize(*Param))
5987 Arg = Arg.getPackExpansionPattern();
5988 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5989 SaveAndRestore _1(CTAI.PartialOrdering, false);
5990 SaveAndRestore _2(CTAI.MatchingTTP, true);
5991 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5992 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5994 return true;
5995 Arg = NewArgLoc.getArgument();
5996 CTAI.CanonicalConverted.back().setIsDefaulted(
5997 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5998 CTAI.CanonicalConverted,
5999 Params->getDepth()));
6000 }
6001 ArgLoc = TemplateArgumentLoc(
6004 } else {
6005 SaveAndRestore _1(CTAI.PartialOrdering, false);
6006 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6007 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6009 return true;
6010 CTAI.CanonicalConverted.back().setIsDefaulted(
6011 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6012 *Param, CTAI.CanonicalConverted,
6013 Params->getDepth()));
6014 if (ArgIsExpansion && NonPackParameter) {
6015 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6016 // alias template, builtin template, or concept, and it's not part of
6017 // a parameter pack. This can't be canonicalized, so reject it now.
6019 Template)) {
6020 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6022 : 0;
6023 Diag(ArgLoc.getLocation(),
6024 diag::err_template_expansion_into_fixed_list)
6025 << DiagSelect << ArgLoc.getSourceRange();
6027 return true;
6028 }
6029 }
6030 }
6031
6032 // We're now done with this argument.
6033 ++ArgIdx;
6034
6035 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6036 // Directly convert the remaining arguments, because we don't know what
6037 // parameters they'll match up with.
6038
6039 if (!SugaredArgumentPack.empty()) {
6040 // If we were part way through filling in an expanded parameter pack,
6041 // fall back to just producing individual arguments.
6042 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6043 SugaredArgumentPack.begin(),
6044 SugaredArgumentPack.end());
6045 SugaredArgumentPack.clear();
6046
6047 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6048 CanonicalArgumentPack.begin(),
6049 CanonicalArgumentPack.end());
6050 CanonicalArgumentPack.clear();
6051 }
6052
6053 while (ArgIdx < NumArgs) {
6054 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6055 CTAI.SugaredConverted.push_back(Arg);
6056 CTAI.CanonicalConverted.push_back(
6057 Context.getCanonicalTemplateArgument(Arg));
6058 ++ArgIdx;
6059 }
6060
6061 return false;
6062 }
6063
6064 if ((*Param)->isTemplateParameterPack()) {
6065 // The template parameter was a template parameter pack, so take the
6066 // deduced argument and place it on the argument pack. Note that we
6067 // stay on the same template parameter so that we can deduce more
6068 // arguments.
6069 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6070 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6071 } else {
6072 // Move to the next template parameter.
6073 ++Param;
6074 }
6075 continue;
6076 }
6077
6078 // If we're checking a partial template argument list, we're done.
6079 if (PartialTemplateArgs) {
6080 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6081 CTAI.SugaredConverted.push_back(
6082 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6083 CTAI.CanonicalConverted.push_back(
6084 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6085 }
6086 return false;
6087 }
6088
6089 // If we have a template parameter pack with no more corresponding
6090 // arguments, just break out now and we'll fill in the argument pack below.
6091 if ((*Param)->isTemplateParameterPack()) {
6092 assert(!getExpandedPackSize(*Param) &&
6093 "Should have dealt with this already");
6094
6095 // A non-expanded parameter pack before the end of the parameter list
6096 // only occurs for an ill-formed template parameter list, unless we've
6097 // got a partial argument list for a function template, so just bail out.
6098 if (Param + 1 != ParamEnd) {
6099 assert(
6100 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6101 "Concept templates must have parameter packs at the end.");
6102 return true;
6103 }
6104
6105 CTAI.SugaredConverted.push_back(
6106 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6107 SugaredArgumentPack.clear();
6108
6109 CTAI.CanonicalConverted.push_back(
6110 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6111 CanonicalArgumentPack.clear();
6112
6113 ++Param;
6114 continue;
6115 }
6116
6117 // Check whether we have a default argument.
6118 bool HasDefaultArg;
6119
6120 // Retrieve the default template argument from the template
6121 // parameter. For each kind of template parameter, we substitute the
6122 // template arguments provided thus far and any "outer" template arguments
6123 // (when the template parameter was part of a nested template) into
6124 // the default argument.
6126 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6127 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6128
6129 if (Arg.getArgument().isNull()) {
6130 if (!HasDefaultArg) {
6131 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6132 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6133 NewArgs);
6134 if (NonTypeTemplateParmDecl *NTTP =
6135 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6136 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6137 NewArgs);
6138 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6140 NewArgs);
6141 }
6142 return true;
6143 }
6144
6145 // Introduce an instantiation record that describes where we are using
6146 // the default template argument. We're not actually instantiating a
6147 // template here, we just create this object to put a note into the
6148 // context stack.
6149 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6150 CTAI.SugaredConverted,
6151 SourceRange(TemplateLoc, RAngleLoc));
6152 if (Inst.isInvalid())
6153 return true;
6154
6155 SaveAndRestore _1(CTAI.PartialOrdering, false);
6156 SaveAndRestore _2(CTAI.MatchingTTP, false);
6157 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6158 // Check the default template argument.
6159 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6160 CTAI, CTAK_Specified))
6161 return true;
6162
6163 CTAI.SugaredConverted.back().setIsDefaulted(true);
6164 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6165
6166 // Core issue 150 (assumed resolution): if this is a template template
6167 // parameter, keep track of the default template arguments from the
6168 // template definition.
6169 if (isTemplateTemplateParameter)
6170 NewArgs.addArgument(Arg);
6171
6172 // Move to the next template parameter and argument.
6173 ++Param;
6174 ++ArgIdx;
6175 }
6176
6177 // If we're performing a partial argument substitution, allow any trailing
6178 // pack expansions; they might be empty. This can happen even if
6179 // PartialTemplateArgs is false (the list of arguments is complete but
6180 // still dependent).
6181 if (CTAI.MatchingTTP ||
6183 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6184 while (ArgIdx < NumArgs &&
6185 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6186 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6187 CTAI.SugaredConverted.push_back(Arg);
6188 CTAI.CanonicalConverted.push_back(
6189 Context.getCanonicalTemplateArgument(Arg));
6190 }
6191 }
6192
6193 // If we have any leftover arguments, then there were too many arguments.
6194 // Complain and fail.
6195 if (ArgIdx < NumArgs) {
6196 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6197 << /*too many args*/1
6199 << Template
6200 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6202 return true;
6203 }
6204
6205 // No problems found with the new argument list, propagate changes back
6206 // to caller.
6207 if (UpdateArgsWithConversions)
6208 TemplateArgs = std::move(NewArgs);
6209
6210 if (!PartialTemplateArgs) {
6211 // Setup the context/ThisScope for the case where we are needing to
6212 // re-instantiate constraints outside of normal instantiation.
6213 DeclContext *NewContext = Template->getDeclContext();
6214
6215 // If this template is in a template, make sure we extract the templated
6216 // decl.
6217 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6218 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6219 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6220
6221 Qualifiers ThisQuals;
6222 if (const auto *Method =
6223 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6224 ThisQuals = Method->getMethodQualifiers();
6225
6226 ContextRAII Context(*this, NewContext);
6227 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6228
6230 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6231 /*RelativeToPrimary=*/true,
6232 /*Pattern=*/nullptr,
6233 /*ForConceptInstantiation=*/true);
6234 if (!isa<ConceptDecl>(Template) &&
6236 Template, MLTAL,
6237 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6240 return true;
6241 }
6242 }
6243
6244 return false;
6245}
6246
6247namespace {
6248 class UnnamedLocalNoLinkageFinder
6249 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6250 {
6251 Sema &S;
6252 SourceRange SR;
6253
6255
6256 public:
6257 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6258
6259 bool Visit(QualType T) {
6260 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6261 }
6262
6263#define TYPE(Class, Parent) \
6264 bool Visit##Class##Type(const Class##Type *);
6265#define ABSTRACT_TYPE(Class, Parent) \
6266 bool Visit##Class##Type(const Class##Type *) { return false; }
6267#define NON_CANONICAL_TYPE(Class, Parent) \
6268 bool Visit##Class##Type(const Class##Type *) { return false; }
6269#include "clang/AST/TypeNodes.inc"
6270
6271 bool VisitTagDecl(const TagDecl *Tag);
6272 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6273 };
6274} // end anonymous namespace
6275
6276bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6277 return false;
6278}
6279
6280bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6281 return Visit(T->getElementType());
6282}
6283
6284bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6285 return Visit(T->getPointeeType());
6286}
6287
6288bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6289 const BlockPointerType* T) {
6290 return Visit(T->getPointeeType());
6291}
6292
6293bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6294 const LValueReferenceType* T) {
6295 return Visit(T->getPointeeType());
6296}
6297
6298bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6299 const RValueReferenceType* T) {
6300 return Visit(T->getPointeeType());
6301}
6302
6303bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6304 const MemberPointerType *T) {
6305 if (Visit(T->getPointeeType()))
6306 return true;
6307 if (auto *RD = T->getMostRecentCXXRecordDecl())
6308 return VisitTagDecl(RD);
6309 return VisitNestedNameSpecifier(T->getQualifier());
6310}
6311
6312bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6313 const ConstantArrayType* T) {
6314 return Visit(T->getElementType());
6315}
6316
6317bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6318 const IncompleteArrayType* T) {
6319 return Visit(T->getElementType());
6320}
6321
6322bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6323 const VariableArrayType* T) {
6324 return Visit(T->getElementType());
6325}
6326
6327bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6328 const DependentSizedArrayType* T) {
6329 return Visit(T->getElementType());
6330}
6331
6332bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6334 return Visit(T->getElementType());
6335}
6336
6337bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6338 const DependentSizedMatrixType *T) {
6339 return Visit(T->getElementType());
6340}
6341
6342bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6344 return Visit(T->getPointeeType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6348 return Visit(T->getElementType());
6349}
6350
6351bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6352 const DependentVectorType *T) {
6353 return Visit(T->getElementType());
6354}
6355
6356bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6357 return Visit(T->getElementType());
6358}
6359
6360bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6361 const ConstantMatrixType *T) {
6362 return Visit(T->getElementType());
6363}
6364
6365bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6366 const FunctionProtoType* T) {
6367 for (const auto &A : T->param_types()) {
6368 if (Visit(A))
6369 return true;
6370 }
6371
6372 return Visit(T->getReturnType());
6373}
6374
6375bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6376 const FunctionNoProtoType* T) {
6377 return Visit(T->getReturnType());
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6381 const UnresolvedUsingType*) {
6382 return false;
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6386 return false;
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6390 return Visit(T->getUnmodifiedType());
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6394 return false;
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6398 const PackIndexingType *) {
6399 return false;
6400}
6401
6402bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6403 const UnaryTransformType*) {
6404 return false;
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6408 return Visit(T->getDeducedType());
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6412 const DeducedTemplateSpecializationType *T) {
6413 return Visit(T->getDeducedType());
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6417 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6421 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6425 const TemplateTypeParmType*) {
6426 return false;
6427}
6428
6429bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6430 const SubstTemplateTypeParmPackType *) {
6431 return false;
6432}
6433
6434bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6435 const SubstBuiltinTemplatePackType *) {
6436 return false;
6437}
6438
6439bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6440 const TemplateSpecializationType*) {
6441 return false;
6442}
6443
6444bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6445 const InjectedClassNameType* T) {
6446 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6447}
6448
6449bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6450 const DependentNameType* T) {
6451 return VisitNestedNameSpecifier(T->getQualifier());
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6455 const PackExpansionType* T) {
6456 return Visit(T->getPattern());
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6460 return false;
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6464 const ObjCInterfaceType *) {
6465 return false;
6466}
6467
6468bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6469 const ObjCObjectPointerType *) {
6470 return false;
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6474 return Visit(T->getValueType());
6475}
6476
6477bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6478 const OverflowBehaviorType *T) {
6479 return Visit(T->getUnderlyingType());
6480}
6481
6482bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6483 return false;
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6487 return false;
6488}
6489
6490bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6491 const ArrayParameterType *T) {
6492 return VisitConstantArrayType(T);
6493}
6494
6495bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6496 const DependentBitIntType *T) {
6497 return false;
6498}
6499
6500bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6501 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6502 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6503 ? diag::warn_cxx98_compat_template_arg_local_type
6504 : diag::ext_template_arg_local_type)
6505 << S.Context.getCanonicalTagType(Tag) << SR;
6506 return true;
6507 }
6508
6509 if (!Tag->hasNameForLinkage()) {
6510 S.Diag(SR.getBegin(),
6511 S.getLangOpts().CPlusPlus11 ?
6512 diag::warn_cxx98_compat_template_arg_unnamed_type :
6513 diag::ext_template_arg_unnamed_type) << SR;
6514 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6515 return true;
6516 }
6517
6518 return false;
6519}
6520
6521bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6522 NestedNameSpecifier NNS) {
6523 switch (NNS.getKind()) {
6528 return false;
6530 return Visit(QualType(NNS.getAsType(), 0));
6531 }
6532 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6533}
6534
6535bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6536 const HLSLAttributedResourceType *T) {
6537 if (T->hasContainedType() && Visit(T->getContainedType()))
6538 return true;
6539 return Visit(T->getWrappedType());
6540}
6541
6542bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6543 const HLSLInlineSpirvType *T) {
6544 for (auto &Operand : T->getOperands())
6545 if (Operand.isConstant() && Operand.isLiteral())
6546 if (Visit(Operand.getResultType()))
6547 return true;
6548 return false;
6549}
6550
6552 assert(ArgInfo && "invalid TypeSourceInfo");
6553 QualType Arg = ArgInfo->getType();
6554 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6555 QualType CanonArg = Context.getCanonicalType(Arg);
6556
6557 if (CanonArg->isVariablyModifiedType()) {
6558 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6559 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6560 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6561 }
6562
6563 // C++03 [temp.arg.type]p2:
6564 // A local type, a type with no linkage, an unnamed type or a type
6565 // compounded from any of these types shall not be used as a
6566 // template-argument for a template type-parameter.
6567 //
6568 // C++11 allows these, and even in C++03 we allow them as an extension with
6569 // a warning.
6570 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6571 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6572 (void)Finder.Visit(CanonArg);
6573 }
6574
6575 return false;
6576}
6577
6583
6584/// Determine whether the given template argument is a null pointer
6585/// value of the appropriate type.
6588 QualType ParamType, Expr *Arg,
6589 Decl *Entity = nullptr) {
6590 if (Arg->isValueDependent() || Arg->isTypeDependent())
6591 return NPV_NotNullPointer;
6592
6593 // dllimport'd entities aren't constant but are available inside of template
6594 // arguments.
6595 if (Entity && Entity->hasAttr<DLLImportAttr>())
6596 return NPV_NotNullPointer;
6597
6598 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6599 llvm_unreachable(
6600 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6601
6602 if (!S.getLangOpts().CPlusPlus11)
6603 return NPV_NotNullPointer;
6604
6605 // Determine whether we have a constant expression.
6607 if (ArgRV.isInvalid())
6608 return NPV_Error;
6609 Arg = ArgRV.get();
6610
6611 Expr::EvalResult EvalResult;
6613 EvalResult.Diag = &Notes;
6614 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6615 EvalResult.HasSideEffects) {
6616 SourceLocation DiagLoc = Arg->getExprLoc();
6617
6618 // If our only note is the usual "invalid subexpression" note, just point
6619 // the caret at its location rather than producing an essentially
6620 // redundant note.
6621 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6622 diag::note_invalid_subexpr_in_const_expr) {
6623 DiagLoc = Notes[0].first;
6624 Notes.clear();
6625 }
6626
6627 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6628 << Arg->getType() << Arg->getSourceRange();
6629 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6630 S.Diag(Notes[I].first, Notes[I].second);
6631
6633 return NPV_Error;
6634 }
6635
6636 // C++11 [temp.arg.nontype]p1:
6637 // - an address constant expression of type std::nullptr_t
6638 if (Arg->getType()->isNullPtrType())
6639 return NPV_NullPointer;
6640
6641 // - a constant expression that evaluates to a null pointer value (4.10); or
6642 // - a constant expression that evaluates to a null member pointer value
6643 // (4.11); or
6644 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6645 (EvalResult.Val.isMemberPointer() &&
6646 !EvalResult.Val.getMemberPointerDecl())) {
6647 // If our expression has an appropriate type, we've succeeded.
6648 bool ObjCLifetimeConversion;
6649 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6650 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6651 ObjCLifetimeConversion))
6652 return NPV_NullPointer;
6653
6654 // The types didn't match, but we know we got a null pointer; complain,
6655 // then recover as if the types were correct.
6656 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6657 << Arg->getType() << ParamType << Arg->getSourceRange();
6659 return NPV_NullPointer;
6660 }
6661
6662 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6663 // We found a pointer that isn't null, but doesn't refer to an object.
6664 // We could just return NPV_NotNullPointer, but we can print a better
6665 // message with the information we have here.
6666 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6667 << EvalResult.Val.getAsString(S.Context, ParamType);
6669 return NPV_Error;
6670 }
6671
6672 // If we don't have a null pointer value, but we do have a NULL pointer
6673 // constant, suggest a cast to the appropriate type.
6675 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6676 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6677 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6679 ")");
6681 return NPV_NullPointer;
6682 }
6683
6684 // FIXME: If we ever want to support general, address-constant expressions
6685 // as non-type template arguments, we should return the ExprResult here to
6686 // be interpreted by the caller.
6687 return NPV_NotNullPointer;
6688}
6689
6690/// Checks whether the given template argument is compatible with its
6691/// template parameter.
6692static bool
6694 QualType ParamType, Expr *ArgIn,
6695 Expr *Arg, QualType ArgType) {
6696 bool ObjCLifetimeConversion;
6697 if (ParamType->isPointerType() &&
6698 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6699 S.IsQualificationConversion(ArgType, ParamType, false,
6700 ObjCLifetimeConversion)) {
6701 // For pointer-to-object types, qualification conversions are
6702 // permitted.
6703 } else {
6704 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6705 if (!ParamRef->getPointeeType()->isFunctionType()) {
6706 // C++ [temp.arg.nontype]p5b3:
6707 // For a non-type template-parameter of type reference to
6708 // object, no conversions apply. The type referred to by the
6709 // reference may be more cv-qualified than the (otherwise
6710 // identical) type of the template- argument. The
6711 // template-parameter is bound directly to the
6712 // template-argument, which shall be an lvalue.
6713
6714 // FIXME: Other qualifiers?
6715 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6716 unsigned ArgQuals = ArgType.getCVRQualifiers();
6717
6718 if ((ParamQuals | ArgQuals) != ParamQuals) {
6719 S.Diag(Arg->getBeginLoc(),
6720 diag::err_template_arg_ref_bind_ignores_quals)
6721 << ParamType << Arg->getType() << Arg->getSourceRange();
6723 return true;
6724 }
6725 }
6726 }
6727
6728 // At this point, the template argument refers to an object or
6729 // function with external linkage. We now need to check whether the
6730 // argument and parameter types are compatible.
6731 if (!S.Context.hasSameUnqualifiedType(ArgType,
6732 ParamType.getNonReferenceType())) {
6733 // We can't perform this conversion or binding.
6734 if (ParamType->isReferenceType())
6735 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6736 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6737 else
6738 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6739 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6741 return true;
6742 }
6743 }
6744
6745 return false;
6746}
6747
6748/// Checks whether the given template argument is the address
6749/// of an object or function according to C++ [temp.arg.nontype]p1.
6751 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6752 bool IsSpecified, TemplateArgument &SugaredConverted,
6753 TemplateArgument &CanonicalConverted) {
6754 Expr *Arg = ArgIn;
6755 QualType ArgType = Arg->getType();
6756
6757 bool AddressTaken = false;
6758 SourceLocation AddrOpLoc;
6759 if (S.getLangOpts().MicrosoftExt) {
6760 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6761 // dereference and address-of operators.
6762 Arg = Arg->IgnoreParenCasts();
6763
6764 bool ExtWarnMSTemplateArg = false;
6765 UnaryOperatorKind FirstOpKind;
6766 SourceLocation FirstOpLoc;
6767 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6768 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6769 if (UnOpKind == UO_Deref)
6770 ExtWarnMSTemplateArg = true;
6771 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6772 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6773 if (!AddrOpLoc.isValid()) {
6774 FirstOpKind = UnOpKind;
6775 FirstOpLoc = UnOp->getOperatorLoc();
6776 }
6777 } else
6778 break;
6779 }
6780 if (FirstOpLoc.isValid()) {
6781 if (ExtWarnMSTemplateArg)
6782 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6783 << ArgIn->getSourceRange();
6784
6785 if (FirstOpKind == UO_AddrOf)
6786 AddressTaken = true;
6787 else if (Arg->getType()->isPointerType()) {
6788 // We cannot let pointers get dereferenced here, that is obviously not a
6789 // constant expression.
6790 assert(FirstOpKind == UO_Deref);
6791 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6792 << Arg->getSourceRange();
6793 }
6794 }
6795 } else {
6796 // See through any implicit casts we added to fix the type.
6797 // Also ignore parentheses for deduced template arguments.
6798 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6799
6800 // C++ [temp.arg.nontype]p1:
6801 //
6802 // A template-argument for a non-type, non-template
6803 // template-parameter shall be one of: [...]
6804 //
6805 // -- the address of an object or function with external
6806 // linkage, including function templates and function
6807 // template-ids but excluding non-static class members,
6808 // expressed as & id-expression where the & is optional if
6809 // the name refers to a function or array, or if the
6810 // corresponding template-parameter is a reference; or
6811
6812 // In C++98/03 mode, give an extension warning on any extra parentheses.
6813 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6814 if (IsSpecified) {
6815 bool ExtraParens = false;
6816 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6817 if (!ExtraParens) {
6818 S.DiagCompat(Arg->getBeginLoc(),
6819 diag_compat::template_arg_extra_parens)
6820 << Arg->getSourceRange();
6821 ExtraParens = true;
6822 }
6823
6824 Arg = Parens->getSubExpr();
6825 }
6826 }
6827
6828 while (SubstNonTypeTemplateParmExpr *subst =
6829 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6830 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6831
6832 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6833 if (UnOp->getOpcode() == UO_AddrOf) {
6834 Arg = UnOp->getSubExpr();
6835 AddressTaken = true;
6836 AddrOpLoc = UnOp->getOperatorLoc();
6837 }
6838 }
6839
6840 while (SubstNonTypeTemplateParmExpr *subst =
6841 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6842 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6843 }
6844
6845 ValueDecl *Entity = nullptr;
6846 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6847 Entity = DRE->getDecl();
6848 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6849 Entity = CUE->getGuidDecl();
6850
6851 // If our parameter has pointer type, check for a null template value.
6852 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6853 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6854 Entity)) {
6855 case NPV_NullPointer:
6856 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6857 SugaredConverted = TemplateArgument(ParamType,
6858 /*isNullPtr=*/true);
6859 CanonicalConverted =
6861 /*isNullPtr=*/true);
6862 return false;
6863
6864 case NPV_Error:
6865 return true;
6866
6867 case NPV_NotNullPointer:
6868 break;
6869 }
6870 }
6871
6872 // Stop checking the precise nature of the argument if it is value dependent,
6873 // it should be checked when instantiated.
6874 if (Arg->isValueDependent()) {
6875 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6876 CanonicalConverted =
6877 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6878 return false;
6879 }
6880
6881 if (!Entity) {
6882 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6883 << Arg->getSourceRange();
6885 return true;
6886 }
6887
6888 // Cannot refer to non-static data members
6889 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6890 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6891 << Entity << Arg->getSourceRange();
6893 return true;
6894 }
6895
6896 // Cannot refer to non-static member functions
6897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6898 if (!Method->isStatic()) {
6899 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6900 << Method << Arg->getSourceRange();
6902 return true;
6903 }
6904 }
6905
6906 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6907 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6908 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6909
6910 // A non-type template argument must refer to an object or function.
6911 if (!Func && !Var && !Guid) {
6912 // We found something, but we don't know specifically what it is.
6913 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6914 << Arg->getSourceRange();
6915 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6916 return true;
6917 }
6918
6919 // Address / reference template args must have external linkage in C++98.
6920 if (Entity->getFormalLinkage() == Linkage::Internal) {
6921 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_object_internal)
6922 << !Func << Entity << Arg->getSourceRange();
6923 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6924 << !Func;
6925 } else if (!Entity->hasLinkage()) {
6926 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6927 << !Func << Entity << Arg->getSourceRange();
6928 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6929 << !Func;
6930 return true;
6931 }
6932
6933 if (Var) {
6934 // A value of reference type is not an object.
6935 if (Var->getType()->isReferenceType()) {
6936 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6937 << Var->getType() << Arg->getSourceRange();
6939 return true;
6940 }
6941
6942 // A template argument must have static storage duration.
6943 if (Var->getTLSKind()) {
6944 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6945 << Arg->getSourceRange();
6946 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6947 return true;
6948 }
6949 }
6950
6951 if (AddressTaken && ParamType->isReferenceType()) {
6952 // If we originally had an address-of operator, but the
6953 // parameter has reference type, complain and (if things look
6954 // like they will work) drop the address-of operator.
6955 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6956 ParamType.getNonReferenceType())) {
6957 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6958 << ParamType;
6960 return true;
6961 }
6962
6963 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6964 << ParamType
6965 << FixItHint::CreateRemoval(AddrOpLoc);
6967
6968 ArgType = Entity->getType();
6969 }
6970
6971 // If the template parameter has pointer type, either we must have taken the
6972 // address or the argument must decay to a pointer.
6973 if (!AddressTaken && ParamType->isPointerType()) {
6974 if (Func) {
6975 // Function-to-pointer decay.
6976 ArgType = S.Context.getPointerType(Func->getType());
6977 } else if (Entity->getType()->isArrayType()) {
6978 // Array-to-pointer decay.
6979 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6980 } else {
6981 // If the template parameter has pointer type but the address of
6982 // this object was not taken, complain and (possibly) recover by
6983 // taking the address of the entity.
6984 ArgType = S.Context.getPointerType(Entity->getType());
6985 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6986 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6987 << ParamType;
6989 return true;
6990 }
6991
6992 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6993 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6994
6996 }
6997 }
6998
6999 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7000 Arg, ArgType))
7001 return true;
7002
7003 // Create the template argument.
7004 SugaredConverted = TemplateArgument(Entity, ParamType);
7005 CanonicalConverted =
7007 S.Context.getCanonicalType(ParamType));
7008 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7009 return false;
7010}
7011
7012/// Checks whether the given template argument is a pointer to
7013/// member constant according to C++ [temp.arg.nontype]p1.
7015 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7016 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7017 bool Invalid = false;
7018
7019 Expr *Arg = ResultArg;
7020 bool ObjCLifetimeConversion;
7021
7022 // C++ [temp.arg.nontype]p1:
7023 //
7024 // A template-argument for a non-type, non-template
7025 // template-parameter shall be one of: [...]
7026 //
7027 // -- a pointer to member expressed as described in 5.3.1.
7028 DeclRefExpr *DRE = nullptr;
7029
7030 // In C++98/03 mode, give an extension warning on any extra parentheses.
7031 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7032 bool ExtraParens = false;
7033 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7034 if (!Invalid && !ExtraParens) {
7035 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7036 << Arg->getSourceRange();
7037 ExtraParens = true;
7038 }
7039
7040 Arg = Parens->getSubExpr();
7041 }
7042
7043 while (SubstNonTypeTemplateParmExpr *subst =
7044 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7045 Arg = subst->getReplacement()->IgnoreImpCasts();
7046
7047 // A pointer-to-member constant written &Class::member.
7048 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7049 if (UnOp->getOpcode() == UO_AddrOf) {
7050 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7051 if (DRE && !DRE->getQualifier())
7052 DRE = nullptr;
7053 }
7054 }
7055 // A constant of pointer-to-member type.
7056 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7057 ValueDecl *VD = DRE->getDecl();
7058 if (VD->getType()->isMemberPointerType()) {
7060 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7061 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7062 CanonicalConverted =
7063 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7064 } else {
7065 SugaredConverted = TemplateArgument(VD, ParamType);
7066 CanonicalConverted =
7068 S.Context.getCanonicalType(ParamType));
7069 }
7070 return Invalid;
7071 }
7072 }
7073
7074 DRE = nullptr;
7075 }
7076
7077 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7078
7079 // Check for a null pointer value.
7080 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7081 Entity)) {
7082 case NPV_Error:
7083 return true;
7084 case NPV_NullPointer:
7085 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7086 SugaredConverted = TemplateArgument(ParamType,
7087 /*isNullPtr*/ true);
7088 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7089 /*isNullPtr*/ true);
7090 return false;
7091 case NPV_NotNullPointer:
7092 break;
7093 }
7094
7095 if (S.IsQualificationConversion(ResultArg->getType(),
7096 ParamType.getNonReferenceType(), false,
7097 ObjCLifetimeConversion)) {
7098 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7099 ResultArg->getValueKind())
7100 .get();
7101 } else if (!S.Context.hasSameUnqualifiedType(
7102 ResultArg->getType(), ParamType.getNonReferenceType())) {
7103 // We can't perform this conversion.
7104 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7105 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7107 return true;
7108 }
7109
7110 if (!DRE)
7111 return S.Diag(Arg->getBeginLoc(),
7112 diag::err_template_arg_not_pointer_to_member_form)
7113 << Arg->getSourceRange();
7114
7115 if (isa<FieldDecl>(DRE->getDecl()) ||
7117 isa<CXXMethodDecl>(DRE->getDecl())) {
7118 assert((isa<FieldDecl>(DRE->getDecl()) ||
7121 ->isImplicitObjectMemberFunction()) &&
7122 "Only non-static member pointers can make it here");
7123
7124 // Okay: this is the address of a non-static member, and therefore
7125 // a member pointer constant.
7126 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7127 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7128 CanonicalConverted =
7129 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7130 } else {
7131 ValueDecl *D = DRE->getDecl();
7132 SugaredConverted = TemplateArgument(D, ParamType);
7133 CanonicalConverted =
7135 S.Context.getCanonicalType(ParamType));
7136 }
7137 return Invalid;
7138 }
7139
7140 // We found something else, but we don't know specifically what it is.
7141 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7142 << Arg->getSourceRange();
7143 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7144 return true;
7145}
7146
7147/// Check a template argument against its corresponding
7148/// non-type template parameter.
7149///
7150/// This routine implements the semantics of C++ [temp.arg.nontype].
7151/// If an error occurred, it returns ExprError(); otherwise, it
7152/// returns the converted template argument. \p ParamType is the
7153/// type of the non-type template parameter after it has been instantiated.
7155 Expr *Arg,
7156 TemplateArgument &SugaredConverted,
7157 TemplateArgument &CanonicalConverted,
7158 bool StrictCheck,
7160 SourceLocation StartLoc = Arg->getBeginLoc();
7161 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7162 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7163 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7164 DeductionArg = NewDeductionArg;
7165 if (ArgPE) {
7166 // Recreate a pack expansion if we unwrapped one.
7167 Arg = new (Context) PackExpansionExpr(
7168 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7169 } else {
7170 Arg = DeductionArg;
7171 }
7172 };
7173
7174 // If the parameter type somehow involves auto, deduce the type now.
7175 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7176 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7177 if (IsDeduced) {
7178 // When checking a deduced template argument, deduce from its type even if
7179 // the type is dependent, in order to check the types of non-type template
7180 // arguments line up properly in partial ordering.
7181 TypeSourceInfo *TSI =
7182 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7184 InitializedEntity Entity =
7187 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7188 Expr *Inits[1] = {DeductionArg};
7189 ParamType =
7191 if (ParamType.isNull())
7192 return ExprError();
7193 } else {
7194 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7195 Param->getTemplateDepth() + 1);
7196 ParamType = QualType();
7198 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7199 /*DependentDeduction=*/true,
7200 // We do not check constraints right now because the
7201 // immediately-declared constraint of the auto type is
7202 // also an associated constraint, and will be checked
7203 // along with the other associated constraints after
7204 // checking the template argument list.
7205 /*IgnoreConstraints=*/true);
7207 ParamType = TSI->getType();
7208 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7210 return ExprError();
7211 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7212 Diag(Arg->getExprLoc(),
7213 diag::err_non_type_template_parm_type_deduction_failure)
7214 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7215 << Arg->getSourceRange();
7217 return ExprError();
7218 }
7219 ParamType = SubstAutoTypeDependent(ParamType);
7220 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7221 }
7222 }
7223 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7224 // an error. The error message normally references the parameter
7225 // declaration, but here we'll pass the argument location because that's
7226 // where the parameter type is deduced.
7227 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7228 if (ParamType.isNull()) {
7230 return ExprError();
7231 }
7232 }
7233
7234 // We should have already dropped all cv-qualifiers by now.
7235 assert(!ParamType.hasQualifiers() &&
7236 "non-type template parameter type cannot be qualified");
7237
7238 // If either the parameter has a dependent type or the argument is
7239 // type-dependent, there's nothing we can check now.
7240 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7241 // Force the argument to the type of the parameter to maintain invariants.
7242 if (!IsDeduced) {
7244 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7245 ParamType->isLValueReferenceType() ? VK_LValue
7246 : ParamType->isRValueReferenceType() ? VK_XValue
7247 : VK_PRValue);
7248 if (E.isInvalid())
7249 return ExprError();
7250 setDeductionArg(E.get());
7251 }
7252 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7253 CanonicalConverted = TemplateArgument(
7254 Context.getCanonicalTemplateArgument(SugaredConverted));
7255 return Arg;
7256 }
7257
7258 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7259 if (CTAK == CTAK_Deduced && !StrictCheck &&
7260 (ParamType->isReferenceType()
7261 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7262 DeductionArg->getType())
7263 : !Context.hasSameUnqualifiedType(ParamType,
7264 DeductionArg->getType()))) {
7265 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7266 // we should actually be checking the type of the template argument in P,
7267 // not the type of the template argument deduced from A, against the
7268 // template parameter type.
7269 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7270 << Arg->getType() << ParamType.getUnqualifiedType();
7272 return ExprError();
7273 }
7274
7275 // If the argument is a pack expansion, we don't know how many times it would
7276 // expand. If we continue checking the argument, this will make the template
7277 // definition ill-formed if it would be ill-formed for any number of
7278 // expansions during instantiation time. When partial ordering or matching
7279 // template template parameters, this is exactly what we want. Otherwise, the
7280 // normal template rules apply: we accept the template if it would be valid
7281 // for any number of expansions (i.e. none).
7282 if (ArgPE && !StrictCheck) {
7283 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7284 CanonicalConverted = TemplateArgument(
7285 Context.getCanonicalTemplateArgument(SugaredConverted));
7286 return Arg;
7287 }
7288
7289 // Avoid making a copy when initializing a template parameter of class type
7290 // from a template parameter object of the same type. This is going beyond
7291 // the standard, but is required for soundness: in
7292 // template<A a> struct X { X *p; X<a> *q; };
7293 // ... we need p and q to have the same type.
7294 //
7295 // Similarly, don't inject a call to a copy constructor when initializing
7296 // from a template parameter of the same type.
7297 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7298 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7299 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7300 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7301 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7302
7303 SugaredConverted = TemplateArgument(TPO, ParamType);
7304 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7305 ParamType.getCanonicalType());
7306 return Arg;
7307 }
7309 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7310 CanonicalConverted =
7311 Context.getCanonicalTemplateArgument(SugaredConverted);
7312 return Arg;
7313 }
7314 }
7315
7316 // The initialization of the parameter from the argument is
7317 // a constant-evaluated context.
7320
7321 bool IsConvertedConstantExpression = true;
7322 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7324 StartLoc, /*DirectInit=*/false, DeductionArg);
7325 Expr *Inits[1] = {DeductionArg};
7326 InitializedEntity Entity =
7328 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7329 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7330 if (Result.isInvalid() || !Result.get())
7331 return ExprError();
7333 if (Result.isInvalid() || !Result.get())
7334 return ExprError();
7335 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7336 /*DiscardedValue=*/false,
7337 /*IsConstexpr=*/true,
7338 /*IsTemplateArgument=*/true)
7339 .get());
7340 IsConvertedConstantExpression = false;
7341 }
7342
7343 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7344 // C++17 [temp.arg.nontype]p1:
7345 // A template-argument for a non-type template parameter shall be
7346 // a converted constant expression of the type of the template-parameter.
7347 APValue Value;
7348 ExprResult ArgResult;
7349 if (IsConvertedConstantExpression) {
7351 DeductionArg, ParamType,
7352 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7353 assert(!ArgResult.isUnset());
7354 if (ArgResult.isInvalid()) {
7356 return ExprError();
7357 }
7358 } else {
7359 ArgResult = DeductionArg;
7360 }
7361
7362 // For a value-dependent argument, CheckConvertedConstantExpression is
7363 // permitted (and expected) to be unable to determine a value.
7364 if (ArgResult.get()->isValueDependent()) {
7365 setDeductionArg(ArgResult.get());
7366 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7367 CanonicalConverted =
7368 Context.getCanonicalTemplateArgument(SugaredConverted);
7369 return Arg;
7370 }
7371
7372 APValue PreNarrowingValue;
7374 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7375 false, PreNarrowingValue);
7376 if (ArgResult.isInvalid())
7377 return ExprError();
7378 setDeductionArg(ArgResult.get());
7379
7380 if (Value.isLValue()) {
7381 APValue::LValueBase Base = Value.getLValueBase();
7382 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7383 // For a non-type template-parameter of pointer or reference type,
7384 // the value of the constant expression shall not refer to
7385 assert(ParamType->isPointerOrReferenceType() ||
7386 ParamType->isNullPtrType());
7387 // -- a temporary object
7388 // -- a string literal
7389 // -- the result of a typeid expression, or
7390 // -- a predefined __func__ variable
7391 if (Base &&
7392 (!VD ||
7394 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7395 << Arg->getSourceRange();
7396 return ExprError();
7397 }
7398
7399 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7400 VD->getType()->isArrayType() &&
7401 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7402 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7403 if (ArgPE) {
7404 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7405 CanonicalConverted =
7406 Context.getCanonicalTemplateArgument(SugaredConverted);
7407 } else {
7408 SugaredConverted = TemplateArgument(VD, ParamType);
7409 CanonicalConverted =
7410 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7411 ParamType.getCanonicalType());
7412 }
7413 return Arg;
7414 }
7415
7416 // -- a subobject [until C++20]
7417 if (!getLangOpts().CPlusPlus20) {
7418 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7419 Value.isLValueOnePastTheEnd()) {
7420 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7421 << Value.getAsString(Context, ParamType);
7422 return ExprError();
7423 }
7424 assert((VD || !ParamType->isReferenceType()) &&
7425 "null reference should not be a constant expression");
7426 assert((!VD || !ParamType->isNullPtrType()) &&
7427 "non-null value of type nullptr_t?");
7428 }
7429 }
7430
7431 if (Value.isAddrLabelDiff())
7432 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7433
7434 if (ArgPE) {
7435 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7436 CanonicalConverted =
7437 Context.getCanonicalTemplateArgument(SugaredConverted);
7438 } else {
7439 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7440 CanonicalConverted =
7442 }
7443 return Arg;
7444 }
7445
7446 // These should have all been handled above using the C++17 rules.
7447 assert(!ArgPE && !StrictCheck);
7448
7449 // C++ [temp.arg.nontype]p5:
7450 // The following conversions are performed on each expression used
7451 // as a non-type template-argument. If a non-type
7452 // template-argument cannot be converted to the type of the
7453 // corresponding template-parameter then the program is
7454 // ill-formed.
7455 if (ParamType->isIntegralOrEnumerationType()) {
7456 // C++11:
7457 // -- for a non-type template-parameter of integral or
7458 // enumeration type, conversions permitted in a converted
7459 // constant expression are applied.
7460 //
7461 // C++98:
7462 // -- for a non-type template-parameter of integral or
7463 // enumeration type, integral promotions (4.5) and integral
7464 // conversions (4.7) are applied.
7465
7466 if (getLangOpts().CPlusPlus11) {
7467 // C++ [temp.arg.nontype]p1:
7468 // A template-argument for a non-type, non-template template-parameter
7469 // shall be one of:
7470 //
7471 // -- for a non-type template-parameter of integral or enumeration
7472 // type, a converted constant expression of the type of the
7473 // template-parameter; or
7474 llvm::APSInt Value;
7476 Arg, ParamType, Value, CCEKind::TemplateArg);
7477 if (ArgResult.isInvalid())
7478 return ExprError();
7479 Arg = ArgResult.get();
7480
7481 // We can't check arbitrary value-dependent arguments.
7482 if (Arg->isValueDependent()) {
7483 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7484 CanonicalConverted =
7485 Context.getCanonicalTemplateArgument(SugaredConverted);
7486 return Arg;
7487 }
7488
7489 // Widen the argument value to sizeof(parameter type). This is almost
7490 // always a no-op, except when the parameter type is bool. In
7491 // that case, this may extend the argument from 1 bit to 8 bits.
7492 QualType IntegerType = ParamType;
7493 if (const auto *ED = IntegerType->getAsEnumDecl())
7494 IntegerType = ED->getIntegerType();
7495 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7496 ? Context.getIntWidth(IntegerType)
7497 : Context.getTypeSize(IntegerType));
7498
7499 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7500 CanonicalConverted =
7501 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7502 return Arg;
7503 }
7504
7505 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7506 if (ArgResult.isInvalid())
7507 return ExprError();
7508 Arg = ArgResult.get();
7509
7510 QualType ArgType = Arg->getType();
7511
7512 // C++ [temp.arg.nontype]p1:
7513 // A template-argument for a non-type, non-template
7514 // template-parameter shall be one of:
7515 //
7516 // -- an integral constant-expression of integral or enumeration
7517 // type; or
7518 // -- the name of a non-type template-parameter; or
7519 llvm::APSInt Value;
7520 if (!ArgType->isIntegralOrEnumerationType()) {
7521 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7522 << ArgType << Arg->getSourceRange();
7524 return ExprError();
7525 }
7526 if (!Arg->isValueDependent()) {
7527 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7528 QualType T;
7529
7530 public:
7531 TmplArgICEDiagnoser(QualType T) : T(T) { }
7532
7533 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7534 SourceLocation Loc) override {
7535 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7536 }
7537 } Diagnoser(ArgType);
7538
7539 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7540 if (!Arg)
7541 return ExprError();
7542 }
7543
7544 // From here on out, all we care about is the unqualified form
7545 // of the argument type.
7546 ArgType = ArgType.getUnqualifiedType();
7547
7548 // Try to convert the argument to the parameter's type.
7549 if (Context.hasSameType(ParamType, ArgType)) {
7550 // Okay: no conversion necessary
7551 } else if (ParamType->isBooleanType()) {
7552 // This is an integral-to-boolean conversion.
7553 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7554 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7555 !ParamType->isEnumeralType()) {
7556 // This is an integral promotion or conversion.
7557 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7558 } else {
7559 // We can't perform this conversion.
7560 Diag(StartLoc, diag::err_template_arg_not_convertible)
7561 << Arg->getType() << ParamType << Arg->getSourceRange();
7563 return ExprError();
7564 }
7565
7566 // Add the value of this argument to the list of converted
7567 // arguments. We use the bitwidth and signedness of the template
7568 // parameter.
7569 if (Arg->isValueDependent()) {
7570 // The argument is value-dependent. Create a new
7571 // TemplateArgument with the converted expression.
7572 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7573 CanonicalConverted =
7574 Context.getCanonicalTemplateArgument(SugaredConverted);
7575 return Arg;
7576 }
7577
7578 QualType IntegerType = ParamType;
7579 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7580 IntegerType = ED->getIntegerType();
7581 }
7582
7583 if (ParamType->isBooleanType()) {
7584 // Value must be zero or one.
7585 Value = Value != 0;
7586 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7587 if (Value.getBitWidth() != AllowedBits)
7588 Value = Value.extOrTrunc(AllowedBits);
7589 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7590 } else {
7591 llvm::APSInt OldValue = Value;
7592
7593 // Coerce the template argument's value to the value it will have
7594 // based on the template parameter's type.
7595 unsigned AllowedBits = IntegerType->isBitIntType()
7596 ? Context.getIntWidth(IntegerType)
7597 : Context.getTypeSize(IntegerType);
7598 if (Value.getBitWidth() != AllowedBits)
7599 Value = Value.extOrTrunc(AllowedBits);
7600 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7601
7602 // Complain if an unsigned parameter received a negative value.
7603 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7604 (OldValue.isSigned() && OldValue.isNegative())) {
7605 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7606 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7607 << Arg->getSourceRange();
7609 }
7610
7611 // Complain if we overflowed the template parameter's type.
7612 unsigned RequiredBits;
7613 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7614 RequiredBits = OldValue.getActiveBits();
7615 else if (OldValue.isUnsigned())
7616 RequiredBits = OldValue.getActiveBits() + 1;
7617 else
7618 RequiredBits = OldValue.getSignificantBits();
7619 if (RequiredBits > AllowedBits) {
7620 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7621 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7622 << Arg->getSourceRange();
7624 }
7625 }
7626
7627 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7628 SugaredConverted = TemplateArgument(Context, Value, T);
7629 CanonicalConverted =
7630 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7631 return Arg;
7632 }
7633
7634 QualType ArgType = Arg->getType();
7635 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7636 bool IsSpecified = CTAK == CTAK_Specified;
7637
7638 // Handle pointer-to-function, reference-to-function, and
7639 // pointer-to-member-function all in (roughly) the same way.
7640 if (// -- For a non-type template-parameter of type pointer to
7641 // function, only the function-to-pointer conversion (4.3) is
7642 // applied. If the template-argument represents a set of
7643 // overloaded functions (or a pointer to such), the matching
7644 // function is selected from the set (13.4).
7645 (ParamType->isPointerType() &&
7646 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7647 // -- For a non-type template-parameter of type reference to
7648 // function, no conversions apply. If the template-argument
7649 // represents a set of overloaded functions, the matching
7650 // function is selected from the set (13.4).
7651 (ParamType->isReferenceType() &&
7652 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7653 // -- For a non-type template-parameter of type pointer to
7654 // member function, no conversions apply. If the
7655 // template-argument represents a set of overloaded member
7656 // functions, the matching member function is selected from
7657 // the set (13.4).
7658 (ParamType->isMemberPointerType() &&
7659 ParamType->castAs<MemberPointerType>()->getPointeeType()
7660 ->isFunctionType())) {
7661
7662 if (Arg->getType() == Context.OverloadTy) {
7663 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7664 true,
7665 FoundResult)) {
7666 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7667 return ExprError();
7668
7669 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7670 if (Res.isInvalid())
7671 return ExprError();
7672 Arg = Res.get();
7673 ArgType = Arg->getType();
7674 } else
7675 return ExprError();
7676 }
7677
7678 if (!ParamType->isMemberPointerType()) {
7680 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7681 CanonicalConverted))
7682 return ExprError();
7683 return Arg;
7684 }
7685
7687 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7688 return ExprError();
7689 return Arg;
7690 }
7691
7692 if (ParamType->isPointerType()) {
7693 // -- for a non-type template-parameter of type pointer to
7694 // object, qualification conversions (4.4) and the
7695 // array-to-pointer conversion (4.2) are applied.
7696 // C++0x also allows a value of std::nullptr_t.
7697 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7698 "Only object pointers allowed here");
7699
7701 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7702 CanonicalConverted))
7703 return ExprError();
7704 return Arg;
7705 }
7706
7707 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7708 // -- For a non-type template-parameter of type reference to
7709 // object, no conversions apply. The type referred to by the
7710 // reference may be more cv-qualified than the (otherwise
7711 // identical) type of the template-argument. The
7712 // template-parameter is bound directly to the
7713 // template-argument, which must be an lvalue.
7714 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7715 "Only object references allowed here");
7716
7717 if (Arg->getType() == Context.OverloadTy) {
7719 ParamRefType->getPointeeType(),
7720 true,
7721 FoundResult)) {
7722 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7723 return ExprError();
7724 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7725 if (Res.isInvalid())
7726 return ExprError();
7727 Arg = Res.get();
7728 ArgType = Arg->getType();
7729 } else
7730 return ExprError();
7731 }
7732
7734 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7735 CanonicalConverted))
7736 return ExprError();
7737 return Arg;
7738 }
7739
7740 // Deal with parameters of type std::nullptr_t.
7741 if (ParamType->isNullPtrType()) {
7742 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7743 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7744 CanonicalConverted =
7745 Context.getCanonicalTemplateArgument(SugaredConverted);
7746 return Arg;
7747 }
7748
7749 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7750 case NPV_NotNullPointer:
7751 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7752 << Arg->getType() << ParamType;
7754 return ExprError();
7755
7756 case NPV_Error:
7757 return ExprError();
7758
7759 case NPV_NullPointer:
7760 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7761 SugaredConverted = TemplateArgument(ParamType,
7762 /*isNullPtr=*/true);
7763 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7764 /*isNullPtr=*/true);
7765 return Arg;
7766 }
7767 }
7768
7769 // -- For a non-type template-parameter of type pointer to data
7770 // member, qualification conversions (4.4) are applied.
7771 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7772
7774 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7775 return ExprError();
7776 return Arg;
7777}
7778
7782
7785 const TemplateArgumentLoc &Arg) {
7786 // C++0x [temp.arg.template]p1:
7787 // A template-argument for a template template-parameter shall be
7788 // the name of a class template or an alias template, expressed as an
7789 // id-expression. When the template-argument names a class template, only
7790 // primary class templates are considered when matching the
7791 // template template argument with the corresponding parameter;
7792 // partial specializations are not considered even if their
7793 // parameter lists match that of the template template parameter.
7794 //
7795
7797 unsigned DiagFoundKind = 0;
7798
7799 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7800 switch (TTP->templateParameterKind()) {
7802 DiagFoundKind = 3;
7803 break;
7805 DiagFoundKind = 2;
7806 break;
7807 default:
7808 DiagFoundKind = 1;
7809 break;
7810 }
7811 Kind = TTP->templateParameterKind();
7812 } else if (isa<ConceptDecl>(Template)) {
7814 DiagFoundKind = 3;
7815 } else if (isa<FunctionTemplateDecl>(Template)) {
7817 DiagFoundKind = 0;
7818 } else if (isa<VarTemplateDecl>(Template)) {
7820 DiagFoundKind = 2;
7821 } else if (isa<ClassTemplateDecl>(Template) ||
7825 DiagFoundKind = 1;
7826 } else {
7827 assert(false && "Unexpected Decl");
7828 }
7829
7830 if (Kind == Param->templateParameterKind()) {
7831 return true;
7832 }
7833
7834 unsigned DiagKind = 0;
7835 switch (Param->templateParameterKind()) {
7837 DiagKind = 2;
7838 break;
7840 DiagKind = 1;
7841 break;
7842 default:
7843 DiagKind = 0;
7844 break;
7845 }
7846 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7847 << DiagKind;
7848 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7849 << DiagFoundKind << Template;
7850 return false;
7851}
7852
7853/// Check a template argument against its corresponding
7854/// template template parameter.
7855///
7856/// This routine implements the semantics of C++ [temp.arg.template].
7857/// It returns true if an error occurred, and false otherwise.
7859 TemplateParameterList *Params,
7861 bool PartialOrdering,
7862 bool *StrictPackMatch) {
7864 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7865 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7866 if (!Template) {
7867 // FIXME: Handle AssumedTemplateNames
7868 // Any dependent template name is fine.
7869 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7870 return false;
7871 }
7872
7873 if (Template->isInvalidDecl())
7874 return true;
7875
7877 return true;
7878 }
7879
7880 // C++1z [temp.arg.template]p3: (DR 150)
7881 // A template-argument matches a template template-parameter P when P
7882 // is at least as specialized as the template-argument A.
7884 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7885 PartialOrdering, StrictPackMatch))
7886 return true;
7887 // P2113
7888 // C++20[temp.func.order]p2
7889 // [...] If both deductions succeed, the partial ordering selects the
7890 // more constrained template (if one exists) as determined below.
7891 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7892 Params->getAssociatedConstraints(ParamsAC);
7893 // C++20[temp.arg.template]p3
7894 // [...] In this comparison, if P is unconstrained, the constraints on A
7895 // are not considered.
7896 if (ParamsAC.empty())
7897 return false;
7898
7899 Template->getAssociatedConstraints(TemplateAC);
7900
7901 bool IsParamAtLeastAsConstrained;
7902 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7903 IsParamAtLeastAsConstrained))
7904 return true;
7905 if (!IsParamAtLeastAsConstrained) {
7906 Diag(Arg.getLocation(),
7907 diag::err_template_template_parameter_not_at_least_as_constrained)
7908 << Template << Param << Arg.getSourceRange();
7909 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7910 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7912 TemplateAC);
7913 return true;
7914 }
7915 return false;
7916}
7917
7919 unsigned HereDiagID,
7920 unsigned ExternalDiagID) {
7921 if (Decl.getLocation().isValid())
7922 return S.Diag(Decl.getLocation(), HereDiagID);
7923
7924 SmallString<128> Str;
7925 llvm::raw_svector_ostream Out(Str);
7927 PP.TerseOutput = 1;
7928 Decl.print(Out, PP);
7929 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7930}
7931
7933 std::optional<SourceRange> ParamRange) {
7935 noteLocation(*this, Decl, diag::note_template_decl_here,
7936 diag::note_template_decl_external);
7937 if (ParamRange && ParamRange->isValid()) {
7938 assert(Decl.getLocation().isValid() &&
7939 "Parameter range has location when Decl does not");
7940 DB << *ParamRange;
7941 }
7942}
7943
7945 noteLocation(*this, Decl, diag::note_template_param_here,
7946 diag::note_template_param_external);
7947}
7948
7949/// Given a non-type template argument that refers to a
7950/// declaration and the type of its corresponding non-type template
7951/// parameter, produce an expression that properly refers to that
7952/// declaration.
7954 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7955 // C++ [temp.param]p8:
7956 //
7957 // A non-type template-parameter of type "array of T" or
7958 // "function returning T" is adjusted to be of type "pointer to
7959 // T" or "pointer to function returning T", respectively.
7960 if (ParamType->isArrayType())
7961 ParamType = Context.getArrayDecayedType(ParamType);
7962 else if (ParamType->isFunctionType())
7963 ParamType = Context.getPointerType(ParamType);
7964
7965 // For a NULL non-type template argument, return nullptr casted to the
7966 // parameter's type.
7967 if (Arg.getKind() == TemplateArgument::NullPtr) {
7968 return ImpCastExprToType(
7969 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7970 ParamType,
7971 ParamType->getAs<MemberPointerType>()
7972 ? CK_NullToMemberPointer
7973 : CK_NullToPointer);
7974 }
7975 assert(Arg.getKind() == TemplateArgument::Declaration &&
7976 "Only declaration template arguments permitted here");
7977
7978 ValueDecl *VD = Arg.getAsDecl();
7979
7980 CXXScopeSpec SS;
7981 if (ParamType->isMemberPointerType()) {
7982 // If this is a pointer to member, we need to use a qualified name to
7983 // form a suitable pointer-to-member constant.
7984 assert(VD->getDeclContext()->isRecord() &&
7985 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7987 CanQualType ClassType =
7988 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7989 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7990 SS.MakeTrivial(Context, Qualifier, Loc);
7991 }
7992
7994 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7995 if (RefExpr.isInvalid())
7996 return ExprError();
7997
7998 // For a pointer, the argument declaration is the pointee. Take its address.
7999 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8000 if (ParamType->isPointerType() && !ElemT.isNull() &&
8001 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8002 // Decay an array argument if we want a pointer to its first element.
8003 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8004 if (RefExpr.isInvalid())
8005 return ExprError();
8006 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8007 // For any other pointer, take the address (or form a pointer-to-member).
8008 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8009 if (RefExpr.isInvalid())
8010 return ExprError();
8011 } else if (ParamType->isRecordType()) {
8012 assert(isa<TemplateParamObjectDecl>(VD) &&
8013 "arg for class template param not a template parameter object");
8014 // No conversions apply in this case.
8015 return RefExpr;
8016 } else {
8017 assert(ParamType->isReferenceType() &&
8018 "unexpected type for decl template argument");
8019 // If the parameter has reference type, wrap it in paretheses so that this
8020 // expression will have the correct type under `decltype`.
8021 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8022 }
8023
8024 // At this point we should have the right value category.
8025 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8026 "value kind mismatch for non-type template argument");
8027
8028 // The type of the template parameter can differ from the type of the
8029 // argument in various ways; convert it now if necessary.
8030 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8031 QualType SrcExprType = RefExpr.get()->getType();
8032 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8033 CastKind CK;
8034 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8035 IsFunctionConversion(SrcExprType, DestExprType)) {
8036 CK = CK_NoOp;
8037 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8038 CK = CK_BitCast;
8039 } else {
8040 // FIXME: Pointers to members can need conversion derived-to-base or
8041 // base-to-derived conversions. We currently don't retain enough
8042 // information to convert properly (we need to track a cast path or
8043 // subobject number in the template argument).
8044 llvm_unreachable(
8045 "unexpected conversion required for non-type template argument");
8046 }
8047 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8048 RefExpr.get()->getValueKind());
8049 }
8050
8051 return RefExpr;
8052}
8053
8054/// Construct a new expression that refers to the given
8055/// integral template argument with the given source-location
8056/// information.
8057///
8058/// This routine takes care of the mapping from an integral template
8059/// argument (which may have any integral type) to the appropriate
8060/// literal value.
8062 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8063 assert(OrigT->isIntegralOrEnumerationType());
8064
8065 // If this is an enum type that we're instantiating, we need to use an integer
8066 // type the same size as the enumerator. We don't want to build an
8067 // IntegerLiteral with enum type. The integer type of an enum type can be of
8068 // any integral type with C++11 enum classes, make sure we create the right
8069 // type of literal for it.
8070 QualType T = OrigT;
8071 if (const auto *ED = OrigT->getAsEnumDecl())
8072 T = ED->getIntegerType();
8073
8074 Expr *E;
8075 if (T->isAnyCharacterType()) {
8077 if (T->isWideCharType())
8079 else if (T->isChar8Type() && S.getLangOpts().Char8)
8081 else if (T->isChar16Type())
8083 else if (T->isChar32Type())
8085 else
8087
8088 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8089 } else if (T->isBooleanType()) {
8090 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8091 } else {
8092 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8093 }
8094
8095 if (OrigT->isEnumeralType()) {
8096 // FIXME: This is a hack. We need a better way to handle substituted
8097 // non-type template parameters.
8098 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8099 nullptr, S.CurFPFeatureOverrides(),
8100 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8101 Loc, Loc);
8102 }
8103
8104 return E;
8105}
8106
8108 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8109 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8110 auto *ILE = new (S.Context)
8111 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8112 ILE->setType(T);
8113 return ILE;
8114 };
8115
8116 switch (Val.getKind()) {
8118 // This cannot occur in a template argument at all.
8119 case APValue::Array:
8120 case APValue::Struct:
8121 case APValue::Union:
8122 // These can only occur within a template parameter object, which is
8123 // represented as a TemplateArgument::Declaration.
8124 llvm_unreachable("unexpected template argument value");
8125
8126 case APValue::Int:
8128 Loc);
8129
8130 case APValue::Float:
8131 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8132 T, Loc);
8133
8136 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8137 Val.getFixedPoint().getScale());
8138
8139 case APValue::ComplexInt: {
8140 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8142 S, ElemT, Val.getComplexIntReal(), Loc),
8144 S, ElemT, Val.getComplexIntImag(), Loc)});
8145 }
8146
8147 case APValue::ComplexFloat: {
8148 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8149 return MakeInitList(
8151 ElemT, Loc),
8153 ElemT, Loc)});
8154 }
8155
8156 case APValue::Vector: {
8157 QualType ElemT = T->castAs<VectorType>()->getElementType();
8159 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8161 S, ElemT, Val.getVectorElt(I), Loc));
8162 return MakeInitList(Elts);
8163 }
8164
8165 case APValue::Matrix:
8166 llvm_unreachable("Matrix template argument expression not yet supported");
8167
8168 case APValue::None:
8170 llvm_unreachable("Unexpected APValue kind.");
8171 case APValue::LValue:
8173 // There isn't necessarily a valid equivalent source-level syntax for
8174 // these; in particular, a naive lowering might violate access control.
8175 // So for now we lower to a ConstantExpr holding the value, wrapped around
8176 // an OpaqueValueExpr.
8177 // FIXME: We should have a better representation for this.
8179 if (T->isReferenceType()) {
8180 T = T->getPointeeType();
8181 VK = VK_LValue;
8182 }
8183 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8184 return ConstantExpr::Create(S.Context, OVE, Val);
8185 }
8186 llvm_unreachable("Unhandled APValue::ValueKind enum");
8187}
8188
8191 SourceLocation Loc) {
8192 switch (Arg.getKind()) {
8198 llvm_unreachable("not a non-type template argument");
8199
8201 return Arg.getAsExpr();
8202
8206 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8207
8210 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8211
8214 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8215 }
8216 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8217}
8218
8219/// Match two template parameters within template parameter lists.
8221 Sema &S, NamedDecl *New,
8222 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8223 const NamedDecl *OldInstFrom, bool Complain,
8225 // Check the actual kind (type, non-type, template).
8226 if (Old->getKind() != New->getKind()) {
8227 if (Complain) {
8228 unsigned NextDiag = diag::err_template_param_different_kind;
8229 if (TemplateArgLoc.isValid()) {
8230 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8231 NextDiag = diag::note_template_param_different_kind;
8232 }
8233 S.Diag(New->getLocation(), NextDiag)
8234 << (Kind != Sema::TPL_TemplateMatch);
8235 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8236 << (Kind != Sema::TPL_TemplateMatch);
8237 }
8238
8239 return false;
8240 }
8241
8242 // Check that both are parameter packs or neither are parameter packs.
8243 // However, if we are matching a template template argument to a
8244 // template template parameter, the template template parameter can have
8245 // a parameter pack where the template template argument does not.
8246 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8247 if (Complain) {
8248 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8249 if (TemplateArgLoc.isValid()) {
8250 S.Diag(TemplateArgLoc,
8251 diag::err_template_arg_template_params_mismatch);
8252 NextDiag = diag::note_template_parameter_pack_non_pack;
8253 }
8254
8255 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8257 : 2;
8258 S.Diag(New->getLocation(), NextDiag)
8259 << ParamKind << New->isParameterPack();
8260 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8261 << ParamKind << Old->isParameterPack();
8262 }
8263
8264 return false;
8265 }
8266 // For non-type template parameters, check the type of the parameter.
8267 if (NonTypeTemplateParmDecl *OldNTTP =
8268 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8270
8271 // If we are matching a template template argument to a template
8272 // template parameter and one of the non-type template parameter types
8273 // is dependent, then we must wait until template instantiation time
8274 // to actually compare the arguments.
8276 (!OldNTTP->getType()->isDependentType() &&
8277 !NewNTTP->getType()->isDependentType())) {
8278 // C++20 [temp.over.link]p6:
8279 // Two [non-type] template-parameters are equivalent [if] they have
8280 // equivalent types ignoring the use of type-constraints for
8281 // placeholder types
8282 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8283 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8284 if (!S.Context.hasSameType(OldType, NewType)) {
8285 if (Complain) {
8286 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8287 if (TemplateArgLoc.isValid()) {
8288 S.Diag(TemplateArgLoc,
8289 diag::err_template_arg_template_params_mismatch);
8290 NextDiag = diag::note_template_nontype_parm_different_type;
8291 }
8292 S.Diag(NewNTTP->getLocation(), NextDiag)
8293 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8294 S.Diag(OldNTTP->getLocation(),
8295 diag::note_template_nontype_parm_prev_declaration)
8296 << OldNTTP->getType();
8297 }
8298 return false;
8299 }
8300 }
8301 }
8302 // For template template parameters, check the template parameter types.
8303 // The template parameter lists of template template
8304 // parameters must agree.
8305 else if (TemplateTemplateParmDecl *OldTTP =
8306 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8308 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8309 return false;
8311 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8312 OldTTP->getTemplateParameters(), Complain,
8315 : Kind),
8316 TemplateArgLoc))
8317 return false;
8318 }
8319
8323 const Expr *NewC = nullptr, *OldC = nullptr;
8324
8326 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8327 NewC = TC->getImmediatelyDeclaredConstraint();
8328 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8329 OldC = TC->getImmediatelyDeclaredConstraint();
8330 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8331 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8332 ->getPlaceholderTypeConstraint())
8333 NewC = E;
8334 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8335 ->getPlaceholderTypeConstraint())
8336 OldC = E;
8337 } else
8338 llvm_unreachable("unexpected template parameter type");
8339
8340 auto Diagnose = [&] {
8341 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8342 diag::err_template_different_type_constraint);
8343 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8344 diag::note_template_prev_declaration) << /*declaration*/0;
8345 };
8346
8347 if (!NewC != !OldC) {
8348 if (Complain)
8349 Diagnose();
8350 return false;
8351 }
8352
8353 if (NewC) {
8354 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8355 NewC)) {
8356 if (Complain)
8357 Diagnose();
8358 return false;
8359 }
8360 }
8361 }
8362
8363 return true;
8364}
8365
8366/// Diagnose a known arity mismatch when comparing template argument
8367/// lists.
8368static
8373 SourceLocation TemplateArgLoc) {
8374 unsigned NextDiag = diag::err_template_param_list_different_arity;
8375 if (TemplateArgLoc.isValid()) {
8376 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8377 NextDiag = diag::note_template_param_list_different_arity;
8378 }
8379 S.Diag(New->getTemplateLoc(), NextDiag)
8380 << (New->size() > Old->size())
8381 << (Kind != Sema::TPL_TemplateMatch)
8382 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8383 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8384 << (Kind != Sema::TPL_TemplateMatch)
8385 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8386}
8387
8390 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8391 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8392 if (Old->size() != New->size()) {
8393 if (Complain)
8395 TemplateArgLoc);
8396
8397 return false;
8398 }
8399
8400 // C++0x [temp.arg.template]p3:
8401 // A template-argument matches a template template-parameter (call it P)
8402 // when each of the template parameters in the template-parameter-list of
8403 // the template-argument's corresponding class template or alias template
8404 // (call it A) matches the corresponding template parameter in the
8405 // template-parameter-list of P. [...]
8406 TemplateParameterList::iterator NewParm = New->begin();
8407 TemplateParameterList::iterator NewParmEnd = New->end();
8408 for (TemplateParameterList::iterator OldParm = Old->begin(),
8409 OldParmEnd = Old->end();
8410 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8411 if (NewParm == NewParmEnd) {
8412 if (Complain)
8414 TemplateArgLoc);
8415 return false;
8416 }
8417 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8418 OldInstFrom, Complain, Kind,
8419 TemplateArgLoc))
8420 return false;
8421 }
8422
8423 // Make sure we exhausted all of the arguments.
8424 if (NewParm != NewParmEnd) {
8425 if (Complain)
8427 TemplateArgLoc);
8428
8429 return false;
8430 }
8431
8432 if (Kind != TPL_TemplateParamsEquivalent) {
8433 const Expr *NewRC = New->getRequiresClause();
8434 const Expr *OldRC = Old->getRequiresClause();
8435
8436 auto Diagnose = [&] {
8437 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8438 diag::err_template_different_requires_clause);
8439 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8440 diag::note_template_prev_declaration) << /*declaration*/0;
8441 };
8442
8443 if (!NewRC != !OldRC) {
8444 if (Complain)
8445 Diagnose();
8446 return false;
8447 }
8448
8449 if (NewRC) {
8450 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8451 NewRC)) {
8452 if (Complain)
8453 Diagnose();
8454 return false;
8455 }
8456 }
8457 }
8458
8459 return true;
8460}
8461
8462bool
8464 if (!S)
8465 return false;
8466
8467 // Find the nearest enclosing declaration scope.
8468 S = S->getDeclParent();
8469
8470 // C++ [temp.pre]p6: [P2096]
8471 // A template, explicit specialization, or partial specialization shall not
8472 // have C linkage.
8473 DeclContext *Ctx = S->getEntity();
8474 if (Ctx && Ctx->isExternCContext()) {
8475 SourceRange Range =
8476 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8477 ? TemplateParams->getParam(0)->getSourceRange()
8478 : TemplateParams->getSourceRange();
8479 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8480 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8481 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8482 return true;
8483 }
8484 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8485
8486 // C++ [temp]p2:
8487 // A template-declaration can appear only as a namespace scope or
8488 // class scope declaration.
8489 // C++ [temp.expl.spec]p3:
8490 // An explicit specialization may be declared in any scope in which the
8491 // corresponding primary template may be defined.
8492 // C++ [temp.class.spec]p6: [P2096]
8493 // A partial specialization may be declared in any scope in which the
8494 // corresponding primary template may be defined.
8495 if (Ctx) {
8496 if (Ctx->isFileContext())
8497 return false;
8498 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8499 // C++ [temp.mem]p2:
8500 // A local class shall not have member templates.
8501
8502 // Trace the outer context chain, bypassing nested records and OpenMP
8503 // captured regions, to determine if the class in defined inside a
8504 // function or method.
8505 const DeclContext *OutCtx = RD->getDeclContext();
8506 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8507 OutCtx = OutCtx->getParent();
8508
8509 if (OutCtx && OutCtx->isFunctionOrMethod())
8510 return Diag(TemplateParams->getTemplateLoc(),
8511 diag::err_template_inside_local_class)
8512 << TemplateParams->getSourceRange();
8513
8514 return false;
8515 }
8516 }
8517
8518 return Diag(TemplateParams->getTemplateLoc(),
8519 diag::err_template_outside_namespace_or_class_scope)
8520 << TemplateParams->getSourceRange();
8521}
8522
8523/// Determine what kind of template specialization the given declaration
8524/// is.
8526 if (!D)
8527 return TSK_Undeclared;
8528
8529 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8530 return Record->getTemplateSpecializationKind();
8531 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8532 return Function->getTemplateSpecializationKind();
8533 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8534 return Var->getTemplateSpecializationKind();
8535
8536 return TSK_Undeclared;
8537}
8538
8539/// Check whether a specialization is well-formed in the current
8540/// context.
8541///
8542/// This routine determines whether a template specialization can be declared
8543/// in the current context (C++ [temp.expl.spec]p2).
8544///
8545/// \param S the semantic analysis object for which this check is being
8546/// performed.
8547///
8548/// \param Specialized the entity being specialized or instantiated, which
8549/// may be a kind of template (class template, function template, etc.) or
8550/// a member of a class template (member function, static data member,
8551/// member class).
8552///
8553/// \param PrevDecl the previous declaration of this entity, if any.
8554///
8555/// \param Loc the location of the explicit specialization or instantiation of
8556/// this entity.
8557///
8558/// \param IsPartialSpecialization whether this is a partial specialization of
8559/// a class template.
8560///
8561/// \returns true if there was an error that we cannot recover from, false
8562/// otherwise.
8564 NamedDecl *Specialized,
8565 NamedDecl *PrevDecl,
8566 SourceLocation Loc,
8568 // Keep these "kind" numbers in sync with the %select statements in the
8569 // various diagnostics emitted by this routine.
8570 int EntityKind = 0;
8571 if (isa<ClassTemplateDecl>(Specialized))
8572 EntityKind = IsPartialSpecialization? 1 : 0;
8573 else if (isa<VarTemplateDecl>(Specialized))
8574 EntityKind = IsPartialSpecialization ? 3 : 2;
8575 else if (isa<FunctionTemplateDecl>(Specialized))
8576 EntityKind = 4;
8577 else if (isa<CXXMethodDecl>(Specialized))
8578 EntityKind = 5;
8579 else if (isa<VarDecl>(Specialized))
8580 EntityKind = 6;
8581 else if (isa<RecordDecl>(Specialized))
8582 EntityKind = 7;
8583 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8584 EntityKind = 8;
8585 else {
8586 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8587 << S.getLangOpts().CPlusPlus11;
8588 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8589 return true;
8590 }
8591
8592 // C++ [temp.expl.spec]p2:
8593 // An explicit specialization may be declared in any scope in which
8594 // the corresponding primary template may be defined.
8596 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8597 << Specialized;
8598 return true;
8599 }
8600
8601 // C++ [temp.class.spec]p6:
8602 // A class template partial specialization may be declared in any
8603 // scope in which the primary template may be defined.
8604 DeclContext *SpecializedContext =
8605 Specialized->getDeclContext()->getRedeclContext();
8607
8608 // Make sure that this redeclaration (or definition) occurs in the same
8609 // scope or an enclosing namespace.
8610 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8611 : DC->Equals(SpecializedContext))) {
8612 if (isa<TranslationUnitDecl>(SpecializedContext))
8613 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8614 << EntityKind << Specialized;
8615 else {
8616 auto *ND = cast<NamedDecl>(SpecializedContext);
8617 int Diag = diag::err_template_spec_redecl_out_of_scope;
8618 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8619 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8620 S.Diag(Loc, Diag) << EntityKind << Specialized
8621 << ND << isa<CXXRecordDecl>(ND);
8622 }
8623
8624 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8625
8626 // Don't allow specializing in the wrong class during error recovery.
8627 // Otherwise, things can go horribly wrong.
8628 if (DC->isRecord())
8629 return true;
8630 }
8631
8632 return false;
8633}
8634
8636 if (!E->isTypeDependent())
8637 return SourceLocation();
8638 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8639 Checker.TraverseStmt(E);
8640 if (Checker.MatchLoc.isInvalid())
8641 return E->getSourceRange();
8642 return Checker.MatchLoc;
8643}
8644
8645static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8646 if (!TL.getType()->isDependentType())
8647 return SourceLocation();
8648 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8649 Checker.TraverseTypeLoc(TL);
8650 if (Checker.MatchLoc.isInvalid())
8651 return TL.getSourceRange();
8652 return Checker.MatchLoc;
8653}
8654
8655/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8656/// that checks non-type template partial specialization arguments.
8658 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8659 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8660 bool HasError = false;
8661 for (unsigned I = 0; I != NumArgs; ++I) {
8662 if (Args[I].getKind() == TemplateArgument::Pack) {
8664 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8665 Args[I].pack_size(), IsDefaultArgument))
8666 return true;
8667
8668 continue;
8669 }
8670
8671 if (Args[I].getKind() != TemplateArgument::Expression)
8672 continue;
8673
8674 Expr *ArgExpr = Args[I].getAsExpr();
8675 if (ArgExpr->containsErrors()) {
8676 HasError = true;
8677 continue;
8678 }
8679
8680 // We can have a pack expansion of any of the bullets below.
8681 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8682 ArgExpr = Expansion->getPattern();
8683
8684 // Strip off any implicit casts we added as part of type checking.
8685 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8686 ArgExpr = ICE->getSubExpr();
8687
8688 // C++ [temp.class.spec]p8:
8689 // A non-type argument is non-specialized if it is the name of a
8690 // non-type parameter. All other non-type arguments are
8691 // specialized.
8692 //
8693 // Below, we check the two conditions that only apply to
8694 // specialized non-type arguments, so skip any non-specialized
8695 // arguments.
8696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8697 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8698 continue;
8699
8700 if (isa<DependentTemplateIdExpr>(ArgExpr))
8701 continue;
8702
8703 // C++ [temp.class.spec]p9:
8704 // Within the argument list of a class template partial
8705 // specialization, the following restrictions apply:
8706 // -- A partially specialized non-type argument expression
8707 // shall not involve a template parameter of the partial
8708 // specialization except when the argument expression is a
8709 // simple identifier.
8710 // -- The type of a template parameter corresponding to a
8711 // specialized non-type argument shall not be dependent on a
8712 // parameter of the specialization.
8713 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8714 // We implement a compromise between the original rules and DR1315:
8715 // -- A specialized non-type template argument shall not be
8716 // type-dependent and the corresponding template parameter
8717 // shall have a non-dependent type.
8718 SourceRange ParamUseRange =
8719 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8720 if (ParamUseRange.isValid()) {
8721 if (IsDefaultArgument) {
8722 S.Diag(TemplateNameLoc,
8723 diag::err_dependent_non_type_arg_in_partial_spec);
8724 S.Diag(ParamUseRange.getBegin(),
8725 diag::note_dependent_non_type_default_arg_in_partial_spec)
8726 << ParamUseRange;
8727 } else {
8728 S.Diag(ParamUseRange.getBegin(),
8729 diag::err_dependent_non_type_arg_in_partial_spec)
8730 << ParamUseRange;
8731 }
8732 return true;
8733 }
8734
8735 ParamUseRange = findTemplateParameter(
8736 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8737 if (ParamUseRange.isValid()) {
8738 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8739 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8740 << Param->getType();
8742 return true;
8743 }
8744 }
8745
8746 return HasError;
8747}
8748
8750 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8751 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8752 // We have to be conservative when checking a template in a dependent
8753 // context.
8754 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8755 return false;
8756
8757 TemplateParameterList *TemplateParams =
8758 PrimaryTemplate->getTemplateParameters();
8759 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8761 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8762 if (!Param)
8763 continue;
8764
8765 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8766 Param, &TemplateArgs[I],
8767 1, I >= NumExplicit))
8768 return true;
8769 }
8770
8771 return false;
8772}
8773
8775 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8776 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8778 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8779 assert(TUK != TagUseKind::Reference && "References are not specializations");
8780
8781 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8782 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8783 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8784
8785 // Find the class template we're specializing
8786 TemplateName Name = TemplateId.Template.get();
8788 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8789
8790 if (!ClassTemplate) {
8791 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8792 << (Name.getAsTemplateDecl() &&
8794 return true;
8795 }
8796
8797 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8798 auto Message = DSA->getMessage();
8799 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8800 << ClassTemplate << !Message.empty() << Message;
8801 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8802 }
8803
8804 if (S->isTemplateParamScope())
8805 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8806
8807 DeclContext *DC = ClassTemplate->getDeclContext();
8808
8809 bool isMemberSpecialization = false;
8810 bool isPartialSpecialization = false;
8811
8812 if (SS.isSet()) {
8813 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8814 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8815 TemplateNameLoc, &TemplateId,
8816 /*IsMemberSpecialization=*/false))
8817 return true;
8818 }
8819
8820 // Check the validity of the template headers that introduce this
8821 // template.
8822 // FIXME: We probably shouldn't complain about these headers for
8823 // friend declarations.
8824 bool Invalid = false;
8825 TemplateParameterList *TemplateParams =
8827 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8828 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8829 if (Invalid)
8830 return true;
8831
8832 // Check that we can declare a template specialization here.
8833 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8834 return true;
8835
8836 if (TemplateParams && DC->isDependentContext()) {
8837 ContextRAII SavedContext(*this, DC);
8839 return true;
8840 }
8841
8842 if (TemplateParams && TemplateParams->size() > 0) {
8843 isPartialSpecialization = true;
8844
8845 if (TUK == TagUseKind::Friend) {
8846 Diag(KWLoc, diag::err_partial_specialization_friend)
8847 << SourceRange(LAngleLoc, RAngleLoc);
8848 return true;
8849 }
8850
8851 // C++ [temp.class.spec]p10:
8852 // The template parameter list of a specialization shall not
8853 // contain default template argument values.
8854 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8855 Decl *Param = TemplateParams->getParam(I);
8856 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8857 if (TTP->hasDefaultArgument()) {
8858 Diag(TTP->getDefaultArgumentLoc(),
8859 diag::err_default_arg_in_partial_spec);
8860 TTP->removeDefaultArgument();
8861 }
8862 } else if (NonTypeTemplateParmDecl *NTTP
8863 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8864 if (NTTP->hasDefaultArgument()) {
8865 Diag(NTTP->getDefaultArgumentLoc(),
8866 diag::err_default_arg_in_partial_spec)
8867 << NTTP->getDefaultArgument().getSourceRange();
8868 NTTP->removeDefaultArgument();
8869 }
8870 } else {
8872 if (TTP->hasDefaultArgument()) {
8874 diag::err_default_arg_in_partial_spec)
8876 TTP->removeDefaultArgument();
8877 }
8878 }
8879 }
8880 } else if (TemplateParams) {
8881 if (TUK == TagUseKind::Friend)
8882 Diag(KWLoc, diag::err_template_spec_friend)
8884 SourceRange(TemplateParams->getTemplateLoc(),
8885 TemplateParams->getRAngleLoc()))
8886 << SourceRange(LAngleLoc, RAngleLoc);
8887 } else {
8888 assert(TUK == TagUseKind::Friend &&
8889 "should have a 'template<>' for this decl");
8890 }
8891
8892 // Check that the specialization uses the same tag kind as the
8893 // original template.
8895 assert(Kind != TagTypeKind::Enum &&
8896 "Invalid enum tag in class template spec!");
8897 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8898 TUK == TagUseKind::Definition, KWLoc,
8899 ClassTemplate->getIdentifier())) {
8900 Diag(KWLoc, diag::err_use_with_wrong_tag)
8901 << ClassTemplate
8903 ClassTemplate->getTemplatedDecl()->getKindName());
8904 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8905 diag::note_previous_use);
8906 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8907 }
8908
8909 // Translate the parser's template argument list in our AST format.
8910 TemplateArgumentListInfo TemplateArgs =
8911 makeTemplateArgumentListInfo(*this, TemplateId);
8912
8913 // Check for unexpanded parameter packs in any of the template arguments.
8914 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8915 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8916 isPartialSpecialization
8919 return true;
8920
8921 // Check that the template argument list is well-formed for this
8922 // template.
8924 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8925 /*DefaultArgs=*/{},
8926 /*PartialTemplateArgs=*/false, CTAI,
8927 /*UpdateArgsWithConversions=*/true))
8928 return true;
8929
8930 // Find the class template (partial) specialization declaration that
8931 // corresponds to these arguments.
8932 if (isPartialSpecialization) {
8934 TemplateArgs.size(),
8935 CTAI.CanonicalConverted))
8936 return true;
8937
8938 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8939 // also do it during instantiation.
8940 if (!Name.isDependent() &&
8941 !TemplateSpecializationType::anyDependentTemplateArguments(
8942 TemplateArgs, CTAI.CanonicalConverted)) {
8943 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8944 << ClassTemplate->getDeclName();
8945 isPartialSpecialization = false;
8946 Invalid = true;
8947 }
8948 }
8949
8950 llvm::FoldingSetInsertToken InsertToken;
8951 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8952
8953 if (isPartialSpecialization)
8954 PrevDecl = ClassTemplate->findPartialSpecialization(
8955 CTAI.CanonicalConverted, TemplateParams, InsertToken);
8956 else
8957 PrevDecl =
8958 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
8959
8961
8962 // Check whether we can declare a class template specialization in
8963 // the current scope.
8964 if (TUK != TagUseKind::Friend &&
8966 TemplateNameLoc,
8967 isPartialSpecialization))
8968 return true;
8969
8970 if (!isPartialSpecialization) {
8971 // Create a new class template specialization declaration node for
8972 // this explicit specialization or friend declaration.
8974 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8975 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8976 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8978 if (TemplateParameterLists.size() > 0) {
8979 Specialization->setTemplateParameterListsInfo(Context,
8980 TemplateParameterLists);
8981 }
8982
8983 if (!PrevDecl)
8984 ClassTemplate->AddSpecialization(Specialization, InsertToken);
8985 } else {
8987 Context.getCanonicalTemplateSpecializationType(
8989 TemplateName(ClassTemplate->getCanonicalDecl()),
8990 CTAI.CanonicalConverted));
8991 if (Context.hasSameType(
8992 CanonType,
8993 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8994 (!Context.getLangOpts().CPlusPlus20 ||
8995 !TemplateParams->hasAssociatedConstraints())) {
8996 // C++ [temp.class.spec]p9b3:
8997 //
8998 // -- The argument list of the specialization shall not be identical
8999 // to the implicit argument list of the primary template.
9000 //
9001 // This rule has since been removed, because it's redundant given DR1495,
9002 // but we keep it because it produces better diagnostics and recovery.
9003 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9004 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9005 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9006 return CheckClassTemplate(
9007 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9008 TemplateNameLoc, Attr, TemplateParams, AS_none,
9009 /*ModulePrivateLoc=*/SourceLocation(),
9010 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9011 TemplateParameterLists.data(), isMemberSpecialization);
9012 }
9013
9014 // Create a new class template partial specialization declaration node.
9016 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9019 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9020 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9021 Partial->setTemplateArgsAsWritten(TemplateArgs);
9022 SetNestedNameSpecifier(*this, Partial, SS);
9023 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9025 Context, TemplateParameterLists.drop_back(1));
9026 }
9027
9028 if (!PrevPartial)
9029 ClassTemplate->AddPartialSpecialization(Partial, InsertToken);
9030 Specialization = Partial;
9031
9032 // If we are providing an explicit specialization of a member class
9033 // template specialization, make a note of that.
9034 if (isMemberSpecialization)
9035 Partial->setMemberSpecialization();
9036
9038 }
9039
9040 // C++ [temp.expl.spec]p6:
9041 // If a template, a member template or the member of a class template is
9042 // explicitly specialized then that specialization shall be declared
9043 // before the first use of that specialization that would cause an implicit
9044 // instantiation to take place, in every translation unit in which such a
9045 // use occurs; no diagnostic is required.
9046 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9047 bool Okay = false;
9048 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9049 // Is there any previous explicit specialization declaration?
9051 Okay = true;
9052 break;
9053 }
9054 }
9055
9056 if (!Okay) {
9057 SourceRange Range(TemplateNameLoc, RAngleLoc);
9058 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9059 << Context.getCanonicalTagType(Specialization) << Range;
9060
9061 Diag(PrevDecl->getPointOfInstantiation(),
9062 diag::note_instantiation_required_here)
9063 << (PrevDecl->getTemplateSpecializationKind()
9065 return true;
9066 }
9067 }
9068
9069 // If this is not a friend, note that this is an explicit specialization.
9070 if (TUK != TagUseKind::Friend)
9071 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9072
9073 // Check that this isn't a redefinition of this specialization.
9074 if (TUK == TagUseKind::Definition) {
9075 RecordDecl *Def = Specialization->getDefinition();
9076 NamedDecl *Hidden = nullptr;
9077 bool HiddenDefVisible = false;
9078 if (Def && SkipBody &&
9079 isRedefinitionAllowedFor(Def, TemplateNameLoc, &Hidden,
9080 HiddenDefVisible)) {
9081 SkipBody->ShouldSkip = true;
9082 SkipBody->Previous = Def;
9083 if (!HiddenDefVisible && Hidden)
9085 } else if (Def) {
9086 SourceRange Range(TemplateNameLoc, RAngleLoc);
9087 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9088 Diag(Def->getLocation(), diag::note_previous_definition);
9089 Specialization->setInvalidDecl();
9090 return true;
9091 }
9092 }
9093
9096
9097 // Add alignment attributes if necessary; these attributes are checked when
9098 // the ASTContext lays out the structure.
9099 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9100 if (LangOpts.HLSL)
9101 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9104 }
9105
9106 if (ModulePrivateLoc.isValid())
9107 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9108 << (isPartialSpecialization? 1 : 0)
9109 << FixItHint::CreateRemoval(ModulePrivateLoc);
9110
9111 // C++ [temp.expl.spec]p9:
9112 // A template explicit specialization is in the scope of the
9113 // namespace in which the template was defined.
9114 //
9115 // We actually implement this paragraph where we set the semantic
9116 // context (in the creation of the ClassTemplateSpecializationDecl),
9117 // but we also maintain the lexical context where the actual
9118 // definition occurs.
9119 Specialization->setLexicalDeclContext(CurContext);
9120
9121 // We may be starting the definition of this specialization.
9122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9123 Specialization->startDefinition();
9124
9125 if (TUK == TagUseKind::Friend) {
9126 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9127 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9128 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9130 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9131 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9132
9133 // Build the fully-sugared type for this class template
9134 // specialization as the user wrote in the specialization
9135 // itself. This means that we'll pretty-print the type retrieved
9136 // from the specialization's declaration the way that the user
9137 // actually wrote the specialization, rather than formatting the
9138 // name based on the "canonical" representation used to store the
9139 // template arguments in the specialization.
9141 TemplateNameLoc,
9142 WrittenTy,
9143 /*FIXME:*/KWLoc);
9144 Friend->setAccess(AS_public);
9145 CurContext->addDecl(Friend);
9146 } else {
9147 // Add the specialization into its lexical context, so that it can
9148 // be seen when iterating through the list of declarations in that
9149 // context. However, specializations are not found by name lookup.
9150 CurContext->addDecl(Specialization);
9151 }
9152
9153 if (SkipBody && SkipBody->ShouldSkip)
9154 return SkipBody->Previous;
9155
9156 Specialization->setInvalidDecl(Invalid);
9158 return Specialization;
9159}
9160
9162 MultiTemplateParamsArg TemplateParameterLists,
9163 Declarator &D) {
9164 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9165 ActOnDocumentableDecl(NewDecl);
9166 return NewDecl;
9167}
9168
9170 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9171 const IdentifierInfo *Name, SourceLocation NameLoc) {
9172 DeclContext *DC = CurContext;
9173
9174 if (!DC->getRedeclContext()->isFileContext()) {
9175 Diag(NameLoc,
9176 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9177 return nullptr;
9178 }
9179
9180 if (TemplateParameterLists.size() > 1) {
9181 Diag(NameLoc, diag::err_concept_extra_headers);
9182 return nullptr;
9183 }
9184
9185 TemplateParameterList *Params = TemplateParameterLists.front();
9186
9187 if (Params->size() == 0) {
9188 Diag(NameLoc, diag::err_concept_no_parameters);
9189 return nullptr;
9190 }
9191
9192 // Ensure that the parameter pack, if present, is the last parameter in the
9193 // template.
9194 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9195 ParamEnd = Params->end();
9196 ParamIt != ParamEnd; ++ParamIt) {
9197 Decl const *Param = *ParamIt;
9198 if (Param->isParameterPack()) {
9199 if (++ParamIt == ParamEnd)
9200 break;
9201 Diag(Param->getLocation(),
9202 diag::err_template_param_pack_must_be_last_template_parameter);
9203 return nullptr;
9204 }
9205 }
9206
9207 ConceptDecl *NewDecl =
9208 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9209
9210 if (NewDecl->hasAssociatedConstraints()) {
9211 // C++2a [temp.concept]p4:
9212 // A concept shall not have associated constraints.
9213 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9214 NewDecl->setInvalidDecl();
9215 }
9216
9217 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9218 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9220 LookupName(Previous, S);
9221 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9222 /*AllowInlineNamespace*/ false);
9223
9224 // We cannot properly handle redeclarations until we parse the constraint
9225 // expression, so only inject the name if we are sure we are not redeclaring a
9226 // symbol
9227 if (Previous.empty())
9228 PushOnScopeChains(NewDecl, S, true);
9229
9230 return NewDecl;
9231}
9232
9234 bool Found = false;
9235 LookupResult::Filter F = R.makeFilter();
9236 while (F.hasNext()) {
9237 NamedDecl *D = F.next();
9238 if (D == C) {
9239 F.erase();
9240 Found = true;
9241 break;
9242 }
9243 }
9244 F.done();
9245 return Found;
9246}
9247
9250 Expr *ConstraintExpr,
9251 const ParsedAttributesView &Attrs) {
9252 assert(!C->hasDefinition() && "Concept already defined");
9253 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9254 C->setInvalidDecl();
9255 return nullptr;
9256 }
9257 C->setDefinition(ConstraintExpr);
9258 ProcessDeclAttributeList(S, C, Attrs);
9259
9260 // Check for conflicting previous declaration.
9261 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9262 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9264 LookupName(Previous, S);
9265 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9266 /*AllowInlineNamespace*/ false);
9267 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9268 bool AddToScope = true;
9269 CheckConceptRedefinition(C, Previous, AddToScope);
9270
9272 if (!WasAlreadyAdded && AddToScope)
9273 PushOnScopeChains(C, S);
9274
9275 return C;
9276}
9277
9279 LookupResult &Previous, bool &AddToScope) {
9280 AddToScope = true;
9281
9282 if (Previous.empty())
9283 return;
9284
9285 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9286 if (!OldConcept) {
9287 auto *Old = Previous.getRepresentativeDecl();
9288 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9289 << NewDecl->getDeclName();
9290 notePreviousDefinition(Old, NewDecl->getLocation());
9291 AddToScope = false;
9292 return;
9293 }
9294 // Check if we can merge with a concept declaration.
9295 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9296 if (!IsSame) {
9297 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9298 << NewDecl->getDeclName();
9299 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9300 AddToScope = false;
9301 return;
9302 }
9303 if (hasReachableDefinition(OldConcept) &&
9304 IsRedefinitionInModule(NewDecl, OldConcept)) {
9305 Diag(NewDecl->getLocation(), diag::err_redefinition)
9306 << NewDecl->getDeclName();
9307 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9308 AddToScope = false;
9309 return;
9310 }
9311 if (!Previous.isSingleResult()) {
9312 // FIXME: we should produce an error in case of ambig and failed lookups.
9313 // Other decls (e.g. namespaces) also have this shortcoming.
9314 return;
9315 }
9316 // We unwrap canonical decl late to check for module visibility.
9317 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9318}
9319
9321 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9322 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9323 Diag(Loc, diag::err_recursive_concept) << CE;
9324 Diag(CE->getLocation(), diag::note_declared_at);
9325 CE->setInvalidDecl();
9326 return true;
9327 }
9328 // Concept template parameters don't have a definition and can't
9329 // be defined recursively.
9330 return false;
9331}
9332
9333/// \brief Strips various properties off an implicit instantiation
9334/// that has just been explicitly specialized.
9335static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9336 if (MinGW || (isa<FunctionDecl>(D) &&
9337 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9338 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9339
9340 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9341 FD->setInlineSpecified(false);
9342}
9343
9344/// Create an ExplicitInstantiationDecl to record source-location info for an
9345/// explicit template instantiation statement, and add it to \p CurContext.
9346///
9347/// For class templates / nested classes, the caller should build a
9348/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9349/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9350///
9351/// For function / variable templates, the caller should pass TypeAsWritten for
9352/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9354 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9355 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9356 NestedNameSpecifierLoc QualifierLoc,
9357 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9358 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9360 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9361 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9362 Context.addExplicitInstantiationDecl(Spec, EID);
9363 CurContext->addDecl(EID);
9364}
9365
9366/// Compute the diagnostic location for an explicit instantiation
9367// declaration or definition.
9368static SourceLocation
9370 SourceLocation PointOfInstantiation) {
9371 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9372 if (EID->getTemplateSpecializationKind() ==
9374 return EID->getTemplateLoc();
9375
9376 // Explicit instantiations following a specialization have no effect and
9377 // hence no PointOfInstantiation. In that case, walk decl backwards
9378 // until a valid name loc is found.
9379 SourceLocation PrevDiagLoc = PointOfInstantiation;
9380 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9381 Prev = Prev->getPreviousDecl()) {
9382 PrevDiagLoc = Prev->getLocation();
9383 }
9384 assert(PrevDiagLoc.isValid() &&
9385 "Explicit instantiation without point of instantiation?");
9386 return PrevDiagLoc;
9387}
9388
9389bool
9392 NamedDecl *PrevDecl,
9394 SourceLocation PrevPointOfInstantiation,
9395 bool &HasNoEffect) {
9396 HasNoEffect = false;
9397
9398 switch (NewTSK) {
9399 case TSK_Undeclared:
9401 assert(
9402 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9403 "previous declaration must be implicit!");
9404 return false;
9405
9407 switch (PrevTSK) {
9408 case TSK_Undeclared:
9410 // Okay, we're just specializing something that is either already
9411 // explicitly specialized or has merely been mentioned without any
9412 // instantiation.
9413 return false;
9414
9416 if (PrevPointOfInstantiation.isInvalid()) {
9417 // The declaration itself has not actually been instantiated, so it is
9418 // still okay to specialize it.
9420 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9421 return false;
9422 }
9423 // Fall through
9424 [[fallthrough]];
9425
9428 assert((PrevTSK == TSK_ImplicitInstantiation ||
9429 PrevPointOfInstantiation.isValid()) &&
9430 "Explicit instantiation without point of instantiation?");
9431
9432 // C++ [temp.expl.spec]p6:
9433 // If a template, a member template or the member of a class template
9434 // is explicitly specialized then that specialization shall be declared
9435 // before the first use of that specialization that would cause an
9436 // implicit instantiation to take place, in every translation unit in
9437 // which such a use occurs; no diagnostic is required.
9438 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9439 // Is there any previous explicit specialization declaration?
9441 return false;
9442 }
9443
9444 Diag(NewLoc, diag::err_specialization_after_instantiation)
9445 << PrevDecl;
9446 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9447 << (PrevTSK != TSK_ImplicitInstantiation);
9448
9449 return true;
9450 }
9451 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9452
9454 switch (PrevTSK) {
9456 // This explicit instantiation declaration is redundant (that's okay).
9457 HasNoEffect = true;
9458 return false;
9459
9460 case TSK_Undeclared:
9462 // We're explicitly instantiating something that may have already been
9463 // implicitly instantiated; that's fine.
9464 return false;
9465
9467 // C++0x [temp.explicit]p4:
9468 // For a given set of template parameters, if an explicit instantiation
9469 // of a template appears after a declaration of an explicit
9470 // specialization for that template, the explicit instantiation has no
9471 // effect.
9472 HasNoEffect = true;
9473 return false;
9474
9476 // C++0x [temp.explicit]p10:
9477 // If an entity is the subject of both an explicit instantiation
9478 // declaration and an explicit instantiation definition in the same
9479 // translation unit, the definition shall follow the declaration.
9480 Diag(NewLoc,
9481 diag::err_explicit_instantiation_declaration_after_definition);
9482
9483 // Explicit instantiations following a specialization have no effect and
9484 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9485 // until a valid name loc is found.
9486 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9487 diag::note_explicit_instantiation_definition_here);
9488 HasNoEffect = true;
9489 return false;
9490 }
9491 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9492
9494 switch (PrevTSK) {
9495 case TSK_Undeclared:
9497 // We're explicitly instantiating something that may have already been
9498 // implicitly instantiated; that's fine.
9499 return false;
9500
9502 // C++ DR 259, C++0x [temp.explicit]p4:
9503 // For a given set of template parameters, if an explicit
9504 // instantiation of a template appears after a declaration of
9505 // an explicit specialization for that template, the explicit
9506 // instantiation has no effect.
9507 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9508 << PrevDecl;
9509 Diag(PrevDecl->getLocation(),
9510 diag::note_previous_template_specialization);
9511 HasNoEffect = true;
9512 return false;
9513
9515 // We're explicitly instantiating a definition for something for which we
9516 // were previously asked to suppress instantiations. That's fine.
9517
9518 // C++0x [temp.explicit]p4:
9519 // For a given set of template parameters, if an explicit instantiation
9520 // of a template appears after a declaration of an explicit
9521 // specialization for that template, the explicit instantiation has no
9522 // effect.
9523 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9524 // Is there any previous explicit specialization declaration?
9526 HasNoEffect = true;
9527 break;
9528 }
9529 }
9530
9531 return false;
9532
9534 // C++0x [temp.spec]p5:
9535 // For a given template and a given set of template-arguments,
9536 // - an explicit instantiation definition shall appear at most once
9537 // in a program,
9538
9539 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9540 Diag(NewLoc, (getLangOpts().MSVCCompat)
9541 ? diag::ext_explicit_instantiation_duplicate
9542 : diag::err_explicit_instantiation_duplicate)
9543 << PrevDecl;
9544 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9545 diag::note_previous_explicit_instantiation);
9546 HasNoEffect = true;
9547 return false;
9548 }
9549 }
9550
9551 llvm_unreachable("Missing specialization/instantiation case?");
9552}
9553
9555 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9557 // Remove anything from Previous that isn't a function template in
9558 // the correct context.
9559 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9560 LookupResult::Filter F = Previous.makeFilter();
9561 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9562 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9563 while (F.hasNext()) {
9564 NamedDecl *D = F.next()->getUnderlyingDecl();
9565 if (!isa<FunctionTemplateDecl>(D)) {
9566 F.erase();
9567 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9568 continue;
9569 }
9570
9571 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9573 F.erase();
9574 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9575 continue;
9576 }
9577 }
9578 F.done();
9579
9580 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9581 if (Previous.empty()) {
9582 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9583 if (IsFriend && FriendQualifier.isDependent() &&
9584 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9585 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9587 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9588 return false;
9589 }
9590
9591 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9592 << IsFriend;
9593 for (auto &P : DiscardedCandidates)
9594 Diag(P.second->getLocation(),
9595 diag::note_dependent_function_template_spec_discard_reason)
9596 << P.first << IsFriend;
9597 return true;
9598 }
9599
9601 ExplicitTemplateArgs);
9602 return false;
9603}
9604
9606 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9607 LookupResult &Previous, bool QualifiedFriend) {
9608 // The set of function template specializations that could match this
9609 // explicit function template specialization.
9610 UnresolvedSet<8> Candidates;
9611 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9612 /*ForTakingAddress=*/false);
9613
9614 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9615 ConvertedTemplateArgs;
9616
9617 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9618 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9619 I != E; ++I) {
9620 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9621 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9622 // Only consider templates found within the same semantic lookup scope as
9623 // FD.
9624 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9626 continue;
9627
9628 QualType FT = FD->getType();
9629 // C++11 [dcl.constexpr]p8:
9630 // A constexpr specifier for a non-static member function that is not
9631 // a constructor declares that member function to be const.
9632 //
9633 // When matching a constexpr member function template specialization
9634 // against the primary template, we don't yet know whether the
9635 // specialization has an implicit 'const' (because we don't know whether
9636 // it will be a static member function until we know which template it
9637 // specializes). This rule was removed in C++14.
9638 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9639 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9641 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9642 if (OldMD && OldMD->isConst()) {
9643 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9645 EPI.TypeQuals.addConst();
9646 FT = Context.getFunctionType(FPT->getReturnType(),
9647 FPT->getParamTypes(), EPI);
9648 }
9649 }
9650
9652 if (ExplicitTemplateArgs)
9653 Args = *ExplicitTemplateArgs;
9654
9655 // C++ [temp.expl.spec]p11:
9656 // A trailing template-argument can be left unspecified in the
9657 // template-id naming an explicit function template specialization
9658 // provided it can be deduced from the function argument type.
9659 // Perform template argument deduction to determine whether we may be
9660 // specializing this template.
9661 // FIXME: It is somewhat wasteful to build
9662 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9663 FunctionDecl *Specialization = nullptr;
9665 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9666 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9668 // Template argument deduction failed; record why it failed, so
9669 // that we can provide nifty diagnostics.
9670 FailedCandidates.addCandidate().set(
9671 I.getPair(), FunTmpl->getTemplatedDecl(),
9672 MakeDeductionFailureInfo(Context, TDK, Info));
9673 (void)TDK;
9674 continue;
9675 }
9676
9677 // Target attributes are part of the cuda function signature, so
9678 // the deduced template's cuda target must match that of the
9679 // specialization. Given that C++ template deduction does not
9680 // take target attributes into account, we reject candidates
9681 // here that have a different target.
9682 if (LangOpts.CUDA &&
9683 CUDA().IdentifyTarget(Specialization,
9684 /* IgnoreImplicitHDAttr = */ true) !=
9685 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9686 FailedCandidates.addCandidate().set(
9687 I.getPair(), FunTmpl->getTemplatedDecl(),
9690 continue;
9691 }
9692
9693 // Record this candidate.
9694 if (ExplicitTemplateArgs)
9695 ConvertedTemplateArgs[Specialization] = std::move(Args);
9696 Candidates.addDecl(Specialization, I.getAccess());
9697 }
9698 }
9699
9700 // For a qualified friend declaration (with no explicit marker to indicate
9701 // that a template specialization was intended), note all (template and
9702 // non-template) candidates.
9703 if (QualifiedFriend && Candidates.empty()) {
9704 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9705 << FD->getDeclName() << FDLookupContext;
9706 // FIXME: We should form a single candidate list and diagnose all
9707 // candidates at once, to get proper sorting and limiting.
9708 for (auto *OldND : Previous) {
9709 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9710 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9711 }
9712 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9713 return true;
9714 }
9715
9716 // Find the most specialized function template.
9718 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9719 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9720 PDiag(diag::err_function_template_spec_ambiguous)
9721 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9722 PDiag(diag::note_function_template_spec_matched));
9723
9724 if (Result == Candidates.end())
9725 return true;
9726
9727 // Ignore access information; it doesn't figure into redeclaration checking.
9729
9730 if (const auto *PT = Specialization->getPrimaryTemplate();
9731 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9732 auto Message = DSA->getMessage();
9733 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9734 << PT << !Message.empty() << Message;
9735 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9736 }
9737
9738 // C++23 [except.spec]p13:
9739 // An exception specification is considered to be needed when:
9740 // - [...]
9741 // - the exception specification is compared to that of another declaration
9742 // (e.g., an explicit specialization or an overriding virtual function);
9743 // - [...]
9744 //
9745 // The exception specification of a defaulted function is evaluated as
9746 // described above only when needed; similarly, the noexcept-specifier of a
9747 // specialization of a function template or member function of a class
9748 // template is instantiated only when needed.
9749 //
9750 // The standard doesn't specify what the "comparison with another declaration"
9751 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9752 // not state which properties of an explicit specialization must match the
9753 // primary template.
9754 //
9755 // We assume that an explicit specialization must correspond with (per
9756 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9757 // the declaration produced by substitution into the function template.
9758 //
9759 // Since the determination whether two function declarations correspond does
9760 // not consider exception specification, we only need to instantiate it once
9761 // we determine the primary template when comparing types per
9762 // [basic.link]p11.1.
9763 auto *SpecializationFPT =
9764 Specialization->getType()->castAs<FunctionProtoType>();
9765 // If the function has a dependent exception specification, resolve it after
9766 // we have selected the primary template so we can check whether it matches.
9767 if (getLangOpts().CPlusPlus17 &&
9768 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9769 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9770 return true;
9771
9773 = Specialization->getTemplateSpecializationInfo();
9774 assert(SpecInfo && "Function template specialization info missing?");
9775
9776 // Note: do not overwrite location info if previous template
9777 // specialization kind was explicit.
9779 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9780 Specialization->setLocation(FD->getLocation());
9781 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9782 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9783 // function can differ from the template declaration with respect to
9784 // the constexpr specifier.
9785 // FIXME: We need an update record for this AST mutation.
9786 // FIXME: What if there are multiple such prior declarations (for instance,
9787 // from different modules)?
9788 Specialization->setConstexprKind(FD->getConstexprKind());
9789 }
9790
9791 // FIXME: Check if the prior specialization has a point of instantiation.
9792 // If so, we have run afoul of .
9793
9794 // If this is a friend declaration, then we're not really declaring
9795 // an explicit specialization.
9796 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9797
9798 // Check the scope of this explicit specialization.
9799 if (!isFriend &&
9801 Specialization->getPrimaryTemplate(),
9803 false))
9804 return true;
9805
9806 // C++ [temp.expl.spec]p6:
9807 // If a template, a member template or the member of a class template is
9808 // explicitly specialized then that specialization shall be declared
9809 // before the first use of that specialization that would cause an implicit
9810 // instantiation to take place, in every translation unit in which such a
9811 // use occurs; no diagnostic is required.
9812 bool HasNoEffect = false;
9813 if (!isFriend &&
9818 SpecInfo->getPointOfInstantiation(),
9819 HasNoEffect))
9820 return true;
9821
9822 // Mark the prior declaration as an explicit specialization, so that later
9823 // clients know that this is an explicit specialization.
9824 // A dependent friend specialization which has a definition should be treated
9825 // as explicit specialization, despite being invalid.
9826 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9827 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9828 // Since explicit specializations do not inherit '=delete' from their
9829 // primary function template - check if the 'specialization' that was
9830 // implicitly generated (during template argument deduction for partial
9831 // ordering) from the most specialized of all the function templates that
9832 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9833 // first check that it was implicitly generated during template argument
9834 // deduction by making sure it wasn't referenced, and then reset the deleted
9835 // flag to not-deleted, so that we can inherit that information from 'FD'.
9836 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9837 !Specialization->getCanonicalDecl()->isReferenced()) {
9838 // FIXME: This assert will not hold in the presence of modules.
9839 assert(
9840 Specialization->getCanonicalDecl() == Specialization &&
9841 "This must be the only existing declaration of this specialization");
9842 // FIXME: We need an update record for this AST mutation.
9843 Specialization->setDeletedAsWritten(false);
9844 }
9845 // FIXME: We need an update record for this AST mutation.
9848 }
9849
9850 // Turn the given function declaration into a function template
9851 // specialization, with the template arguments from the previous
9852 // specialization.
9853 // Take copies of (semantic and syntactic) template argument lists.
9855 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9856 FD->setFunctionTemplateSpecialization(
9857 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertToken=*/{},
9859 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9860
9861 // A function template specialization inherits the target attributes
9862 // of its template. (We require the attributes explicitly in the
9863 // code to match, but a template may have implicit attributes by
9864 // virtue e.g. of being constexpr, and it passes these implicit
9865 // attributes on to its specializations.)
9866 if (LangOpts.CUDA)
9867 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9868
9869 // The "previous declaration" for this function template specialization is
9870 // the prior function template specialization.
9871 Previous.clear();
9872 Previous.addDecl(Specialization);
9873 return false;
9874}
9875
9876bool
9878 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9879 "Only for non-template members");
9880
9881 // Try to find the member we are instantiating.
9882 NamedDecl *FoundInstantiation = nullptr;
9883 NamedDecl *Instantiation = nullptr;
9884 NamedDecl *InstantiatedFrom = nullptr;
9885 MemberSpecializationInfo *MSInfo = nullptr;
9886
9887 if (Previous.empty()) {
9888 // Nowhere to look anyway.
9889 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9890 UnresolvedSet<8> Candidates;
9891 for (NamedDecl *Candidate : Previous) {
9892 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9893 // Ignore any candidates that aren't member functions.
9894 if (!Method)
9895 continue;
9896
9897 QualType Adjusted = Function->getType();
9898 if (!hasExplicitCallingConv(Adjusted))
9899 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9900 // Ignore any candidates with the wrong type.
9901 // This doesn't handle deduced return types, but both function
9902 // declarations should be undeduced at this point.
9903 // FIXME: The exception specification should probably be ignored when
9904 // comparing the types.
9905 if (!Context.hasSameType(Adjusted, Method->getType()))
9906 continue;
9907
9908 // Ignore any candidates with unsatisfied constraints.
9909 if (ConstraintSatisfaction Satisfaction;
9910 Method->getTrailingRequiresClause() &&
9911 (CheckFunctionConstraints(Method, Satisfaction,
9912 /*UsageLoc=*/Member->getLocation(),
9913 /*ForOverloadResolution=*/true) ||
9914 !Satisfaction.IsSatisfied))
9915 continue;
9916
9917 Candidates.addDecl(Candidate);
9918 }
9919
9920 // If we have no viable candidates left after filtering, we are done.
9921 if (Candidates.empty())
9922 return false;
9923
9924 // Find the function that is more constrained than every other function it
9925 // has been compared to.
9926 UnresolvedSetIterator Best = Candidates.begin();
9927 CXXMethodDecl *BestMethod = nullptr;
9928 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9929 I != E; ++I) {
9930 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9931 if (I == Best ||
9932 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9933 Best = I;
9934 BestMethod = Method;
9935 }
9936 }
9937
9938 FoundInstantiation = *Best;
9939 Instantiation = BestMethod;
9940 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9941 MSInfo = BestMethod->getMemberSpecializationInfo();
9942
9943 // Make sure the best candidate is more constrained than all of the others.
9944 bool Ambiguous = false;
9945 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9946 I != E; ++I) {
9947 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9948 if (I != Best &&
9949 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9950 Ambiguous = true;
9951 break;
9952 }
9953 }
9954
9955 if (Ambiguous) {
9956 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9957 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9958 for (NamedDecl *Candidate : Candidates) {
9959 Candidate = Candidate->getUnderlyingDecl();
9960 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9961 << Candidate;
9962 }
9963 return true;
9964 }
9965 } else if (isa<VarDecl>(Member)) {
9966 VarDecl *PrevVar;
9967 if (Previous.isSingleResult() &&
9968 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9969 if (PrevVar->isStaticDataMember()) {
9970 FoundInstantiation = Previous.getRepresentativeDecl();
9971 Instantiation = PrevVar;
9972 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9973 MSInfo = PrevVar->getMemberSpecializationInfo();
9974 }
9975 } else if (isa<RecordDecl>(Member)) {
9976 CXXRecordDecl *PrevRecord;
9977 if (Previous.isSingleResult() &&
9978 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9979 FoundInstantiation = Previous.getRepresentativeDecl();
9980 Instantiation = PrevRecord;
9981 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9982 MSInfo = PrevRecord->getMemberSpecializationInfo();
9983 }
9984 } else if (isa<EnumDecl>(Member)) {
9985 EnumDecl *PrevEnum;
9986 if (Previous.isSingleResult() &&
9987 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9988 FoundInstantiation = Previous.getRepresentativeDecl();
9989 Instantiation = PrevEnum;
9990 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9991 MSInfo = PrevEnum->getMemberSpecializationInfo();
9992 }
9993 }
9994
9995 if (!Instantiation) {
9996 // There is no previous declaration that matches. Since member
9997 // specializations are always out-of-line, the caller will complain about
9998 // this mismatch later.
9999 return false;
10000 }
10001
10002 // A member specialization in a friend declaration isn't really declaring
10003 // an explicit specialization, just identifying a specific (possibly implicit)
10004 // specialization. Don't change the template specialization kind.
10005 //
10006 // FIXME: Is this really valid? Other compilers reject.
10007 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10008 // Preserve instantiation information.
10009 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10010 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10011 cast<CXXMethodDecl>(InstantiatedFrom),
10013 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10014 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10015 cast<CXXRecordDecl>(InstantiatedFrom),
10017 }
10018
10019 Previous.clear();
10020 Previous.addDecl(FoundInstantiation);
10021 return false;
10022 }
10023
10024 // Make sure that this is a specialization of a member.
10025 if (!InstantiatedFrom) {
10026 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10027 << Member;
10028 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10029 return true;
10030 }
10031
10032 // C++ [temp.expl.spec]p6:
10033 // If a template, a member template or the member of a class template is
10034 // explicitly specialized then that specialization shall be declared
10035 // before the first use of that specialization that would cause an implicit
10036 // instantiation to take place, in every translation unit in which such a
10037 // use occurs; no diagnostic is required.
10038 assert(MSInfo && "Member specialization info missing?");
10039
10040 bool HasNoEffect = false;
10043 Instantiation,
10045 MSInfo->getPointOfInstantiation(),
10046 HasNoEffect))
10047 return true;
10048
10049 // Check the scope of this explicit specialization.
10051 InstantiatedFrom,
10052 Instantiation, Member->getLocation(),
10053 false))
10054 return true;
10055
10056 // Note that this member specialization is an "instantiation of" the
10057 // corresponding member of the original template.
10058 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10059 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10060 if (InstantiationFunction->getTemplateSpecializationKind() ==
10062 // Explicit specializations of member functions of class templates do not
10063 // inherit '=delete' from the member function they are specializing.
10064 if (InstantiationFunction->isDeleted()) {
10065 // FIXME: This assert will not hold in the presence of modules.
10066 assert(InstantiationFunction->getCanonicalDecl() ==
10067 InstantiationFunction);
10068 // FIXME: We need an update record for this AST mutation.
10069 InstantiationFunction->setDeletedAsWritten(false);
10070 }
10071 }
10072
10073 MemberFunction->setInstantiationOfMemberFunction(
10075 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10076 MemberVar->setInstantiationOfStaticDataMember(
10077 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10078 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10079 MemberClass->setInstantiationOfMemberClass(
10081 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10082 MemberEnum->setInstantiationOfMemberEnum(
10083 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10084 } else {
10085 llvm_unreachable("unknown member specialization kind");
10086 }
10087
10088 // Save the caller the trouble of having to figure out which declaration
10089 // this specialization matches.
10090 Previous.clear();
10091 Previous.addDecl(FoundInstantiation);
10092 return false;
10093}
10094
10095/// Complete the explicit specialization of a member of a class template by
10096/// updating the instantiated member to be marked as an explicit specialization.
10097///
10098/// \param OrigD The member declaration instantiated from the template.
10099/// \param Loc The location of the explicit specialization of the member.
10100template<typename DeclT>
10101static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10102 SourceLocation Loc) {
10103 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10104 return;
10105
10106 // FIXME: Inform AST mutation listeners of this AST mutation.
10107 // FIXME: If there are multiple in-class declarations of the member (from
10108 // multiple modules, or a declaration and later definition of a member type),
10109 // should we update all of them?
10110 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10111 OrigD->setLocation(Loc);
10112}
10113
10116 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10117 if (Instantiation == Member)
10118 return;
10119
10120 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10121 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10122 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10123 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10124 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10125 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10126 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10127 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10128 else
10129 llvm_unreachable("unknown member specialization kind");
10130}
10131
10132/// Check the scope of an explicit instantiation.
10133///
10134/// \returns true if a serious error occurs, false otherwise.
10136 SourceLocation InstLoc,
10137 bool WasQualifiedName) {
10139 DeclContext *CurContext = S.CurContext->getRedeclContext();
10140
10141 if (CurContext->isRecord()) {
10142 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10143 << D;
10144 return true;
10145 }
10146
10147 // C++11 [temp.explicit]p3:
10148 // An explicit instantiation shall appear in an enclosing namespace of its
10149 // template. If the name declared in the explicit instantiation is an
10150 // unqualified name, the explicit instantiation shall appear in the
10151 // namespace where its template is declared or, if that namespace is inline
10152 // (7.3.1), any namespace from its enclosing namespace set.
10153 //
10154 // This is DR275, which we do not retroactively apply to C++98/03.
10155 if (WasQualifiedName) {
10156 if (CurContext->Encloses(OrigContext))
10157 return false;
10158 } else {
10159 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10160 return false;
10161 }
10162
10163 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10164 if (WasQualifiedName)
10165 S.Diag(InstLoc,
10166 S.getLangOpts().CPlusPlus11?
10167 diag::err_explicit_instantiation_out_of_scope :
10168 diag::warn_explicit_instantiation_out_of_scope_0x)
10169 << D << NS;
10170 else
10171 S.Diag(InstLoc,
10172 S.getLangOpts().CPlusPlus11?
10173 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10174 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10175 << D << NS;
10176 } else
10177 S.Diag(InstLoc,
10178 S.getLangOpts().CPlusPlus11?
10179 diag::err_explicit_instantiation_must_be_global :
10180 diag::warn_explicit_instantiation_must_be_global_0x)
10181 << D;
10182 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10183 return false;
10184}
10185
10186/// Common checks for whether an explicit instantiation of \p D is valid.
10188 SourceLocation InstLoc,
10189 bool WasQualifiedName,
10191 // C++ [temp.explicit]p13:
10192 // An explicit instantiation declaration shall not name a specialization of
10193 // a template with internal linkage.
10196 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10197 return true;
10198 }
10199
10200 // C++11 [temp.explicit]p3: [DR 275]
10201 // An explicit instantiation shall appear in an enclosing namespace of its
10202 // template.
10203 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10204 return true;
10205
10206 return false;
10207}
10208
10209/// Determine whether the given scope specifier has a template-id in it.
10211 // C++11 [temp.explicit]p3:
10212 // If the explicit instantiation is for a member function, a member class
10213 // or a static data member of a class template specialization, the name of
10214 // the class template specialization in the qualified-id for the member
10215 // name shall be a simple-template-id.
10216 //
10217 // C++98 has the same restriction, just worded differently.
10218 for (NestedNameSpecifier NNS = SS.getScopeRep();
10220 /**/) {
10221 const Type *T = NNS.getAsType();
10223 return true;
10224 NNS = T->getPrefix();
10225 }
10226 return false;
10227}
10228
10229/// Make a dllexport or dllimport attr on a class template specialization take
10230/// effect.
10233 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10234 assert(A && "dllExportImportClassTemplateSpecialization called "
10235 "on Def without dllexport or dllimport");
10236
10237 // We reject explicit instantiations in class scope, so there should
10238 // never be any delayed exported classes to worry about.
10239 assert(S.DelayedDllExportClasses.empty() &&
10240 "delayed exports present at explicit instantiation");
10242
10243 // Propagate attribute to base class templates.
10244 for (auto &B : Def->bases()) {
10245 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10246 B.getType()->getAsCXXRecordDecl()))
10248 }
10249
10251}
10252
10254 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10255 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10256 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10257 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10258 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10259 // Find the class template we're specializing
10260 TemplateName Name = TemplateD.get();
10261 TemplateDecl *TD = Name.getAsTemplateDecl();
10262 // Check that the specialization uses the same tag kind as the
10263 // original template.
10265 assert(Kind != TagTypeKind::Enum &&
10266 "Invalid enum tag in class template explicit instantiation!");
10267
10268 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10269
10270 if (!ClassTemplate) {
10271 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10272 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10273 Diag(TD->getLocation(), diag::note_previous_use);
10274 return true;
10275 }
10276
10277 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10278 Kind, /*isDefinition*/false, KWLoc,
10279 ClassTemplate->getIdentifier())) {
10280 Diag(KWLoc, diag::err_use_with_wrong_tag)
10281 << ClassTemplate
10283 ClassTemplate->getTemplatedDecl()->getKindName());
10284 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10285 diag::note_previous_use);
10286 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10287 }
10288
10289 // C++0x [temp.explicit]p2:
10290 // There are two forms of explicit instantiation: an explicit instantiation
10291 // definition and an explicit instantiation declaration. An explicit
10292 // instantiation declaration begins with the extern keyword. [...]
10293 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10296
10298 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10299 // Check for dllexport class template instantiation declarations,
10300 // except for MinGW mode.
10301 for (const ParsedAttr &AL : Attr) {
10302 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10303 Diag(ExternLoc,
10304 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10305 Diag(AL.getLoc(), diag::note_attribute);
10306 break;
10307 }
10308 }
10309
10310 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10311 Diag(ExternLoc,
10312 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10313 Diag(A->getLocation(), diag::note_attribute);
10314 }
10315 }
10316
10317 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10318 // instantiation declarations for most purposes.
10319 bool DLLImportExplicitInstantiationDef = false;
10321 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10322 // Check for dllimport class template instantiation definitions.
10323 bool DLLImport =
10324 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10325 for (const ParsedAttr &AL : Attr) {
10326 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10327 DLLImport = true;
10328 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10329 // dllexport trumps dllimport here.
10330 DLLImport = false;
10331 break;
10332 }
10333 }
10334 if (DLLImport) {
10336 DLLImportExplicitInstantiationDef = true;
10337 }
10338 }
10339
10340 // Translate the parser's template argument list in our AST format.
10341 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10342 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10343
10344 // Check that the template argument list is well-formed for this
10345 // template.
10347 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10348 /*DefaultArgs=*/{}, false, CTAI,
10349 /*UpdateArgsWithConversions=*/true,
10350 /*ConstraintsNotSatisfied=*/nullptr))
10351 return true;
10352
10353 // Find the class template specialization declaration that
10354 // corresponds to these arguments.
10355 llvm::FoldingSetInsertToken InsertToken;
10357 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
10358
10359 TemplateSpecializationKind PrevDecl_TSK
10360 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10361
10362 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10363 Context.getTargetInfo().getTriple().isOSCygMing()) {
10364 // Check for dllexport class template instantiation definitions in MinGW
10365 // mode, if a previous declaration of the instantiation was seen.
10366 for (const ParsedAttr &AL : Attr) {
10367 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10368 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10369 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10370 } else {
10371 Diag(AL.getLoc(),
10372 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10373 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10374 }
10375 break;
10376 }
10377 }
10378 }
10379
10380 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10381 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10382 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10383 return AL.getKind() == ParsedAttr::AT_DLLExport;
10384 })) {
10385 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10386 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10387 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10388 }
10389 }
10390
10391 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10392 SS.isSet(), TSK))
10393 return true;
10394
10396
10397 bool HasNoEffect = false;
10398 if (PrevDecl) {
10399 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10400 PrevDecl, PrevDecl_TSK,
10401 PrevDecl->getPointOfInstantiation(),
10402 HasNoEffect))
10403 return PrevDecl;
10404
10405 // Even though HasNoEffect == true means that this explicit instantiation
10406 // has no effect on semantics, we go on to put its syntax in the AST.
10407
10408 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10409 PrevDecl_TSK == TSK_Undeclared) {
10410 // Since the only prior class template specialization with these
10411 // arguments was referenced but not declared, reuse that
10412 // declaration node as our own, updating the source location
10413 // for the template name to reflect our new declaration.
10414 // (Other source locations will be updated later.)
10415 Specialization = PrevDecl;
10416 Specialization->setLocation(TemplateNameLoc);
10417 PrevDecl = nullptr;
10418 }
10419
10420 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10421 DLLImportExplicitInstantiationDef) {
10422 // The new specialization might add a dllimport attribute.
10423 HasNoEffect = false;
10424 }
10425 }
10426
10427 if (!Specialization) {
10428 // Create a new class template specialization declaration node for
10429 // this explicit specialization.
10431 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10432 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10434
10435 // A MSInheritanceAttr attached to the previous declaration must be
10436 // propagated to the new node prior to instantiation.
10437 if (PrevDecl) {
10438 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10439 auto *Clone = A->clone(getASTContext());
10440 Clone->setInherited(true);
10441 Specialization->addAttr(Clone);
10442 Consumer.AssignInheritanceModel(Specialization);
10443 }
10444 }
10445
10446 if (!HasNoEffect && !PrevDecl) {
10447 // Insert the new specialization.
10448 ClassTemplate->AddSpecialization(Specialization, InsertToken);
10449 }
10450 }
10451
10452 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10453
10454 // Set source locations for keywords.
10455 Specialization->setExternKeywordLoc(ExternLoc);
10456 Specialization->setTemplateKeywordLoc(TemplateLoc);
10457 Specialization->setBraceRange(SourceRange());
10458
10459 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10462
10463 // Add the explicit instantiation into its lexical context. However,
10464 // since explicit instantiations are never found by name lookup, we
10465 // just put it into the declaration context directly.
10466 Specialization->setLexicalDeclContext(CurContext);
10467 CurContext->addDecl(Specialization);
10468
10469 // Syntax is now OK, so return if it has no other effect on semantics.
10470 if (HasNoEffect) {
10471 // Set the template specialization kind.
10472 Specialization->setTemplateSpecializationKind(TSK);
10473
10475 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10476 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10477 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10478 Context.getCanonicalTagType(Specialization));
10480 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10481 TemplateNameLoc, TSI, TSK);
10482 return Specialization;
10483 }
10484
10485 // C++ [temp.explicit]p3:
10486 // A definition of a class template or class member template
10487 // shall be in scope at the point of the explicit instantiation of
10488 // the class template or class member template.
10489 //
10490 // This check comes when we actually try to perform the
10491 // instantiation.
10493 = cast_or_null<ClassTemplateSpecializationDecl>(
10494 Specialization->getDefinition());
10495 if (!Def)
10497 /*Complain=*/true,
10498 CTAI.StrictPackMatch);
10499 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10500 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10501 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10502 }
10503
10504 // Instantiate the members of this class template specialization.
10505 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10506 Specialization->getDefinition());
10507 if (Def) {
10509 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10510 // TSK_ExplicitInstantiationDefinition
10511 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10513 DLLImportExplicitInstantiationDef)) {
10514 // FIXME: Need to notify the ASTMutationListener that we did this.
10516
10517 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10518 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10519 // An explicit instantiation definition can add a dll attribute to a
10520 // template with a previous instantiation declaration. MinGW doesn't
10521 // allow this.
10522 auto *A = cast<InheritableAttr>(
10524 A->setInherited(true);
10525 Def->addAttr(A);
10527 }
10528 }
10529
10530 // Fix a TSK_ImplicitInstantiation followed by a
10531 // TSK_ExplicitInstantiationDefinition
10532 bool NewlyDLLExported =
10533 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10534 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10535 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10536 // An explicit instantiation definition can add a dll attribute to a
10537 // template with a previous implicit instantiation. MinGW doesn't allow
10538 // this. We limit clang to only adding dllexport, to avoid potentially
10539 // strange codegen behavior. For example, if we extend this conditional
10540 // to dllimport, and we have a source file calling a method on an
10541 // implicitly instantiated template class instance and then declaring a
10542 // dllimport explicit instantiation definition for the same template
10543 // class, the codegen for the method call will not respect the dllimport,
10544 // while it will with cl. The Def will already have the DLL attribute,
10545 // since the Def and Specialization will be the same in the case of
10546 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10547 // attribute to the Specialization; we just need to make it take effect.
10548 assert(Def == Specialization &&
10549 "Def and Specialization should match for implicit instantiation");
10551 }
10552
10553 // In MinGW mode, export the template instantiation if the declaration
10554 // was marked dllexport.
10555 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10556 Context.getTargetInfo().getTriple().isOSCygMing() &&
10557 PrevDecl->hasAttr<DLLExportAttr>()) {
10559 }
10560
10561 // Set the template specialization kind. Make sure it is set before
10562 // instantiating the members which will trigger ASTConsumer callbacks.
10563 Specialization->setTemplateSpecializationKind(TSK);
10564 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10565 } else {
10566
10567 // Set the template specialization kind.
10568 Specialization->setTemplateSpecializationKind(TSK);
10569 }
10570
10572 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10573 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10574 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10575 Context.getCanonicalTagType(Specialization));
10577 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10578 TemplateNameLoc, TSI, TSK);
10579 return Specialization;
10580}
10581
10584 SourceLocation TemplateLoc, unsigned TagSpec,
10585 SourceLocation KWLoc, CXXScopeSpec &SS,
10586 IdentifierInfo *Name, SourceLocation NameLoc,
10587 const ParsedAttributesView &Attr) {
10588
10589 bool Owned = false;
10590 bool IsDependent = false;
10591 Decl *TagD =
10592 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10593 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10594 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10595 false, TypeResult(), /*IsTypeSpecifier*/ false,
10596 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10597 .get();
10598 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10599
10600 if (!TagD)
10601 return true;
10602
10603 TagDecl *Tag = cast<TagDecl>(TagD);
10604 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10605
10606 if (Tag->isInvalidDecl())
10607 return true;
10608
10610 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10611 if (!Pattern) {
10612 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10613 << Context.getCanonicalTagType(Record);
10614 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10615 return true;
10616 }
10617
10618 // C++0x [temp.explicit]p2:
10619 // If the explicit instantiation is for a class or member class, the
10620 // elaborated-type-specifier in the declaration shall include a
10621 // simple-template-id.
10622 //
10623 // C++98 has the same restriction, just worded differently.
10625 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10626 << Record << SS.getRange();
10627
10628 // C++0x [temp.explicit]p2:
10629 // There are two forms of explicit instantiation: an explicit instantiation
10630 // definition and an explicit instantiation declaration. An explicit
10631 // instantiation declaration begins with the extern keyword. [...]
10635
10636 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10637
10638 // Verify that it is okay to explicitly instantiate here.
10639 CXXRecordDecl *PrevDecl
10640 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10641 if (!PrevDecl && Record->getDefinition())
10642 PrevDecl = Record;
10643 if (PrevDecl) {
10645 bool HasNoEffect = false;
10646 assert(MSInfo && "No member specialization information?");
10647 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10648 PrevDecl,
10650 MSInfo->getPointOfInstantiation(),
10651 HasNoEffect))
10652 return true;
10653 if (HasNoEffect) {
10657 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10658 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10659 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10660 TL.setElaboratedKeywordLoc(KWLoc);
10661 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10662 TL.setNameLoc(NameLoc);
10664 TemplateLoc, NestedNameSpecifierLoc(),
10665 nullptr, NameLoc, TSI, TSK);
10666 return TagD;
10667 }
10668 }
10669
10670 CXXRecordDecl *RecordDef
10671 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10672 if (!RecordDef) {
10673 // C++ [temp.explicit]p3:
10674 // A definition of a member class of a class template shall be in scope
10675 // at the point of an explicit instantiation of the member class.
10676 CXXRecordDecl *Def
10677 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10678 if (!Def) {
10679 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10680 << 0 << Record->getDeclName() << Record->getDeclContext();
10681 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10682 << Pattern;
10683 return true;
10684 } else {
10685 if (InstantiateClass(NameLoc, Record, Def,
10687 TSK))
10688 return true;
10689
10690 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10691 if (!RecordDef)
10692 return true;
10693 }
10694 }
10695
10696 // Instantiate all of the members of the class.
10697 InstantiateClassMembers(NameLoc, RecordDef,
10699
10701 MarkVTableUsed(NameLoc, RecordDef, true);
10702
10705 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10706 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10707 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10708 TL.setElaboratedKeywordLoc(KWLoc);
10709 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10710 TL.setNameLoc(NameLoc);
10712 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10713 NameLoc, TSI, TSK);
10714 return TagD;
10715}
10716
10718 SourceLocation ExternLoc,
10719 SourceLocation TemplateLoc,
10720 Declarator &D) {
10721 // Explicit instantiations always require a name.
10722 // TODO: check if/when DNInfo should replace Name.
10724 DeclarationName Name = NameInfo.getName();
10725 if (!Name) {
10726 if (!D.isInvalidType())
10728 diag::err_explicit_instantiation_requires_name)
10730
10731 return true;
10732 }
10733
10734 // Get the innermost enclosing declaration scope.
10735 S = S->getDeclParent();
10736
10737 // Determine the type of the declaration.
10739 QualType R = T->getType();
10740 if (R.isNull())
10741 return true;
10742
10743 // C++ [dcl.stc]p1:
10744 // A storage-class-specifier shall not be specified in [...] an explicit
10745 // instantiation (14.7.2) directive.
10747 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10748 << Name;
10749 return true;
10750 } else if (D.getDeclSpec().getStorageClassSpec()
10752 // Complain about then remove the storage class specifier.
10753 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10755
10757 }
10758
10759 // C++0x [temp.explicit]p1:
10760 // [...] An explicit instantiation of a function template shall not use the
10761 // inline or constexpr specifiers.
10762 // Presumably, this also applies to member functions of class templates as
10763 // well.
10767 diag::err_explicit_instantiation_inline :
10768 diag::warn_explicit_instantiation_inline_0x)
10770 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10771 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10772 // not already specified.
10774 diag::err_explicit_instantiation_constexpr);
10775
10776 // A deduction guide is not on the list of entities that can be explicitly
10777 // instantiated.
10779 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10780 << /*explicit instantiation*/ 0;
10781 return true;
10782 }
10783
10784 // C++0x [temp.explicit]p2:
10785 // There are two forms of explicit instantiation: an explicit instantiation
10786 // definition and an explicit instantiation declaration. An explicit
10787 // instantiation declaration begins with the extern keyword. [...]
10791
10792 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10794 /*ObjectType=*/QualType());
10795
10796 if (!R->isFunctionType()) {
10797 // C++ [temp.explicit]p1:
10798 // A [...] static data member of a class template can be explicitly
10799 // instantiated from the member definition associated with its class
10800 // template.
10801 // C++1y [temp.explicit]p1:
10802 // A [...] variable [...] template specialization can be explicitly
10803 // instantiated from its template.
10804 if (Previous.isAmbiguous())
10805 return true;
10806
10807 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10808 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10809 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10810
10811 if (!PrevTemplate) {
10812 if (!Prev || !Prev->isStaticDataMember()) {
10813 // We expect to see a static data member here.
10814 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10815 << Name;
10816 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10817 P != PEnd; ++P)
10818 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10819 return true;
10820 }
10821
10823 // FIXME: Check for explicit specialization?
10825 diag::err_explicit_instantiation_data_member_not_instantiated)
10826 << Prev;
10827 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10828 // FIXME: Can we provide a note showing where this was declared?
10829 return true;
10830 }
10831 } else {
10832 // Explicitly instantiate a variable template.
10833
10834 // C++1y [dcl.spec.auto]p6:
10835 // ... A program that uses auto or decltype(auto) in a context not
10836 // explicitly allowed in this section is ill-formed.
10837 //
10838 // This includes auto-typed variable template instantiations.
10839 if (R->isUndeducedType()) {
10840 Diag(T->getTypeLoc().getBeginLoc(),
10841 diag::err_auto_not_allowed_var_inst);
10842 return true;
10843 }
10844
10846 // C++1y [temp.explicit]p3:
10847 // If the explicit instantiation is for a variable, the unqualified-id
10848 // in the declaration shall be a template-id.
10850 diag::err_explicit_instantiation_without_template_id)
10851 << PrevTemplate;
10852 Diag(PrevTemplate->getLocation(),
10853 diag::note_explicit_instantiation_here);
10854 return true;
10855 }
10856
10857 // Translate the parser's template argument list into our AST format.
10858 TemplateArgumentListInfo TemplateArgs =
10860
10861 DeclResult Res =
10862 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10863 TemplateArgs, /*SetWrittenArgs=*/true);
10864 if (Res.isInvalid())
10865 return true;
10866
10867 if (!Res.isUsable()) {
10868 // We somehow specified dependent template arguments in an explicit
10869 // instantiation. This should probably only happen during error
10870 // recovery.
10871 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10872 return true;
10873 }
10874
10875 // Ignore access control bits, we don't need them for redeclaration
10876 // checking.
10877 Prev = cast<VarDecl>(Res.get());
10878 ArgsAsWritten =
10880 }
10881
10882 // C++0x [temp.explicit]p2:
10883 // If the explicit instantiation is for a member function, a member class
10884 // or a static data member of a class template specialization, the name of
10885 // the class template specialization in the qualified-id for the member
10886 // name shall be a simple-template-id.
10887 //
10888 // C++98 has the same restriction, just worded differently.
10889 //
10890 // This does not apply to variable template specializations, where the
10891 // template-id is in the unqualified-id instead.
10892 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10894 diag::ext_explicit_instantiation_without_qualified_id)
10895 << Prev << D.getCXXScopeSpec().getRange();
10896
10897 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10898
10899 // Verify that it is okay to explicitly instantiate here.
10902 bool HasNoEffect = false;
10904 PrevTSK, POI, HasNoEffect))
10905 return true;
10906
10907 if (!HasNoEffect) {
10908 // Instantiate static data member or variable template.
10910 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10911 VTSD->setExternKeywordLoc(ExternLoc);
10912 VTSD->setTemplateKeywordLoc(TemplateLoc);
10913 }
10914
10915 // Merge attributes.
10917 if (PrevTemplate)
10918 ProcessAPINotes(Prev);
10919
10922 }
10923
10924 // Check the new variable specialization against the parsed input.
10925 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10926 Diag(T->getTypeLoc().getBeginLoc(),
10927 diag::err_invalid_var_template_spec_type)
10928 << 0 << PrevTemplate << R << Prev->getType();
10929 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10930 << 2 << PrevTemplate->getDeclName();
10931 return true;
10932 }
10933
10935 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10936 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10937 D.getIdentifierLoc(), T, TSK);
10938 return (Decl *)nullptr;
10939 }
10940
10941 // If the declarator is a template-id, translate the parser's template
10942 // argument list into our AST format.
10943 bool HasExplicitTemplateArgs = false;
10944 TemplateArgumentListInfo TemplateArgs;
10946 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10947 HasExplicitTemplateArgs = true;
10948 }
10949
10950 // C++ [temp.explicit]p1:
10951 // A [...] function [...] can be explicitly instantiated from its template.
10952 // A member function [...] of a class template can be explicitly
10953 // instantiated from the member definition associated with its class
10954 // template.
10955 UnresolvedSet<8> TemplateMatches;
10956 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10958 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10959 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10960 P != PEnd; ++P) {
10961 NamedDecl *Prev = *P;
10962 if (!HasExplicitTemplateArgs) {
10963 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10964 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10965 /*AdjustExceptionSpec*/true);
10966 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10967 if (Method->getPrimaryTemplate()) {
10968 TemplateMatches.addDecl(Method, P.getAccess());
10969 } else {
10970 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10971 C.FoundDecl = P.getPair();
10972 C.Function = Method;
10973 C.Viable = true;
10975 if (Method->getTrailingRequiresClause() &&
10977 /*ForOverloadResolution=*/true) ||
10978 !S.IsSatisfied)) {
10979 C.Viable = false;
10981 }
10982 }
10983 }
10984 }
10985 }
10986
10987 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10988 if (!FunTmpl)
10989 continue;
10990
10991 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10992 FunctionDecl *Specialization = nullptr;
10994 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10995 Specialization, Info);
10997 // Keep track of almost-matches.
10998 FailedTemplateCandidates.addCandidate().set(
10999 P.getPair(), FunTmpl->getTemplatedDecl(),
11000 MakeDeductionFailureInfo(Context, TDK, Info));
11001 (void)TDK;
11002 continue;
11003 }
11004
11005 // Target attributes are part of the cuda function signature, so
11006 // the cuda target of the instantiated function must match that of its
11007 // template. Given that C++ template deduction does not take
11008 // target attributes into account, we reject candidates here that
11009 // have a different target.
11010 if (LangOpts.CUDA &&
11011 CUDA().IdentifyTarget(Specialization,
11012 /* IgnoreImplicitHDAttr = */ true) !=
11013 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11014 FailedTemplateCandidates.addCandidate().set(
11015 P.getPair(), FunTmpl->getTemplatedDecl(),
11018 continue;
11019 }
11020
11021 TemplateMatches.addDecl(Specialization, P.getAccess());
11022 }
11023
11024 FunctionDecl *Specialization = nullptr;
11025 if (!NonTemplateMatches.empty()) {
11026 unsigned Msg = 0;
11027 OverloadCandidateDisplayKind DisplayKind;
11029 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11030 Best)) {
11031 case OR_Success:
11032 case OR_Deleted:
11033 Specialization = cast<FunctionDecl>(Best->Function);
11034 break;
11035 case OR_Ambiguous:
11036 Msg = diag::err_explicit_instantiation_ambiguous;
11037 DisplayKind = OCD_AmbiguousCandidates;
11038 break;
11040 Msg = diag::err_explicit_instantiation_no_candidate;
11041 DisplayKind = OCD_AllCandidates;
11042 break;
11043 }
11044 if (Msg) {
11045 PartialDiagnostic Diag = PDiag(Msg) << Name;
11046 NonTemplateMatches.NoteCandidates(
11047 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11048 {});
11049 return true;
11050 }
11051 }
11052
11053 if (!Specialization) {
11054 // Find the most specialized function template specialization.
11056 TemplateMatches.begin(), TemplateMatches.end(),
11057 FailedTemplateCandidates, D.getIdentifierLoc(),
11058 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11059 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11060 PDiag(diag::note_explicit_instantiation_candidate));
11061
11062 if (Result == TemplateMatches.end())
11063 return true;
11064
11065 // Ignore access control bits, we don't need them for redeclaration checking.
11067 }
11068
11069 // C++11 [except.spec]p4
11070 // In an explicit instantiation an exception-specification may be specified,
11071 // but is not required.
11072 // If an exception-specification is specified in an explicit instantiation
11073 // directive, it shall be compatible with the exception-specifications of
11074 // other declarations of that function.
11075 if (auto *FPT = R->getAs<FunctionProtoType>())
11076 if (FPT->hasExceptionSpec()) {
11077 unsigned DiagID =
11078 diag::err_mismatched_exception_spec_explicit_instantiation;
11079 if (getLangOpts().MicrosoftExt)
11080 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11082 PDiag(DiagID) << Specialization->getType(),
11083 PDiag(diag::note_explicit_instantiation_here),
11084 Specialization->getType()->getAs<FunctionProtoType>(),
11085 Specialization->getLocation(), FPT, D.getBeginLoc());
11086 // In Microsoft mode, mismatching exception specifications just cause a
11087 // warning.
11088 if (!getLangOpts().MicrosoftExt && Result)
11089 return true;
11090 }
11091
11092 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11094 diag::err_explicit_instantiation_member_function_not_instantiated)
11096 << (Specialization->getTemplateSpecializationKind() ==
11098 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11099 return true;
11100 }
11101
11102 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11103 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11104 PrevDecl = Specialization;
11105
11106 if (PrevDecl) {
11107 bool HasNoEffect = false;
11109 PrevDecl,
11111 PrevDecl->getPointOfInstantiation(),
11112 HasNoEffect))
11113 return true;
11114
11115 if (HasNoEffect) {
11116 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11117 if (HasExplicitTemplateArgs)
11118 ArgsAsWritten =
11121 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11122 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11123 D.getIdentifierLoc(), T, TSK);
11124 return (Decl *)nullptr;
11125 }
11126 }
11127
11128 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11129 // functions
11130 // valarray<size_t>::valarray(size_t) and
11131 // valarray<size_t>::~valarray()
11132 // that it declared to have internal linkage with the internal_linkage
11133 // attribute. Ignore the explicit instantiation declaration in this case.
11134 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11136 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11137 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11138 RD->isInStdNamespace())
11139 return (Decl*) nullptr;
11140 }
11141
11144
11145 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11146 // instantiation declarations.
11148 Specialization->hasAttr<DLLImportAttr>() &&
11149 Context.getTargetInfo().getCXXABI().isMicrosoft())
11151
11152 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11153 if (Specialization->isDefined()) {
11154 // Let the ASTConsumer know that this function has been explicitly
11155 // instantiated now, and its linkage might have changed.
11156 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11157 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11158 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11159 // be explicitly instantiated.
11160 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11161 RD && RD->isLambda()) {
11162 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11163 << /*instantiation*/ 1;
11164 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11165 return (Decl *)nullptr;
11166 }
11168 }
11169
11170 // C++0x [temp.explicit]p2:
11171 // If the explicit instantiation is for a member function, a member class
11172 // or a static data member of a class template specialization, the name of
11173 // the class template specialization in the qualified-id for the member
11174 // name shall be a simple-template-id.
11175 //
11176 // C++98 has the same restriction, just worded differently.
11177 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11178 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11179 D.getCXXScopeSpec().isSet() &&
11182 diag::ext_explicit_instantiation_without_qualified_id)
11184
11186 *this,
11187 FunTmpl ? (NamedDecl *)FunTmpl
11188 : Specialization->getInstantiatedFromMemberFunction(),
11189 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11190
11191 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11192 if (HasExplicitTemplateArgs)
11193 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11195 TemplateLoc,
11197 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11198 return (Decl *)nullptr;
11199}
11200
11202 const CXXScopeSpec &SS,
11203 const IdentifierInfo *Name,
11204 SourceLocation TagLoc,
11205 SourceLocation NameLoc) {
11206 // This has to hold, because SS is expected to be defined.
11207 assert(Name && "Expected a name in a dependent tag");
11208
11210 if (!NNS)
11211 return true;
11212
11213 if (TUK == TagUseKind::Friend &&
11215 return true;
11216
11218
11219 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11220 Diag(NameLoc, diag::err_dependent_tag_decl)
11221 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11222 return true;
11223 }
11224
11225 // Create the resulting type.
11227 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11228
11229 // Create type-source location information for this type.
11230 TypeLocBuilder TLB;
11232 TL.setElaboratedKeywordLoc(TagLoc);
11234 TL.setNameLoc(NameLoc);
11236}
11237
11239 const CXXScopeSpec &SS,
11240 const IdentifierInfo &II,
11241 SourceLocation IdLoc,
11242 ImplicitTypenameContext IsImplicitTypename) {
11243 if (SS.isInvalid())
11244 return true;
11245
11246 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11247 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11248 << FixItHint::CreateRemoval(TypenameLoc);
11249
11251 TypeSourceInfo *TSI = nullptr;
11252 QualType T =
11255 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11256 /*DeducedTSTContext=*/true);
11257 if (T.isNull())
11258 return true;
11259 return CreateParsedType(T, TSI);
11260}
11261
11264 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11265 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11266 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11267 ASTTemplateArgsPtr TemplateArgsIn,
11268 SourceLocation RAngleLoc) {
11269 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11270 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11271 ? diag::compat_cxx11_typename_outside_of_template
11272 : diag::compat_pre_cxx11_typename_outside_of_template)
11273 << FixItHint::CreateRemoval(TypenameLoc);
11274
11275 // Strangely, non-type results are not ignored by this lookup, so the
11276 // program is ill-formed if it finds an injected-class-name.
11277 if (TypenameLoc.isValid()) {
11278 auto *LookupRD =
11279 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11280 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11281 Diag(TemplateIILoc,
11282 diag::ext_out_of_line_qualified_id_type_names_constructor)
11283 << TemplateII << 0 /*injected-class-name used as template name*/
11284 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11285 }
11286 }
11287
11288 // Translate the parser's template argument list in our AST format.
11289 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11290 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11291
11295 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11296 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11297 if (T.isNull())
11298 return true;
11299
11300 // Provide source-location information for the template specialization type.
11301 TypeLocBuilder Builder;
11303 = Builder.push<TemplateSpecializationTypeLoc>(T);
11304 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11305 TemplateIILoc, TemplateArgs);
11306 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11307 return CreateParsedType(T, TSI);
11308}
11309
11310/// Determine whether this failed name lookup should be treated as being
11311/// disabled by a usage of std::enable_if.
11313 SourceRange &CondRange, Expr *&Cond) {
11314 // We must be looking for a ::type...
11315 if (!II.isStr("type"))
11316 return false;
11317
11318 // ... within an explicitly-written template specialization...
11320 return false;
11321
11322 // FIXME: Look through sugar.
11323 auto EnableIfTSTLoc =
11325 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11326 return false;
11327 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11328
11329 // ... which names a complete class template declaration...
11330 const TemplateDecl *EnableIfDecl =
11331 EnableIfTST->getTemplateName().getAsTemplateDecl();
11332 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11333 return false;
11334
11335 // ... called "enable_if".
11336 const IdentifierInfo *EnableIfII =
11337 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11338 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11339 return false;
11340
11341 // Assume the first template argument is the condition.
11342 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11343
11344 // Dig out the condition.
11345 Cond = nullptr;
11346 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11348 return true;
11349
11350 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11351
11352 // Ignore Boolean literals; they add no value.
11354 Cond = nullptr;
11355
11356 return true;
11357}
11358
11361 SourceLocation KeywordLoc,
11362 NestedNameSpecifierLoc QualifierLoc,
11363 const IdentifierInfo &II,
11364 SourceLocation IILoc,
11365 TypeSourceInfo **TSI,
11366 bool DeducedTSTContext) {
11367 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11368 DeducedTSTContext);
11369 if (T.isNull())
11370 return QualType();
11371
11372 TypeLocBuilder TLB;
11374 auto TL = TLB.push<DependentNameTypeLoc>(T);
11375 TL.setElaboratedKeywordLoc(KeywordLoc);
11376 TL.setQualifierLoc(QualifierLoc);
11377 TL.setNameLoc(IILoc);
11380 TL.setElaboratedKeywordLoc(KeywordLoc);
11381 TL.setQualifierLoc(QualifierLoc);
11382 TL.setNameLoc(IILoc);
11383 } else if (isa<TemplateTypeParmType>(T)) {
11384 // FIXME: There might be a 'typename' keyword here, but we just drop it
11385 // as it can't be represented.
11386 assert(!QualifierLoc);
11387 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11388 } else if (isa<TagType>(T)) {
11389 auto TL = TLB.push<TagTypeLoc>(T);
11390 TL.setElaboratedKeywordLoc(KeywordLoc);
11391 TL.setQualifierLoc(QualifierLoc);
11392 TL.setNameLoc(IILoc);
11393 } else if (isa<TypedefType>(T)) {
11394 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11395 } else {
11396 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11397 }
11398 *TSI = TLB.getTypeSourceInfo(Context, T);
11399 return T;
11400}
11401
11402/// Build the type that describes a C++ typename specifier,
11403/// e.g., "typename T::type".
11406 SourceLocation KeywordLoc,
11407 NestedNameSpecifierLoc QualifierLoc,
11408 const IdentifierInfo &II,
11409 SourceLocation IILoc, bool DeducedTSTContext) {
11410 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11411
11412 CXXScopeSpec SS;
11413 SS.Adopt(QualifierLoc);
11414
11415 DeclContext *Ctx = nullptr;
11416 if (QualifierLoc) {
11417 Ctx = computeDeclContext(SS);
11418 if (!Ctx) {
11419 // If the nested-name-specifier is dependent and couldn't be
11420 // resolved to a type, build a typename type.
11421 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11422 return Context.getDependentNameType(Keyword,
11423 QualifierLoc.getNestedNameSpecifier(),
11424 &II);
11425 }
11426
11427 // If the nested-name-specifier refers to the current instantiation,
11428 // the "typename" keyword itself is superfluous. In C++03, the
11429 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11430 // allows such extraneous "typename" keywords, and we retroactively
11431 // apply this DR to C++03 code with only a warning. In any case we continue.
11432
11433 if (RequireCompleteDeclContext(SS, Ctx))
11434 return QualType();
11435 }
11436
11437 DeclarationName Name(&II);
11438 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11439 if (Ctx)
11440 LookupQualifiedName(Result, Ctx, SS);
11441 else
11442 LookupName(Result, CurScope);
11443 unsigned DiagID = 0;
11444 Decl *Referenced = nullptr;
11445 switch (Result.getResultKind()) {
11447 // If we're looking up 'type' within a template named 'enable_if', produce
11448 // a more specific diagnostic.
11449 SourceRange CondRange;
11450 Expr *Cond = nullptr;
11451 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11452 // If we have a condition, narrow it down to the specific failed
11453 // condition.
11454 if (Cond) {
11455 Expr *FailedCond;
11456 std::string FailedDescription;
11457 std::tie(FailedCond, FailedDescription) =
11459
11460 Diag(FailedCond->getExprLoc(),
11461 diag::err_typename_nested_not_found_requirement)
11462 << FailedDescription
11463 << FailedCond->getSourceRange();
11464 return QualType();
11465 }
11466
11467 Diag(CondRange.getBegin(),
11468 diag::err_typename_nested_not_found_enable_if)
11469 << Ctx << CondRange;
11470 return QualType();
11471 }
11472
11473 DiagID = Ctx ? diag::err_typename_nested_not_found
11474 : diag::err_unknown_typename;
11475 break;
11476 }
11477
11479 // We found a using declaration that is a value. Most likely, the using
11480 // declaration itself is meant to have the 'typename' keyword.
11481 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11482 IILoc);
11483 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11484 << Name << Ctx << FullRange;
11485 if (UnresolvedUsingValueDecl *Using
11486 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11487 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11488 Diag(Loc, diag::note_using_value_decl_missing_typename)
11489 << FixItHint::CreateInsertion(Loc, "typename ");
11490 }
11491 }
11492 // Fall through to create a dependent typename type, from which we can
11493 // recover better.
11494 [[fallthrough]];
11495
11497 // Okay, it's a member of an unknown instantiation.
11498 return Context.getDependentNameType(Keyword,
11499 QualifierLoc.getNestedNameSpecifier(),
11500 &II);
11501
11503 // FXIME: Missing support for UsingShadowDecl on this path?
11504 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11505 // C++ [class.qual]p2:
11506 // In a lookup in which function names are not ignored and the
11507 // nested-name-specifier nominates a class C, if the name specified
11508 // after the nested-name-specifier, when looked up in C, is the
11509 // injected-class-name of C [...] then the name is instead considered
11510 // to name the constructor of class C.
11511 //
11512 // Unlike in an elaborated-type-specifier, function names are not ignored
11513 // in typename-specifier lookup. However, they are ignored in all the
11514 // contexts where we form a typename type with no keyword (that is, in
11515 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11516 //
11517 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11518 // ignore functions, but that appears to be an oversight.
11523 Type, IILoc);
11524 // FIXME: This appears to be the only case where a template type parameter
11525 // can have an elaborated keyword. We should preserve it somehow.
11528 assert(!QualifierLoc);
11530 }
11531 return Context.getTypeDeclType(
11532 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11533 }
11534
11535 // C++ [dcl.type.simple]p2:
11536 // A type-specifier of the form
11537 // typename[opt] nested-name-specifier[opt] template-name
11538 // is a placeholder for a deduced class type [...].
11539 if (getLangOpts().CPlusPlus17) {
11540 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11541 if (!DeducedTSTContext) {
11542 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11543 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11544 Diag(IILoc, diag::err_dependent_deduced_tst)
11546 << QualType(Qualifier.getAsType(), 0);
11547 else
11548 Diag(IILoc, diag::err_deduced_tst)
11551 return QualType();
11552 }
11553 TemplateName Name = Context.getQualifiedTemplateName(
11554 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11555 TemplateName(TD));
11556 return Context.getDeducedTemplateSpecializationType(
11557 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11558 Name);
11559 }
11560 }
11561
11562 DiagID = Ctx ? diag::err_typename_nested_not_type
11563 : diag::err_typename_not_type;
11564 Referenced = Result.getFoundDecl();
11565 break;
11566
11568 DiagID = Ctx ? diag::err_typename_nested_not_type
11569 : diag::err_typename_not_type;
11570 Referenced = *Result.begin();
11571 break;
11572
11574 return QualType();
11575 }
11576
11577 // If we get here, it's because name lookup did not find a
11578 // type. Emit an appropriate diagnostic and return an error.
11579 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11580 IILoc);
11581 if (Ctx)
11582 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11583 else
11584 Diag(IILoc, DiagID) << FullRange << Name;
11585 if (Referenced)
11586 Diag(Referenced->getLocation(),
11587 Ctx ? diag::note_typename_member_refers_here
11588 : diag::note_typename_refers_here)
11589 << Name;
11590 return QualType();
11591}
11592
11593namespace {
11594 // See Sema::RebuildTypeInCurrentInstantiation
11595 class CurrentInstantiationRebuilder
11596 : public TreeTransform<CurrentInstantiationRebuilder> {
11597 SourceLocation Loc;
11598 DeclarationName Entity;
11599
11600 public:
11602
11603 CurrentInstantiationRebuilder(Sema &SemaRef,
11604 SourceLocation Loc,
11605 DeclarationName Entity)
11606 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11607 Loc(Loc), Entity(Entity) { }
11608
11609 /// Determine whether the given type \p T has already been
11610 /// transformed.
11611 ///
11612 /// For the purposes of type reconstruction, a type has already been
11613 /// transformed if it is NULL or if it is not dependent.
11614 bool AlreadyTransformed(QualType T) {
11615 return T.isNull() || !T->isInstantiationDependentType();
11616 }
11617
11618 /// Returns the location of the entity whose type is being
11619 /// rebuilt.
11620 SourceLocation getBaseLocation() { return Loc; }
11621
11622 /// Returns the name of the entity whose type is being rebuilt.
11623 DeclarationName getBaseEntity() { return Entity; }
11624
11625 /// Sets the "base" location and entity when that
11626 /// information is known based on another transformation.
11627 void setBase(SourceLocation Loc, DeclarationName Entity) {
11628 this->Loc = Loc;
11629 this->Entity = Entity;
11630 }
11631
11632 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11633 // Lambdas never need to be transformed.
11634 return E;
11635 }
11636 };
11637} // end anonymous namespace
11638
11640 SourceLocation Loc,
11641 DeclarationName Name) {
11642 if (!T || !T->getType()->isInstantiationDependentType())
11643 return T;
11644
11645 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11646 return Rebuilder.TransformType(T);
11647}
11648
11650 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11651 DeclarationName());
11652 return Rebuilder.TransformExpr(E);
11653}
11654
11656 if (SS.isInvalid())
11657 return true;
11658
11660 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11661 DeclarationName());
11663 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11664 if (!Rebuilt)
11665 return true;
11666
11667 SS.Adopt(Rebuilt);
11668 return false;
11669}
11670
11672 TemplateParameterList *Params) {
11673 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11674 Decl *Param = Params->getParam(I);
11675
11676 // There is nothing to rebuild in a type parameter.
11677 if (isa<TemplateTypeParmDecl>(Param))
11678 continue;
11679
11680 // Rebuild the template parameter list of a template template parameter.
11682 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11684 TTP->getTemplateParameters()))
11685 return true;
11686
11687 continue;
11688 }
11689
11690 // Rebuild the type of a non-type template parameter.
11692 TypeSourceInfo *NewTSI
11694 NTTP->getLocation(),
11695 NTTP->getDeclName());
11696 if (!NewTSI)
11697 return true;
11698
11699 if (NewTSI->getType()->isUndeducedType()) {
11700 // C++17 [temp.dep.expr]p3:
11701 // An id-expression is type-dependent if it contains
11702 // - an identifier associated by name lookup with a non-type
11703 // template-parameter declared with a type that contains a
11704 // placeholder type (7.1.7.4),
11705 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11706 }
11707
11708 if (NewTSI != NTTP->getTypeSourceInfo()) {
11709 NTTP->setTypeSourceInfo(NewTSI);
11710 NTTP->setType(NewTSI->getType());
11711 }
11712 }
11713
11714 return false;
11715}
11716
11717std::string
11719 const TemplateArgumentList &Args) {
11720 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11721}
11722
11723std::string
11725 const TemplateArgument *Args,
11726 unsigned NumArgs) {
11727 SmallString<128> Str;
11728 llvm::raw_svector_ostream Out(Str);
11729
11730 if (!Params || Params->size() == 0 || NumArgs == 0)
11731 return std::string();
11732
11733 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11734 if (I >= NumArgs)
11735 break;
11736
11737 if (I == 0)
11738 Out << "[with ";
11739 else
11740 Out << ", ";
11741
11742 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11743 Out << Id->getName();
11744 } else {
11745 Out << '$' << I;
11746 }
11747
11748 Out << " = ";
11749 Args[I].print(getPrintingPolicy(), Out,
11751 getPrintingPolicy(), Params, I));
11752 }
11753
11754 Out << ']';
11755 return std::string(Out.str());
11756}
11757
11759 CachedTokens &Toks) {
11760 if (!FD)
11761 return;
11762
11763 auto LPT = std::make_unique<LateParsedTemplate>();
11764
11765 // Take tokens to avoid allocations
11766 LPT->Toks.swap(Toks);
11767 LPT->D = FnD;
11768 LPT->FPO = getCurFPFeatures();
11769 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11770
11771 FD->setLateTemplateParsed(true);
11772}
11773
11775 if (!FD)
11776 return;
11777 FD->setLateTemplateParsed(false);
11778}
11779
11781 DeclContext *DC = CurContext;
11782
11783 while (DC) {
11784 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11785 const FunctionDecl *FD = RD->isLocalClass();
11786 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11787 } else if (DC->isTranslationUnit() || DC->isNamespace())
11788 return false;
11789
11790 DC = DC->getParent();
11791 }
11792 return false;
11793}
11794
11795namespace {
11796/// Walk the path from which a declaration was instantiated, and check
11797/// that every explicit specialization along that path is visible. This enforces
11798/// C++ [temp.expl.spec]/6:
11799///
11800/// If a template, a member template or a member of a class template is
11801/// explicitly specialized then that specialization shall be declared before
11802/// the first use of that specialization that would cause an implicit
11803/// instantiation to take place, in every translation unit in which such a
11804/// use occurs; no diagnostic is required.
11805///
11806/// and also C++ [temp.class.spec]/1:
11807///
11808/// A partial specialization shall be declared before the first use of a
11809/// class template specialization that would make use of the partial
11810/// specialization as the result of an implicit or explicit instantiation
11811/// in every translation unit in which such a use occurs; no diagnostic is
11812/// required.
11813class ExplicitSpecializationVisibilityChecker {
11814 Sema &S;
11815 SourceLocation Loc;
11818
11819public:
11820 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11822 : S(S), Loc(Loc), Kind(Kind) {}
11823
11824 void check(NamedDecl *ND) {
11825 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11826 return checkImpl(FD);
11827 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11828 return checkImpl(RD);
11829 if (auto *VD = dyn_cast<VarDecl>(ND))
11830 return checkImpl(VD);
11831 if (auto *ED = dyn_cast<EnumDecl>(ND))
11832 return checkImpl(ED);
11833 }
11834
11835private:
11836 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11837 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11838 : Sema::MissingImportKind::ExplicitSpecialization;
11839 const bool Recover = true;
11840
11841 // If we got a custom set of modules (because only a subset of the
11842 // declarations are interesting), use them, otherwise let
11843 // diagnoseMissingImport intelligently pick some.
11844 if (Modules.empty())
11845 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11846 else
11847 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11848 }
11849
11850 bool CheckMemberSpecialization(const NamedDecl *D) {
11851 return Kind == Sema::AcceptableKind::Visible
11854 }
11855
11856 bool CheckExplicitSpecialization(const NamedDecl *D) {
11857 return Kind == Sema::AcceptableKind::Visible
11860 }
11861
11862 bool CheckDeclaration(const NamedDecl *D) {
11863 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11865 }
11866
11867 // Check a specific declaration. There are three problematic cases:
11868 //
11869 // 1) The declaration is an explicit specialization of a template
11870 // specialization.
11871 // 2) The declaration is an explicit specialization of a member of an
11872 // templated class.
11873 // 3) The declaration is an instantiation of a template, and that template
11874 // is an explicit specialization of a member of a templated class.
11875 //
11876 // We don't need to go any deeper than that, as the instantiation of the
11877 // surrounding class / etc is not triggered by whatever triggered this
11878 // instantiation, and thus should be checked elsewhere.
11879 template<typename SpecDecl>
11880 void checkImpl(SpecDecl *Spec) {
11881 bool IsHiddenExplicitSpecialization = false;
11882 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11883 // Some invalid friend declarations are written as specializations but are
11884 // instantiated implicitly.
11885 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11886 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11887 if (SpecKind == TSK_ExplicitSpecialization) {
11888 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11889 ? !CheckMemberSpecialization(Spec)
11890 : !CheckExplicitSpecialization(Spec);
11891 } else {
11892 checkInstantiated(Spec);
11893 }
11894
11895 if (IsHiddenExplicitSpecialization)
11896 diagnose(Spec->getMostRecentDecl(), false);
11897 }
11898
11899 void checkInstantiated(FunctionDecl *FD) {
11900 if (auto *TD = FD->getPrimaryTemplate())
11901 checkTemplate(TD);
11902 }
11903
11904 void checkInstantiated(CXXRecordDecl *RD) {
11905 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11906 if (!SD)
11907 return;
11908
11909 auto From = SD->getSpecializedTemplateOrPartial();
11910 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11911 checkTemplate(TD);
11912 else if (auto *TD =
11913 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11914 if (!CheckDeclaration(TD))
11915 diagnose(TD, true);
11916 checkTemplate(TD);
11917 }
11918 }
11919
11920 void checkInstantiated(VarDecl *RD) {
11921 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11922 if (!SD)
11923 return;
11924
11925 auto From = SD->getSpecializedTemplateOrPartial();
11926 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11927 checkTemplate(TD);
11928 else if (auto *TD =
11929 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11930 if (!CheckDeclaration(TD))
11931 diagnose(TD, true);
11932 checkTemplate(TD);
11933 }
11934 }
11935
11936 void checkInstantiated(EnumDecl *FD) {}
11937
11938 template<typename TemplDecl>
11939 void checkTemplate(TemplDecl *TD) {
11940 if (TD->isMemberSpecialization()) {
11941 if (!CheckMemberSpecialization(TD))
11942 diagnose(TD->getMostRecentDecl(), false);
11943 }
11944 }
11945};
11946} // end anonymous namespace
11947
11949 if (!getLangOpts().Modules)
11950 return;
11951
11952 ExplicitSpecializationVisibilityChecker(*this, Loc,
11954 .check(Spec);
11955}
11956
11958 NamedDecl *Spec) {
11959 if (!getLangOpts().CPlusPlusModules)
11960 return checkSpecializationVisibility(Loc, Spec);
11961
11962 ExplicitSpecializationVisibilityChecker(*this, Loc,
11964 .check(Spec);
11965}
11966
11969 return N->getLocation();
11970 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11972 return FD->getLocation();
11975 return N->getLocation();
11976 }
11977 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11978 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11979 continue;
11980 return CSC.PointOfInstantiation;
11981 }
11982 return N->getLocation();
11983}
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 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 ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
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:239
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
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:3970
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
TemplateName getNamedConcept() const
Definition TypeLoc.h:2466
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8276
Pointer to a block type.
Definition TypeBase.h:3633
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:2135
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:3923
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:2149
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, TemplateName 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:3838
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:4465
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:1290
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1391
ValueDecl * getDecl()
Definition Expr.h:1358
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:815
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:838
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
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:4139
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:3563
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:4089
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4179
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4551
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:4305
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4146
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4418
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5218
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:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:847
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:3103
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:4104
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:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4345
Represents a member of a struct/union/class.
Definition Decl.h:3295
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:2059
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4246
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4575
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4354
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4213
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3791
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4185
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:4419
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2489
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4458
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3158
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4206
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4963
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5674
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5670
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:4921
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:3897
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3987
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5352
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:3695
Represents a linkage specification.
Definition DeclCXX.h:3044
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:4432
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3731
QualType getPointeeType() const
Definition TypeBase.h:3749
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1684
NamedDecl * getMostRecentDecl()
Definition Decl.h:502
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
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:1946
Represent a C++ namespace.
Definition Decl.h:593
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:8003
Represents a pointer to an Objective C object.
Definition TypeBase.h:8059
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:1198
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:1428
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:4416
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:2226
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:8247
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
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:8507
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:8418
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:8603
QualType getCanonicalType() const
Definition TypeBase.h:8470
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8512
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:3713
Represents a struct/union/class.
Definition Decl.h:4460
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5465
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3658
QualType getPointeeType() const
Definition TypeBase.h:3680
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:13760
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8476
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
Whether and why a template name is required in this lookup.
Definition Sema.h:11491
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11499
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12549
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12583
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7746
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13707
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13158
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2701
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9366
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9370
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9373
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:9682
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:1471
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:4215
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:2079
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:11462
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12060
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12063
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12067
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:1304
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:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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...
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:935
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:1208
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:12239
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12257
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12247
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12267
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:11512
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11519
@ None
This is not assumed to be a template name.
Definition Sema.h:11514
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11516
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:11448
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:930
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:14554
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14542
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14551
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14545
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14569
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:1303
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:1302
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:648
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:1444
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 CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
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...
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:13798
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:15594
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.
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
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:1305
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:4720
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:6766
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6745
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:14065
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs, bool SetWrittenArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
@ TemplateNameIsRequired
Definition Sema.h:11489
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:524
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:11672
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11682
@ TPC_FriendFunctionTemplate
Definition Sema.h:11680
@ TPC_ClassTemplateMember
Definition Sema.h:11678
@ TPC_FunctionTemplate
Definition Sema.h:11677
@ TPC_FriendClassTemplate
Definition Sema.h:11679
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11681
friend class InitializationSequence
Definition Sema.h:1586
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)
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
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:6369
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:6453
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1296
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:3525
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11454
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:9691
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13001
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:8689
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13795
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:4717
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
StringRef getKindName() const
Definition Decl.h:4048
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4970
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5106
TagKind getTagKind() const
Definition Decl.h:4052
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...
TemplateTemplateParmDecl * getAsTemplateTemplateParmDecl() const
Retrieve the template template parameter that this template name refers to, if any.
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:3823
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:3648
const Type * getTypeForDecl() const
Definition Decl.h:3673
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
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:6295
A container of type source information.
Definition TypeBase.h:8389
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:8400
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:9164
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:8687
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8754
bool isPointerType() const
Definition TypeBase.h:8655
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
bool isReferenceType() const
Definition TypeBase.h:8679
bool isEnumeralType() const
Definition TypeBase.h:8786
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:9149
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8842
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:8683
bool isBitIntType() const
Definition TypeBase.h:8930
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8778
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:8736
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:9170
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:5039
bool isPointerOrReferenceType() const
Definition TypeBase.h:8659
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:8651
bool isVectorType() const
Definition TypeBase.h:8794
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:9254
bool isNullPtrType() const
Definition TypeBase.h:9064
bool isRecordType() const
Definition TypeBase.h:8782
QualType getUnderlyingType() const
Definition Decl.h:3752
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4209
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:2288
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:6100
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3969
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3428
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3492
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
TLSKind getTLSKind() const
Definition Decl.cpp:2150
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2744
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:2879
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:2772
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:2751
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2870
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:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4253
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:824
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:598
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
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)
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ 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:445
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6008
@ Enum
The "enum" keyword.
Definition TypeBase.h:6022
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:556
@ Type
The name was classified as a type.
Definition Sema.h:558
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:374
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
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:835
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
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:5983
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6004
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5997
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6001
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:1623
#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:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:625
Extra information about a function prototype.
Definition TypeBase.h:5470
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:12098
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12094
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12087
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12084
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12084
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13209
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13313
A stack object to be created when performing template instantiation.
Definition Sema.h:13403
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13556
NamedDecl * Previous
Definition Sema.h:361
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