clang 23.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/Template.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
146 return D;
147
148 return nullptr;
149}
150
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
242 if (isa<FunctionTemplateDecl>(FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
280 R.suppressDiagnostics();
281 } else {
282 if (!D) {
283 D = getAsTemplateNameDecl(*R.begin());
284 assert(D && "unambiguous result is not a template name");
285 }
286
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
300 Template);
301 }
302
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
307 R.suppressDiagnostics();
308 } else {
312 TemplateKind =
314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
318 }
319 }
320
322 S->getTemplateParamParent() == nullptr)
323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(Template);
328 return TemplateKind;
329}
330
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
345 R.suppressDiagnostics();
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
352 if (!TD || !getAsTypeTemplateDecl(TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
358 *Template = TemplateTy::make(Name);
359 }
360 return true;
361}
362
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(IILoc, diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(IILoc, "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
391 bool AllowTypoCorrection) {
392 if (ATK)
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
412 "Caller should have completed object type");
413
414 // Template names cannot appear inside an Objective-C class or object type
415 // or a vector type.
416 //
417 // FIXME: This is wrong. For example:
418 //
419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
420 // Vec<int> vi;
421 // vi.Vec<int>::~Vec<int>();
422 //
423 // ... should be accepted but we will not treat 'Vec' as a template name
424 // here. The right thing to do would be to check if the name is a valid
425 // vector component name, and look up a template name if not. And similarly
426 // for lookups into Objective-C class and object types, where the same
427 // problem can arise.
428 if (ObjectType->isObjCObjectOrInterfaceType() ||
429 ObjectType->isVectorType()) {
430 Found.clear();
431 return false;
432 }
433 } else if (SS.isNotEmpty()) {
434 // This nested-name-specifier occurs after another nested-name-specifier,
435 // so long into the context associated with the prior nested-name-specifier.
436 LookupCtx = computeDeclContext(SS, EnteringContext);
437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
438
439 // The declaration context must be complete.
440 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
441 return true;
442 }
443
444 bool ObjectTypeSearchedInScope = false;
445 bool AllowFunctionTemplatesInLookup = true;
446 if (LookupCtx) {
447 // Perform "qualified" name lookup into the declaration context we
448 // computed, which is either the type of the base of a member access
449 // expression or the declaration context associated with a prior
450 // nested-name-specifier.
451 LookupQualifiedName(Found, LookupCtx);
452
453 // FIXME: The C++ standard does not clearly specify what happens in the
454 // case where the object type is dependent, and implementations vary. In
455 // Clang, we treat a name after a . or -> as a template-name if lookup
456 // finds a non-dependent member or member of the current instantiation that
457 // is a type template, or finds no such members and lookup in the context
458 // of the postfix-expression finds a type template. In the latter case, the
459 // name is nonetheless dependent, and we may resolve it to a member of an
460 // unknown specialization when we come to instantiate the template.
461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
462 }
463
464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
465 // C++ [basic.lookup.classref]p1:
466 // In a class member access expression (5.2.5), if the . or -> token is
467 // immediately followed by an identifier followed by a <, the
468 // identifier must be looked up to determine whether the < is the
469 // beginning of a template argument list (14.2) or a less-than operator.
470 // The identifier is first looked up in the class of the object
471 // expression. If the identifier is not found, it is then looked up in
472 // the context of the entire postfix-expression and shall name a class
473 // template.
474 if (S)
475 LookupName(Found, S);
476
477 if (!ObjectType.isNull()) {
478 // FIXME: We should filter out all non-type templates here, particularly
479 // variable templates and concepts. But the exclusion of alias templates
480 // and template template parameters is a wording defect.
481 AllowFunctionTemplatesInLookup = false;
482 ObjectTypeSearchedInScope = true;
483 }
484
485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
486 }
487
488 if (Found.isAmbiguous())
489 return false;
490
491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
492 !RequiredTemplate.hasTemplateKeyword()) {
493 // C++2a [temp.names]p2:
494 // A name is also considered to refer to a template if it is an
495 // unqualified-id followed by a < and name lookup finds either one or more
496 // functions or finds nothing.
497 //
498 // To keep our behavior consistent, we apply the "finds nothing" part in
499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
500 // successfully form a call to an undeclared template-id.
501 bool AllFunctions =
502 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
504 });
505 if (AllFunctions || (Found.empty() && !IsDependent)) {
506 // If lookup found any functions, or if this is a name that can only be
507 // used for a function, then strongly assume this is a function
508 // template-id.
509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
512 Found.clear();
513 return false;
514 }
515 }
516
517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
518 // If we did not find any names, and this is not a disambiguation, attempt
519 // to correct any typos.
520 DeclarationName Name = Found.getLookupName();
521 Found.clear();
522 QualifiedLookupValidatorCCC FilterCCC(!SS.isEmpty());
523 FilterCCC.WantTypeSpecifiers = false;
524 FilterCCC.WantExpressionKeywords = false;
525 FilterCCC.WantRemainingKeywords = false;
526 FilterCCC.WantCXXNamedCasts = true;
527 if (TypoCorrection Corrected = CorrectTypo(
528 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
529 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
530 if (auto *ND = Corrected.getFoundDecl())
531 Found.addDecl(ND);
533 if (Found.isAmbiguous()) {
534 Found.clear();
535 } else if (!Found.empty()) {
536 // Do not erase the typo-corrected result to avoid duplicated
537 // diagnostics.
538 AllowFunctionTemplatesInLookup = true;
539 Found.setLookupName(Corrected.getCorrection());
540 if (LookupCtx) {
541 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
542 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543 Name.getAsString() == CorrectedStr;
544 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
545 << Name << LookupCtx << DroppedSpecifier
546 << SS.getRange());
547 } else {
548 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
549 }
550 }
551 }
552 }
553
554 NamedDecl *ExampleLookupResult =
555 Found.empty() ? nullptr : Found.getRepresentativeDecl();
556 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
557 if (Found.empty()) {
558 if (IsDependent) {
559 Found.setNotFoundInCurrentInstantiation();
560 return false;
561 }
562
563 // If a 'template' keyword was used, a lookup that finds only non-template
564 // names is an error.
565 if (ExampleLookupResult && RequiredTemplate) {
566 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
567 << Found.getLookupName() << SS.getRange()
568 << RequiredTemplate.hasTemplateKeyword()
569 << RequiredTemplate.getTemplateKeywordLoc();
570 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
571 diag::note_template_kw_refers_to_non_template)
572 << Found.getLookupName();
573 return true;
574 }
575
576 return false;
577 }
578
579 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
581 // C++03 [basic.lookup.classref]p1:
582 // [...] If the lookup in the class of the object expression finds a
583 // template, the name is also looked up in the context of the entire
584 // postfix-expression and [...]
585 //
586 // Note: C++11 does not perform this second lookup.
587 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
589 FoundOuter.setTemplateNameLookup(true);
590 LookupName(FoundOuter, S);
591 // FIXME: We silently accept an ambiguous lookup here, in violation of
592 // [basic.lookup]/1.
593 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
594
595 NamedDecl *OuterTemplate;
596 if (FoundOuter.empty()) {
597 // - if the name is not found, the name found in the class of the
598 // object expression is used, otherwise
599 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
600 !(OuterTemplate =
601 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
602 // - if the name is found in the context of the entire
603 // postfix-expression and does not name a class template, the name
604 // found in the class of the object expression is used, otherwise
605 FoundOuter.clear();
606 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
607 // - if the name found is a class template, it must refer to the same
608 // entity as the one found in the class of the object expression,
609 // otherwise the program is ill-formed.
610 if (!Found.isSingleResult() ||
611 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
612 OuterTemplate->getCanonicalDecl()) {
613 Diag(Found.getNameLoc(),
614 diag::ext_nested_name_member_ref_lookup_ambiguous)
615 << Found.getLookupName()
616 << ObjectType;
617 Diag(Found.getRepresentativeDecl()->getLocation(),
618 diag::note_ambig_member_ref_object_type)
619 << ObjectType;
620 Diag(FoundOuter.getFoundDecl()->getLocation(),
621 diag::note_ambig_member_ref_scope);
622
623 // Recover by taking the template that we found in the object
624 // expression's type.
625 }
626 }
627 }
628
629 return false;
630}
631
635 if (TemplateName.isInvalid())
636 return;
637
638 DeclarationNameInfo NameInfo;
639 CXXScopeSpec SS;
640 LookupNameKind LookupKind;
641
642 DeclContext *LookupCtx = nullptr;
643 NamedDecl *Found = nullptr;
644 bool MissingTemplateKeyword = false;
645
646 // Figure out what name we looked up.
647 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
648 NameInfo = DRE->getNameInfo();
649 SS.Adopt(DRE->getQualifierLoc());
650 LookupKind = LookupOrdinaryName;
651 Found = DRE->getFoundDecl();
652 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
653 NameInfo = ME->getMemberNameInfo();
654 SS.Adopt(ME->getQualifierLoc());
655 LookupKind = LookupMemberName;
656 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
657 Found = ME->getMemberDecl();
658 } else if (auto *DSDRE =
659 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
660 NameInfo = DSDRE->getNameInfo();
661 SS.Adopt(DSDRE->getQualifierLoc());
662 MissingTemplateKeyword = true;
663 } else if (auto *DSME =
664 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
665 NameInfo = DSME->getMemberNameInfo();
666 SS.Adopt(DSME->getQualifierLoc());
667 MissingTemplateKeyword = true;
668 } else {
669 llvm_unreachable("unexpected kind of potential template name");
670 }
671
672 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
673 // was missing.
674 if (MissingTemplateKeyword) {
675 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
676 << NameInfo.getName() << SourceRange(Less, Greater);
677 return;
678 }
679
680 // Try to correct the name by looking for templates and C++ named casts.
681 struct TemplateCandidateFilter : CorrectionCandidateCallback {
682 Sema &S;
683 TemplateCandidateFilter(Sema &S) : S(S) {
684 WantTypeSpecifiers = false;
685 WantExpressionKeywords = false;
686 WantRemainingKeywords = false;
687 WantCXXNamedCasts = true;
688 };
689 bool ValidateCandidate(const TypoCorrection &Candidate) override {
690 if (auto *ND = Candidate.getCorrectionDecl())
691 return S.getAsTemplateNameDecl(ND);
692 return Candidate.isKeyword();
693 }
694
695 std::unique_ptr<CorrectionCandidateCallback> clone() override {
696 return std::make_unique<TemplateCandidateFilter>(*this);
697 }
698 };
699
700 DeclarationName Name = NameInfo.getName();
701 TemplateCandidateFilter CCC(*this);
702 if (TypoCorrection Corrected =
703 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
704 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
705 auto *ND = Corrected.getFoundDecl();
706 if (ND)
707 ND = getAsTemplateNameDecl(ND);
708 if (ND || Corrected.isKeyword()) {
709 if (LookupCtx) {
710 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
711 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
712 Name.getAsString() == CorrectedStr;
713 diagnoseTypo(Corrected,
714 PDiag(diag::err_non_template_in_member_template_id_suggest)
715 << Name << LookupCtx << DroppedSpecifier
716 << SS.getRange(), false);
717 } else {
718 diagnoseTypo(Corrected,
719 PDiag(diag::err_non_template_in_template_id_suggest)
720 << Name, false);
721 }
722 if (Found)
723 Diag(Found->getLocation(),
724 diag::note_non_template_in_template_id_found);
725 return;
726 }
727 }
728
729 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
730 << Name << SourceRange(Less, Greater);
731 if (Found)
732 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
733}
734
737 SourceLocation TemplateKWLoc,
738 const DeclarationNameInfo &NameInfo,
739 bool isAddressOfOperand,
740 const TemplateArgumentListInfo *TemplateArgs) {
741 if (SS.isEmpty()) {
742 // FIXME: This codepath is only used by dependent unqualified names
743 // (e.g. a dependent conversion-function-id, or operator= once we support
744 // it). It doesn't quite do the right thing, and it will silently fail if
745 // getCurrentThisType() returns null.
746 QualType ThisType = getCurrentThisType();
747 if (ThisType.isNull())
748 return ExprError();
749
751 Context, /*Base=*/nullptr, ThisType,
752 /*IsArrow=*/!Context.getLangOpts().HLSL,
753 /*OperatorLoc=*/SourceLocation(),
754 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
755 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
756 }
757 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
758}
759
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 const TemplateArgumentListInfo *TemplateArgs) {
765 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
766 if (!SS.isValid())
767 return CreateRecoveryExpr(
768 SS.getBeginLoc(),
769 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
770
772 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
773 TemplateArgs);
774}
775
777Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
778 QualType ParamType, SourceLocation Loc,
780 UnsignedOrNone PackIndex, bool Final) {
781 // The template argument itself might be an expression, in which case we just
782 // return that expression. This happens when substituting into an alias
783 // template.
784 Expr *Replacement;
786 Replacement = Arg.getAsExpr();
787 } else {
788 ExprResult result =
789 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
790 if (result.isInvalid())
791 return ExprError();
792 Replacement = result.get();
793 }
794 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
795 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
796 AssociatedDecl, ParamType, Index, PackIndex, Final);
797}
798
800 NamedDecl *Instantiation,
801 bool InstantiatedFromMember,
802 const NamedDecl *Pattern,
803 const NamedDecl *PatternDef,
805 bool Complain, bool *Unreachable) {
806 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
807 isa<VarDecl>(Instantiation));
808
809 bool IsEntityBeingDefined = false;
810 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
811 IsEntityBeingDefined = TD->isBeingDefined();
812
813 if (PatternDef && !IsEntityBeingDefined) {
814 NamedDecl *SuggestedDef = nullptr;
815 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
816 &SuggestedDef,
817 /*OnlyNeedComplete*/ false)) {
818 if (Unreachable)
819 *Unreachable = true;
820 // If we're allowed to diagnose this and recover, do so.
821 bool Recover = Complain && !isSFINAEContext();
822 if (Complain)
823 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
825 return !Recover;
826 }
827 return false;
828 }
829
830 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
831 return true;
832
833 CanQualType InstantiationTy;
834 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
835 InstantiationTy = Context.getCanonicalTagType(TD);
836 if (PatternDef) {
837 Diag(PointOfInstantiation,
838 diag::err_template_instantiate_within_definition)
839 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
840 << InstantiationTy;
841 // Not much point in noting the template declaration here, since
842 // we're lexically inside it.
843 Instantiation->setInvalidDecl();
844 } else if (InstantiatedFromMember) {
845 if (isa<FunctionDecl>(Instantiation)) {
846 Diag(PointOfInstantiation,
847 diag::err_explicit_instantiation_undefined_member)
848 << /*member function*/ 1 << Instantiation->getDeclName()
849 << Instantiation->getDeclContext();
850 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
851 } else {
852 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
853 Diag(PointOfInstantiation,
854 diag::err_implicit_instantiate_member_undefined)
855 << InstantiationTy;
856 Diag(Pattern->getLocation(), diag::note_member_declared_at);
857 }
858 } else {
859 if (isa<FunctionDecl>(Instantiation)) {
860 Diag(PointOfInstantiation,
861 diag::err_explicit_instantiation_undefined_func_template)
862 << Pattern;
863 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
864 } else if (isa<TagDecl>(Instantiation)) {
865 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
866 << (TSK != TSK_ImplicitInstantiation)
867 << InstantiationTy;
868 NoteTemplateLocation(*Pattern);
869 } else {
870 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
871 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
872 Diag(PointOfInstantiation,
873 diag::err_explicit_instantiation_undefined_var_template)
874 << Instantiation;
875 Instantiation->setInvalidDecl();
876 } else
877 Diag(PointOfInstantiation,
878 diag::err_explicit_instantiation_undefined_member)
879 << /*static data member*/ 2 << Instantiation->getDeclName()
880 << Instantiation->getDeclContext();
881 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
882 }
883 }
884
885 // In general, Instantiation isn't marked invalid to get more than one
886 // error for multiple undefined instantiations. But the code that does
887 // explicit declaration -> explicit definition conversion can't handle
888 // invalid declarations, so mark as invalid in that case.
890 Instantiation->setInvalidDecl();
891 return true;
892}
893
895 bool SupportedForCompatibility) {
896 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
897
898 // C++23 [temp.local]p6:
899 // The name of a template-parameter shall not be bound to any following.
900 // declaration whose locus is contained by the scope to which the
901 // template-parameter belongs.
902 //
903 // When MSVC compatibility is enabled, the diagnostic is always a warning
904 // by default. Otherwise, it an error unless SupportedForCompatibility is
905 // true, in which case it is a default-to-error warning.
906 unsigned DiagId =
907 getLangOpts().MSVCCompat
908 ? diag::ext_template_param_shadow
909 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
910 : diag::err_template_param_shadow);
911 const auto *ND = cast<NamedDecl>(PrevDecl);
912 Diag(Loc, DiagId) << ND->getDeclName();
914}
915
917 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
918 D = Temp->getTemplatedDecl();
919 return Temp;
920 }
921 return nullptr;
922}
923
925 SourceLocation EllipsisLoc) const {
926 assert(Kind == Template &&
927 "Only template template arguments can be pack expansions here");
928 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
929 "Template template argument pack expansion without packs");
931 Result.EllipsisLoc = EllipsisLoc;
932 return Result;
933}
934
936 const ParsedTemplateArgument &Arg) {
937
938 switch (Arg.getKind()) {
940 TypeSourceInfo *TSI;
941 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
942 if (!TSI)
943 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
945 }
946
948 Expr *E = Arg.getAsExpr();
949 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
950 }
951
954 TemplateArgument TArg;
955 if (Arg.getEllipsisLoc().isValid())
956 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
957 else
958 TArg = Template;
959 return TemplateArgumentLoc(
960 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
962 Arg.getNameLoc(), Arg.getEllipsisLoc());
963 }
964 }
965
966 llvm_unreachable("Unhandled parsed template argument");
967}
968
970 TemplateArgumentListInfo &TemplateArgs) {
971 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
972 TemplateArgs.addArgument(translateTemplateArgument(*this,
973 TemplateArgsIn[I]));
974}
975
977 SourceLocation Loc,
978 const IdentifierInfo *Name) {
979 NamedDecl *PrevDecl =
980 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
982 if (PrevDecl && PrevDecl->isTemplateParameter())
983 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
984}
985
987 TypeSourceInfo *TInfo;
988 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
989 if (T.isNull())
990 return ParsedTemplateArgument();
991 assert(TInfo && "template argument with no location");
992
993 // If we might have formed a deduced template specialization type, convert
994 // it to a template template argument.
995 if (getLangOpts().CPlusPlus17) {
996 TypeLoc TL = TInfo->getTypeLoc();
997 SourceLocation EllipsisLoc;
998 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
999 EllipsisLoc = PET.getEllipsisLoc();
1000 TL = PET.getPatternLoc();
1001 }
1002
1003 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1004 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1005 CXXScopeSpec SS;
1006 SS.Adopt(DTST.getQualifierLoc());
1007 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1008 TemplateTy::make(Name),
1009 DTST.getTemplateNameLoc());
1010 if (EllipsisLoc.isValid())
1011 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1012 return Result;
1013 }
1014 }
1015
1016 // This is a normal type template argument. Note, if the type template
1017 // argument is an injected-class-name for a template, it has a dual nature
1018 // and can be used as either a type or a template. We handle that in
1019 // convertTypeTemplateArgumentToTemplate.
1021 ParsedType.get().getAsOpaquePtr(),
1022 TInfo->getTypeLoc().getBeginLoc());
1023}
1024
1026 SourceLocation EllipsisLoc,
1027 SourceLocation KeyLoc,
1028 IdentifierInfo *ParamName,
1029 SourceLocation ParamNameLoc,
1030 unsigned Depth, unsigned Position,
1031 SourceLocation EqualLoc,
1032 ParsedType DefaultArg,
1033 bool HasTypeConstraint) {
1034 assert(S->isTemplateParamScope() &&
1035 "Template type parameter not in template parameter scope!");
1036
1037 bool IsParameterPack = EllipsisLoc.isValid();
1039 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1040 KeyLoc, ParamNameLoc, Depth, Position,
1041 ParamName, Typename, IsParameterPack,
1042 HasTypeConstraint);
1043 Param->setAccess(AS_public);
1044
1045 if (Param->isParameterPack())
1046 if (auto *CSI = getEnclosingLambdaOrBlock())
1047 CSI->LocalPacks.push_back(Param);
1048
1049 if (ParamName) {
1050 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1051
1052 // Add the template parameter into the current scope.
1053 S->AddDecl(Param);
1054 IdResolver.AddDecl(Param);
1055 }
1056
1057 // C++0x [temp.param]p9:
1058 // A default template-argument may be specified for any kind of
1059 // template-parameter that is not a template parameter pack.
1060 if (DefaultArg && IsParameterPack) {
1061 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1062 DefaultArg = nullptr;
1063 }
1064
1065 // Handle the default argument, if provided.
1066 if (DefaultArg) {
1067 TypeSourceInfo *DefaultTInfo;
1068 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1069
1070 assert(DefaultTInfo && "expected source information for type");
1071
1072 // Check for unexpanded parameter packs.
1073 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1075 return Param;
1076
1077 // Check the template argument itself.
1078 if (CheckTemplateArgument(DefaultTInfo)) {
1079 Param->setInvalidDecl();
1080 return Param;
1081 }
1082
1083 Param->setDefaultArgument(
1084 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1085 }
1086
1087 return Param;
1088}
1089
1090/// Convert the parser's template argument list representation into our form.
1093 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1094 TemplateId.RAngleLoc);
1095 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1096 TemplateId.NumArgs);
1097 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1098 return TemplateArgs;
1099}
1100
1102
1103 TemplateName TN = TypeConstr->Template.get();
1104 NamedDecl *CD = nullptr;
1105 bool IsTypeConcept = false;
1106 bool RequiresArguments = false;
1107 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1108 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1109 RequiresArguments =
1110 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1111 CD = TTP;
1112 } else {
1113 CD = TN.getAsTemplateDecl();
1114 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1115 RequiresArguments = cast<ConceptDecl>(CD)
1116 ->getTemplateParameters()
1117 ->getMinRequiredArguments() > 1;
1118 }
1119
1120 // C++2a [temp.param]p4:
1121 // [...] The concept designated by a type-constraint shall be a type
1122 // concept ([temp.concept]).
1123 if (!IsTypeConcept) {
1124 Diag(TypeConstr->TemplateNameLoc,
1125 diag::err_type_constraint_non_type_concept);
1126 return true;
1127 }
1128
1129 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1130 return true;
1131
1132 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1133
1134 if (!WereArgsSpecified && RequiresArguments) {
1135 Diag(TypeConstr->TemplateNameLoc,
1136 diag::err_type_constraint_missing_arguments)
1137 << CD;
1138 return true;
1139 }
1140 return false;
1141}
1142
1144 TemplateIdAnnotation *TypeConstr,
1145 TemplateTypeParmDecl *ConstrainedParameter,
1146 SourceLocation EllipsisLoc) {
1147 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1148 false);
1149}
1150
1152 TemplateIdAnnotation *TypeConstr,
1153 TemplateTypeParmDecl *ConstrainedParameter,
1154 SourceLocation EllipsisLoc,
1155 bool AllowUnexpandedPack) {
1156
1157 if (CheckTypeConstraint(TypeConstr))
1158 return true;
1159
1160 TemplateName TN = TypeConstr->Template.get();
1163
1164 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1165 TypeConstr->TemplateNameLoc);
1166
1167 TemplateArgumentListInfo TemplateArgs;
1168 if (TypeConstr->LAngleLoc.isValid()) {
1169 TemplateArgs =
1170 makeTemplateArgumentListInfo(*this, *TypeConstr);
1171
1172 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1173 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1175 return true;
1176 }
1177 }
1178 }
1179 return AttachTypeConstraint(
1181 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1182 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1183 ConstrainedParameter, EllipsisLoc);
1184}
1185
1186template <typename ArgumentLocAppender>
1189 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1190 SourceLocation RAngleLoc, QualType ConstrainedType,
1191 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1192 SourceLocation EllipsisLoc) {
1193
1194 TemplateArgumentListInfo ConstraintArgs;
1195 ConstraintArgs.addArgument(
1197 /*NTTPType=*/QualType(), ParamNameLoc));
1198
1199 ConstraintArgs.setRAngleLoc(RAngleLoc);
1200 ConstraintArgs.setLAngleLoc(LAngleLoc);
1201 Appender(ConstraintArgs);
1202
1203 // C++2a [temp.param]p4:
1204 // [...] This constraint-expression E is called the immediately-declared
1205 // constraint of T. [...]
1206 CXXScopeSpec SS;
1207 SS.Adopt(NS);
1208 ExprResult ImmediatelyDeclaredConstraint;
1209 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1210 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1211 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1212 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1213 /*DoCheckConstraintSatisfaction=*/
1215 }
1216 // We have a template template parameter
1217 else {
1218 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1219 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1220 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1221 }
1222 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1223 return ImmediatelyDeclaredConstraint;
1224
1225 // C++2a [temp.param]p4:
1226 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1227 //
1228 // We have the following case:
1229 //
1230 // template<typename T> concept C1 = true;
1231 // template<C1... T> struct s1;
1232 //
1233 // The constraint: (C1<T> && ...)
1234 //
1235 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1236 // any unqualified lookups for 'operator&&' here.
1237 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1238 /*LParenLoc=*/SourceLocation(),
1239 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1240 EllipsisLoc, /*RHS=*/nullptr,
1241 /*RParenLoc=*/SourceLocation(),
1242 /*NumExpansions=*/std::nullopt);
1243}
1244
1246 DeclarationNameInfo NameInfo,
1247 TemplateDecl *NamedConcept,
1248 NamedDecl *FoundDecl,
1249 const TemplateArgumentListInfo *TemplateArgs,
1250 TemplateTypeParmDecl *ConstrainedParameter,
1251 SourceLocation EllipsisLoc) {
1252 // C++2a [temp.param]p4:
1253 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1254 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1255 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1257 *TemplateArgs) : nullptr;
1258
1259 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1260
1261 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1262 *this, NS, NameInfo, NamedConcept, FoundDecl,
1263 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1264 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1265 ParamAsArgument, ConstrainedParameter->getLocation(),
1266 [&](TemplateArgumentListInfo &ConstraintArgs) {
1267 if (TemplateArgs)
1268 for (const auto &ArgLoc : TemplateArgs->arguments())
1269 ConstraintArgs.addArgument(ArgLoc);
1270 },
1271 EllipsisLoc);
1272 if (ImmediatelyDeclaredConstraint.isInvalid())
1273 return true;
1274
1275 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1276 /*TemplateKWLoc=*/SourceLocation{},
1277 /*ConceptNameInfo=*/NameInfo,
1278 /*FoundDecl=*/FoundDecl,
1279 /*NamedConcept=*/NamedConcept,
1280 /*ArgsWritten=*/ArgsAsWritten);
1281 ConstrainedParameter->setTypeConstraint(
1282 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1283 return false;
1284}
1285
1287 NonTypeTemplateParmDecl *NewConstrainedParm,
1288 NonTypeTemplateParmDecl *OrigConstrainedParm,
1289 SourceLocation EllipsisLoc) {
1290 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1292 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1293 diag::err_unsupported_placeholder_constraint)
1294 << NewConstrainedParm->getTypeSourceInfo()
1295 ->getTypeLoc()
1296 .getSourceRange();
1297 return true;
1298 }
1299 // FIXME: Concepts: This should be the type of the placeholder, but this is
1300 // unclear in the wording right now.
1301 DeclRefExpr *Ref =
1302 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1303 VK_PRValue, OrigConstrainedParm->getLocation());
1304 if (!Ref)
1305 return true;
1306 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1308 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1310 OrigConstrainedParm->getLocation(),
1311 [&](TemplateArgumentListInfo &ConstraintArgs) {
1312 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1313 ConstraintArgs.addArgument(TL.getArgLoc(I));
1314 },
1315 EllipsisLoc);
1316 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1317 !ImmediatelyDeclaredConstraint.isUsable())
1318 return true;
1319
1320 NewConstrainedParm->setPlaceholderTypeConstraint(
1321 ImmediatelyDeclaredConstraint.get());
1322 return false;
1323}
1324
1326 SourceLocation Loc) {
1327 if (TSI->getType()->isUndeducedType()) {
1328 // C++17 [temp.dep.expr]p3:
1329 // An id-expression is type-dependent if it contains
1330 // - an identifier associated by name lookup with a non-type
1331 // template-parameter declared with a type that contains a
1332 // placeholder type (7.1.7.4),
1334 if (!NewTSI)
1335 return QualType();
1336 TSI = NewTSI;
1337 }
1338
1339 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1340}
1341
1343 if (T->isDependentType())
1344 return false;
1345
1346 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1347 return true;
1348
1349 if (T->isStructuralType())
1350 return false;
1351
1352 // Structural types are required to be object types or lvalue references.
1353 if (T->isRValueReferenceType()) {
1354 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1355 return true;
1356 }
1357
1358 // Don't mention structural types in our diagnostic prior to C++20. Also,
1359 // there's not much more we can say about non-scalar non-class types --
1360 // because we can't see functions or arrays here, those can only be language
1361 // extensions.
1362 if (!getLangOpts().CPlusPlus20 ||
1363 (!T->isScalarType() && !T->isRecordType())) {
1364 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1365 return true;
1366 }
1367
1368 // Structural types are required to be literal types.
1369 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1370 return true;
1371
1372 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1373
1374 // Drill down into the reason why the class is non-structural.
1375 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1376 // All members are required to be public and non-mutable, and can't be of
1377 // rvalue reference type. Check these conditions first to prefer a "local"
1378 // reason over a more distant one.
1379 for (const FieldDecl *FD : RD->fields()) {
1380 if (FD->getAccess() != AS_public) {
1381 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1382 return true;
1383 }
1384 if (FD->isMutable()) {
1385 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1386 return true;
1387 }
1388 if (FD->getType()->isRValueReferenceType()) {
1389 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1390 << T;
1391 return true;
1392 }
1393 }
1394
1395 // All bases are required to be public.
1396 for (const auto &BaseSpec : RD->bases()) {
1397 if (BaseSpec.getAccessSpecifier() != AS_public) {
1398 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1399 << T << 1;
1400 return true;
1401 }
1402 }
1403
1404 // All subobjects are required to be of structural types.
1405 SourceLocation SubLoc;
1406 QualType SubType;
1407 int Kind = -1;
1408
1409 for (const FieldDecl *FD : RD->fields()) {
1410 QualType T = Context.getBaseElementType(FD->getType());
1411 if (!T->isStructuralType()) {
1412 SubLoc = FD->getLocation();
1413 SubType = T;
1414 Kind = 0;
1415 break;
1416 }
1417 }
1418
1419 if (Kind == -1) {
1420 for (const auto &BaseSpec : RD->bases()) {
1421 QualType T = BaseSpec.getType();
1422 if (!T->isStructuralType()) {
1423 SubLoc = BaseSpec.getBaseTypeLoc();
1424 SubType = T;
1425 Kind = 1;
1426 break;
1427 }
1428 }
1429 }
1430
1431 assert(Kind != -1 && "couldn't find reason why type is not structural");
1432 Diag(SubLoc, diag::note_not_structural_subobject)
1433 << T << Kind << SubType;
1434 T = SubType;
1435 RD = T->getAsCXXRecordDecl();
1436 }
1437
1438 return true;
1439}
1440
1442 SourceLocation Loc) {
1443 // We don't allow variably-modified types as the type of non-type template
1444 // parameters.
1445 if (T->isVariablyModifiedType()) {
1446 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1447 << T;
1448 return QualType();
1449 }
1450
1451 if (T->isBlockPointerType()) {
1452 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1453 return QualType();
1454 }
1455
1456 // C++ [temp.param]p4:
1457 //
1458 // A non-type template-parameter shall have one of the following
1459 // (optionally cv-qualified) types:
1460 //
1461 // -- integral or enumeration type,
1462 if (T->isIntegralOrEnumerationType() ||
1463 // -- pointer to object or pointer to function,
1464 T->isPointerType() ||
1465 // -- lvalue reference to object or lvalue reference to function,
1466 T->isLValueReferenceType() ||
1467 // -- pointer to member,
1468 T->isMemberPointerType() ||
1469 // -- std::nullptr_t, or
1470 T->isNullPtrType() ||
1471 // -- a type that contains a placeholder type.
1472 T->isUndeducedType()) {
1473 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1474 // are ignored when determining its type.
1475 return T.getUnqualifiedType();
1476 }
1477
1478 // C++ [temp.param]p8:
1479 //
1480 // A non-type template-parameter of type "array of T" or
1481 // "function returning T" is adjusted to be of type "pointer to
1482 // T" or "pointer to function returning T", respectively.
1483 if (T->isArrayType() || T->isFunctionType())
1484 return Context.getDecayedType(T);
1485
1486 // If T is a dependent type, we can't do the check now, so we
1487 // assume that it is well-formed. Note that stripping off the
1488 // qualifiers here is not really correct if T turns out to be
1489 // an array type, but we'll recompute the type everywhere it's
1490 // used during instantiation, so that should be OK. (Using the
1491 // qualified type is equally wrong.)
1492 if (T->isDependentType())
1493 return T.getUnqualifiedType();
1494
1495 // C++20 [temp.param]p6:
1496 // -- a structural type
1497 if (RequireStructuralType(T, Loc))
1498 return QualType();
1499
1500 if (!getLangOpts().CPlusPlus20) {
1501 // FIXME: Consider allowing structural types as an extension in C++17. (In
1502 // earlier language modes, the template argument evaluation rules are too
1503 // inflexible.)
1504 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1505 return QualType();
1506 }
1507
1508 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1509 return T.getUnqualifiedType();
1510}
1511
1513 unsigned Depth,
1514 unsigned Position,
1515 SourceLocation EqualLoc,
1516 Expr *Default) {
1518
1519 // Check that we have valid decl-specifiers specified.
1520 auto CheckValidDeclSpecifiers = [this, &D] {
1521 // C++ [temp.param]
1522 // p1
1523 // template-parameter:
1524 // ...
1525 // parameter-declaration
1526 // p2
1527 // ... A storage class shall not be specified in a template-parameter
1528 // declaration.
1529 // [dcl.typedef]p1:
1530 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1531 // of a parameter-declaration
1532 const DeclSpec &DS = D.getDeclSpec();
1533 auto EmitDiag = [this](SourceLocation Loc) {
1534 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1536 };
1538 EmitDiag(DS.getStorageClassSpecLoc());
1539
1541 EmitDiag(DS.getThreadStorageClassSpecLoc());
1542
1543 // [dcl.inline]p1:
1544 // The inline specifier can be applied only to the declaration or
1545 // definition of a variable or function.
1546
1547 if (DS.isInlineSpecified())
1548 EmitDiag(DS.getInlineSpecLoc());
1549
1550 // [dcl.constexpr]p1:
1551 // The constexpr specifier shall be applied only to the definition of a
1552 // variable or variable template or the declaration of a function or
1553 // function template.
1554
1555 if (DS.hasConstexprSpecifier())
1556 EmitDiag(DS.getConstexprSpecLoc());
1557
1558 // [dcl.fct.spec]p1:
1559 // Function-specifiers can be used only in function declarations.
1560
1561 if (DS.isVirtualSpecified())
1562 EmitDiag(DS.getVirtualSpecLoc());
1563
1564 if (DS.hasExplicitSpecifier())
1565 EmitDiag(DS.getExplicitSpecLoc());
1566
1567 if (DS.isNoreturnSpecified())
1568 EmitDiag(DS.getNoreturnSpecLoc());
1569 };
1570
1571 CheckValidDeclSpecifiers();
1572
1573 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1574 if (isa<AutoType>(T))
1576 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1577 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1578
1579 assert(S->isTemplateParamScope() &&
1580 "Non-type template parameter not in template parameter scope!");
1581 bool Invalid = false;
1582
1584 if (T.isNull()) {
1585 T = Context.IntTy; // Recover with an 'int' type.
1586 Invalid = true;
1587 }
1588
1590
1591 const IdentifierInfo *ParamName = D.getIdentifier();
1592 bool IsParameterPack = D.hasEllipsis();
1594 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1595 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1596 TInfo);
1597 Param->setAccess(AS_public);
1598
1600 if (TL.isConstrained()) {
1601 if (D.getEllipsisLoc().isInvalid() &&
1602 T->containsUnexpandedParameterPack()) {
1603 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1604 for (auto &Loc :
1605 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1608 }
1609 if (!Invalid &&
1610 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1611 Invalid = true;
1612 }
1613
1614 if (Invalid)
1615 Param->setInvalidDecl();
1616
1617 if (Param->isParameterPack())
1618 if (auto *CSI = getEnclosingLambdaOrBlock())
1619 CSI->LocalPacks.push_back(Param);
1620
1621 if (ParamName) {
1623 ParamName);
1624
1625 // Add the template parameter into the current scope.
1626 S->AddDecl(Param);
1627 IdResolver.AddDecl(Param);
1628 }
1629
1630 // C++0x [temp.param]p9:
1631 // A default template-argument may be specified for any kind of
1632 // template-parameter that is not a template parameter pack.
1633 if (Default && IsParameterPack) {
1634 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1635 Default = nullptr;
1636 }
1637
1638 // Check the well-formedness of the default template argument, if provided.
1639 if (Default) {
1640 // Check for unexpanded parameter packs.
1642 return Param;
1643
1644 Param->setDefaultArgument(
1646 TemplateArgument(Default, /*IsCanonical=*/false),
1647 QualType(), SourceLocation()));
1648 }
1649
1650 return Param;
1651}
1652
1653/// ActOnTemplateTemplateParameter - Called when a C++ template template
1654/// parameter (e.g. T in template <template <typename> class T> class array)
1655/// has been parsed. S is the current scope.
1657 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1658 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1659 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1660 unsigned Position, SourceLocation EqualLoc,
1662 assert(S->isTemplateParamScope() &&
1663 "Template template parameter not in template parameter scope!");
1664
1665 bool IsParameterPack = EllipsisLoc.isValid();
1666
1667 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1668 if (Params->size() == 0) {
1669 Diag(Loc, diag::err_template_template_parm_no_parms)
1670 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1671
1672 // Recover as if there was a type template parameter pack.
1673 SmallVector<NamedDecl *, 4> ParamDecls;
1674 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1675 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1676 Depth + 1, 0, /*Id=*/nullptr,
1677 /*Typename=*/false, /*ParameterPack=*/true));
1679 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1680 Params->getRAngleLoc(), Params->getRequiresClause());
1681 }
1682
1683 bool Invalid = false;
1685 Params,
1686 /*OldParams=*/nullptr,
1687 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1688 Invalid = true;
1689
1690 // Construct the parameter object.
1692 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1693 IsParameterPack, Name, Kind, Typename, Params);
1694 Param->setAccess(AS_public);
1695
1696 if (Param->isParameterPack())
1697 if (auto *LSI = getEnclosingLambdaOrBlock())
1698 LSI->LocalPacks.push_back(Param);
1699
1700 // If the template template parameter has a name, then link the identifier
1701 // into the scope and lookup mechanisms.
1702 if (Name) {
1703 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1704
1705 S->AddDecl(Param);
1706 IdResolver.AddDecl(Param);
1707 }
1708
1709 if (Invalid)
1710 Param->setInvalidDecl();
1711
1712 // C++0x [temp.param]p9:
1713 // A default template-argument may be specified for any kind of
1714 // template-parameter that is not a template parameter pack.
1715 if (IsParameterPack && !Default.isInvalid()) {
1716 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1718 }
1719
1720 if (!Default.isInvalid()) {
1721 // Check only that we have a template template argument. We don't want to
1722 // try to check well-formedness now, because our template template parameter
1723 // might have dependent types in its template parameters, which we wouldn't
1724 // be able to match now.
1725 //
1726 // If none of the template template parameter's template arguments mention
1727 // other template parameters, we could actually perform more checking here.
1728 // However, it isn't worth doing.
1730 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1731 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1732 << DefaultArg.getSourceRange();
1733 return Param;
1734 }
1735
1736 TemplateName Name =
1739 if (Template &&
1741 return Param;
1742 }
1743
1744 // Check for unexpanded parameter packs.
1746 DefaultArg.getArgument().getAsTemplate(),
1748 return Param;
1749
1750 Param->setDefaultArgument(Context, DefaultArg);
1751 }
1752
1753 return Param;
1754}
1755
1756namespace {
1757class ConstraintRefersToContainingTemplateChecker
1759 using inherited = ConstDynamicRecursiveASTVisitor;
1760 bool Result = false;
1761 const FunctionDecl *Friend = nullptr;
1762 unsigned TemplateDepth = 0;
1763
1764 // Check a record-decl that we've seen to see if it is a lexical parent of the
1765 // Friend, likely because it was referred to without its template arguments.
1766 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1767 CheckingRD = CheckingRD->getMostRecentDecl();
1768 if (!CheckingRD->isTemplated())
1769 return true;
1770
1771 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1772 DC && !DC->isFileContext(); DC = DC->getParent())
1773 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1774 if (CheckingRD == RD->getMostRecentDecl()) {
1775 Result = true;
1776 return false;
1777 }
1778
1779 return true;
1780 }
1781
1782 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1783 if (D->getDepth() < TemplateDepth)
1784 Result = true;
1785
1786 // Necessary because the type of the NTTP might be what refers to the parent
1787 // constriant.
1788 return TraverseType(D->getType());
1789 }
1790
1791public:
1792 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1793 unsigned TemplateDepth)
1794 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1795
1796 bool getResult() const { return Result; }
1797
1798 // This should be the only template parm type that we have to deal with.
1799 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1800 // FunctionParmPackExpr are all partially substituted, which cannot happen
1801 // with concepts at this point in translation.
1802 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1803 if (Type->getDecl()->getDepth() < TemplateDepth) {
1804 Result = true;
1805 return false;
1806 }
1807 return true;
1808 }
1809
1810 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1811 return TraverseDecl(E->getDecl());
1812 }
1813
1814 bool TraverseTypedefType(const TypedefType *TT,
1815 bool /*TraverseQualifier*/) override {
1816 return TraverseType(TT->desugar());
1817 }
1818
1819 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1820 // We don't care about TypeLocs. So traverse Types instead.
1821 return TraverseType(TL.getType(), TraverseQualifier);
1822 }
1823
1824 bool VisitTagType(const TagType *T) override {
1825 return TraverseDecl(T->getDecl());
1826 }
1827
1828 bool TraverseDecl(const Decl *D) override {
1829 assert(D);
1830 // FIXME : This is possibly an incomplete list, but it is unclear what other
1831 // Decl kinds could be used to refer to the template parameters. This is a
1832 // best guess so far based on examples currently available, but the
1833 // unreachable should catch future instances/cases.
1834 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1835 return TraverseType(TD->getUnderlyingType());
1836 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1837 return CheckNonTypeTemplateParmDecl(NTTPD);
1838 if (auto *VD = dyn_cast<ValueDecl>(D))
1839 return TraverseType(VD->getType());
1840 if (isa<TemplateDecl>(D))
1841 return true;
1842 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1843 return CheckIfContainingRecord(RD);
1844
1846 // No direct types to visit here I believe.
1847 } else
1848 llvm_unreachable("Don't know how to handle this declaration type yet");
1849 return true;
1850 }
1851};
1852} // namespace
1853
1855 const FunctionDecl *Friend, unsigned TemplateDepth,
1856 const Expr *Constraint) {
1857 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1858 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1859 Checker.TraverseStmt(Constraint);
1860 return Checker.getResult();
1861}
1862
1865 SourceLocation ExportLoc,
1866 SourceLocation TemplateLoc,
1867 SourceLocation LAngleLoc,
1868 ArrayRef<NamedDecl *> Params,
1869 SourceLocation RAngleLoc,
1870 Expr *RequiresClause) {
1871 if (ExportLoc.isValid())
1872 Diag(ExportLoc, diag::warn_template_export_unsupported);
1873
1874 for (NamedDecl *P : Params)
1876
1877 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1878 llvm::ArrayRef(Params), RAngleLoc,
1879 RequiresClause);
1880}
1881
1883 const CXXScopeSpec &SS) {
1884 if (SS.isSet())
1885 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1886}
1887
1888// Returns the template parameter list with all default template argument
1889// information.
1891 // Make sure we get the template parameter list from the most
1892 // recent declaration, since that is the only one that is guaranteed to
1893 // have all the default template argument information.
1894 Decl *D = TD->getMostRecentDecl();
1895 // C++11 N3337 [temp.param]p12:
1896 // A default template argument shall not be specified in a friend class
1897 // template declaration.
1898 //
1899 // Skip past friend *declarations* because they are not supposed to contain
1900 // default template arguments. Moreover, these declarations may introduce
1901 // template parameters living in different template depths than the
1902 // corresponding template parameters in TD, causing unmatched constraint
1903 // substitution.
1904 //
1905 // FIXME: Diagnose such cases within a class template:
1906 // template <class T>
1907 // struct S {
1908 // template <class = void> friend struct C;
1909 // };
1910 // template struct S<int>;
1912 D->getPreviousDecl())
1913 D = D->getPreviousDecl();
1914 return cast<TemplateDecl>(D)->getTemplateParameters();
1915}
1916
1918 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1919 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1920 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1921 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1922 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1923 TemplateParameterList **OuterTemplateParamLists,
1924 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1925 assert(TemplateParams && TemplateParams->size() > 0 &&
1926 "No template parameters");
1927 assert(TUK != TagUseKind::Reference &&
1928 "Can only declare or define class templates");
1929 bool Invalid = false;
1930
1931 // Check that we can declare a template here.
1932 if (CheckTemplateDeclScope(S, TemplateParams))
1933 return true;
1934
1936 assert(Kind != TagTypeKind::Enum &&
1937 "can't build template of enumerated type");
1938
1939 // There is no such thing as an unnamed class template.
1940 if (!Name) {
1941 Diag(KWLoc, diag::err_template_unnamed_class);
1942 return true;
1943 }
1944
1945 // Find any previous declaration with this name. For a friend with no
1946 // scope explicitly specified, we only look for tag declarations (per
1947 // C++11 [basic.lookup.elab]p2).
1948 DeclContext *SemanticContext;
1949 LookupResult Previous(*this, Name, NameLoc,
1950 (SS.isEmpty() && TUK == TagUseKind::Friend)
1954 if (SS.isNotEmpty() && !SS.isInvalid()) {
1955 SemanticContext = computeDeclContext(SS, true);
1956 if (!SemanticContext) {
1957 // FIXME: Horrible, horrible hack! We can't currently represent this
1958 // in the AST, and historically we have just ignored such friend
1959 // class templates, so don't complain here.
1960 Diag(NameLoc, TUK == TagUseKind::Friend
1961 ? diag::warn_template_qualified_friend_ignored
1962 : diag::err_template_qualified_declarator_no_match)
1963 << SS.getScopeRep() << SS.getRange();
1964 return TUK != TagUseKind::Friend;
1965 }
1966
1967 if (RequireCompleteDeclContext(SS, SemanticContext))
1968 return true;
1969
1970 // If we're adding a template to a dependent context, we may need to
1971 // rebuilding some of the types used within the template parameter list,
1972 // now that we know what the current instantiation is.
1973 if (SemanticContext->isDependentContext()) {
1974 ContextRAII SavedContext(*this, SemanticContext);
1976 Invalid = true;
1977 }
1978
1979 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1980 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1981 /*TemplateId-*/ nullptr,
1982 /*IsMemberSpecialization*/ false);
1983
1984 LookupQualifiedName(Previous, SemanticContext);
1985 } else {
1986 SemanticContext = CurContext;
1987
1988 // C++14 [class.mem]p14:
1989 // If T is the name of a class, then each of the following shall have a
1990 // name different from T:
1991 // -- every member template of class T
1992 if (TUK != TagUseKind::Friend &&
1993 DiagnoseClassNameShadow(SemanticContext,
1994 DeclarationNameInfo(Name, NameLoc)))
1995 return true;
1996
1997 LookupName(Previous, S);
1998 }
1999
2000 if (Previous.isAmbiguous())
2001 return true;
2002
2003 // Let the template parameter scope enter the lookup chain of the current
2004 // class template. For example, given
2005 //
2006 // namespace ns {
2007 // template <class> bool Param = false;
2008 // template <class T> struct N;
2009 // }
2010 //
2011 // template <class Param> struct ns::N { void foo(Param); };
2012 //
2013 // When we reference Param inside the function parameter list, our name lookup
2014 // chain for it should be like:
2015 // FunctionScope foo
2016 // -> RecordScope N
2017 // -> TemplateParamScope (where we will find Param)
2018 // -> NamespaceScope ns
2019 //
2020 // See also CppLookupName().
2021 if (S->isTemplateParamScope())
2022 EnterTemplatedContext(S, SemanticContext);
2023
2024 NamedDecl *PrevDecl = nullptr;
2025 if (Previous.begin() != Previous.end())
2026 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2027
2028 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2029 // Maybe we will complain about the shadowed template parameter.
2030 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2031 // Just pretend that we didn't see the previous declaration.
2032 PrevDecl = nullptr;
2033 }
2034
2035 // If there is a previous declaration with the same name, check
2036 // whether this is a valid redeclaration.
2037 ClassTemplateDecl *PrevClassTemplate =
2038 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2039
2040 // We may have found the injected-class-name of a class template,
2041 // class template partial specialization, or class template specialization.
2042 // In these cases, grab the template that is being defined or specialized.
2043 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2044 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2045 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2046 PrevClassTemplate
2047 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2048 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2049 PrevClassTemplate
2051 ->getSpecializedTemplate();
2052 }
2053 }
2054
2055 if (TUK == TagUseKind::Friend) {
2056 // C++ [namespace.memdef]p3:
2057 // [...] When looking for a prior declaration of a class or a function
2058 // declared as a friend, and when the name of the friend class or
2059 // function is neither a qualified name nor a template-id, scopes outside
2060 // the innermost enclosing namespace scope are not considered.
2061 if (!SS.isSet()) {
2062 DeclContext *OutermostContext = CurContext;
2063 while (!OutermostContext->isFileContext())
2064 OutermostContext = OutermostContext->getLookupParent();
2065
2066 if (PrevDecl &&
2067 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2068 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2069 SemanticContext = PrevDecl->getDeclContext();
2070 } else {
2071 // Declarations in outer scopes don't matter. However, the outermost
2072 // context we computed is the semantic context for our new
2073 // declaration.
2074 PrevDecl = PrevClassTemplate = nullptr;
2075 SemanticContext = OutermostContext;
2076
2077 // Check that the chosen semantic context doesn't already contain a
2078 // declaration of this name as a non-tag type.
2080 DeclContext *LookupContext = SemanticContext;
2081 while (LookupContext->isTransparentContext())
2082 LookupContext = LookupContext->getLookupParent();
2083 LookupQualifiedName(Previous, LookupContext);
2084
2085 if (Previous.isAmbiguous())
2086 return true;
2087
2088 if (Previous.begin() != Previous.end())
2089 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2090 }
2091 }
2092 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2093 SemanticContext, S, SS.isValid()))
2094 PrevDecl = PrevClassTemplate = nullptr;
2095
2096 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2097 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2098 if (SS.isEmpty() &&
2099 !(PrevClassTemplate &&
2100 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2101 SemanticContext->getRedeclContext()))) {
2102 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2103 Diag(Shadow->getTargetDecl()->getLocation(),
2104 diag::note_using_decl_target);
2105 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2106 // Recover by ignoring the old declaration.
2107 PrevDecl = PrevClassTemplate = nullptr;
2108 }
2109 }
2110
2111 if (PrevClassTemplate) {
2112 // Ensure that the template parameter lists are compatible. Skip this check
2113 // for a friend in a dependent context: the template parameter list itself
2114 // could be dependent.
2115 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2117 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2118 : CurContext,
2119 CurContext, KWLoc),
2120 TemplateParams, PrevClassTemplate,
2121 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2123 return true;
2124
2125 // C++ [temp.class]p4:
2126 // In a redeclaration, partial specialization, explicit
2127 // specialization or explicit instantiation of a class template,
2128 // the class-key shall agree in kind with the original class
2129 // template declaration (7.1.5.3).
2130 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2132 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2133 Diag(KWLoc, diag::err_use_with_wrong_tag)
2134 << Name
2135 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2136 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2137 Kind = PrevRecordDecl->getTagKind();
2138 }
2139
2140 // Check for redefinition of this class template.
2141 if (TUK == TagUseKind::Definition) {
2142 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2143 // If we have a prior definition that is not visible, treat this as
2144 // simply making that previous definition visible.
2145 NamedDecl *Hidden = nullptr;
2146 bool HiddenDefVisible = false;
2147 if (SkipBody &&
2148 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2149 SkipBody->ShouldSkip = true;
2150 SkipBody->Previous = Def;
2151 if (!HiddenDefVisible && Hidden) {
2152 auto *Tmpl =
2153 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2154 assert(Tmpl && "original definition of a class template is not a "
2155 "class template?");
2158 }
2159 } else {
2160 Diag(NameLoc, diag::err_redefinition) << Name;
2161 Diag(Def->getLocation(), diag::note_previous_definition);
2162 // FIXME: Would it make sense to try to "forget" the previous
2163 // definition, as part of error recovery?
2164 return true;
2165 }
2166 }
2167 }
2168 } else if (PrevDecl) {
2169 // C++ [temp]p5:
2170 // A class template shall not have the same name as any other
2171 // template, class, function, object, enumeration, enumerator,
2172 // namespace, or type in the same scope (3.3), except as specified
2173 // in (14.5.4).
2174 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2175 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2176 return true;
2177 }
2178
2179 // Check the template parameter list of this declaration, possibly
2180 // merging in the template parameter list from the previous class
2181 // template declaration. Skip this check for a friend in a dependent
2182 // context, because the template parameter list might be dependent.
2183 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2185 TemplateParams,
2186 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2187 : nullptr,
2188 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2189 SemanticContext->isDependentContext())
2192 : TPC_Other,
2193 SkipBody))
2194 Invalid = true;
2195
2196 if (SS.isSet()) {
2197 // If the name of the template was qualified, we must be defining the
2198 // template out-of-line.
2199 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2200 Diag(NameLoc, TUK == TagUseKind::Friend
2201 ? diag::err_friend_decl_does_not_match
2202 : diag::err_member_decl_does_not_match)
2203 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2204 Invalid = true;
2205 }
2206 }
2207
2208 // If this is a templated friend in a dependent context we should not put it
2209 // on the redecl chain. In some cases, the templated friend can be the most
2210 // recent declaration tricking the template instantiator to make substitutions
2211 // there.
2212 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2213 bool ShouldAddRedecl =
2214 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2215
2217 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2218 PrevClassTemplate && ShouldAddRedecl
2219 ? PrevClassTemplate->getTemplatedDecl()
2220 : nullptr);
2221 SetNestedNameSpecifier(*this, NewClass, SS);
2222 if (NumOuterTemplateParamLists > 0)
2224 Context,
2225 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2226
2227 // Add alignment attributes if necessary; these attributes are checked when
2228 // the ASTContext lays out the structure.
2229 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2230 if (LangOpts.HLSL)
2231 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2234 }
2235
2236 ClassTemplateDecl *NewTemplate
2237 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2238 DeclarationName(Name), TemplateParams,
2239 NewClass);
2240
2241 if (ShouldAddRedecl)
2242 NewTemplate->setPreviousDecl(PrevClassTemplate);
2243
2244 NewClass->setDescribedClassTemplate(NewTemplate);
2245
2246 if (ModulePrivateLoc.isValid())
2247 NewTemplate->setModulePrivate();
2248
2249 if (IsMemberSpecialization) {
2250 assert(PrevClassTemplate &&
2251 "Member specialization without a primary template?");
2252 NewTemplate->setMemberSpecialization();
2253 }
2254
2255 // Set the access specifier.
2256 if (!Invalid && TUK != TagUseKind::Friend &&
2257 NewTemplate->getDeclContext()->isRecord())
2258 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2259
2260 // Set the lexical context of these templates
2262 NewTemplate->setLexicalDeclContext(CurContext);
2263
2264 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2265 NewClass->startDefinition();
2266
2267 ProcessDeclAttributeList(S, NewClass, Attr);
2268
2269 if (PrevClassTemplate)
2270 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2271
2275
2276 if (TUK != TagUseKind::Friend) {
2277 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2278 Scope *Outer = S;
2279 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2280 Outer = Outer->getParent();
2281 PushOnScopeChains(NewTemplate, Outer);
2282 } else {
2283 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2284 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2285 NewClass->setAccess(PrevClassTemplate->getAccess());
2286 }
2287
2288 NewTemplate->setObjectOfFriendDecl();
2289
2290 // Friend templates are visible in fairly strange ways.
2291 if (!CurContext->isDependentContext()) {
2292 DeclContext *DC = SemanticContext->getRedeclContext();
2293 DC->makeDeclVisibleInContext(NewTemplate);
2294 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2295 PushOnScopeChains(NewTemplate, EnclosingScope,
2296 /* AddToContext = */ false);
2297 }
2298
2300 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2301 Friend->setAccess(AS_public);
2302 CurContext->addDecl(Friend);
2303 }
2304
2305 if (PrevClassTemplate)
2306 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2307
2308 if (Invalid) {
2309 NewTemplate->setInvalidDecl();
2310 NewClass->setInvalidDecl();
2311 }
2312
2313 ActOnDocumentableDecl(NewTemplate);
2314
2315 if (SkipBody && SkipBody->ShouldSkip)
2316 return SkipBody->Previous;
2317
2318 return NewTemplate;
2319}
2320
2321/// Diagnose the presence of a default template argument on a
2322/// template parameter, which is ill-formed in certain contexts.
2323///
2324/// \returns true if the default template argument should be dropped.
2327 SourceLocation ParamLoc,
2328 SourceRange DefArgRange) {
2329 switch (TPC) {
2330 case Sema::TPC_Other:
2332 return false;
2333
2336 // C++ [temp.param]p9:
2337 // A default template-argument shall not be specified in a
2338 // function template declaration or a function template
2339 // definition [...]
2340 // If a friend function template declaration specifies a default
2341 // template-argument, that declaration shall be a definition and shall be
2342 // the only declaration of the function template in the translation unit.
2343 // (C++98/03 doesn't have this wording; see DR226).
2344 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2345 << DefArgRange;
2346 return false;
2347
2349 // C++0x [temp.param]p9:
2350 // A default template-argument shall not be specified in the
2351 // template-parameter-lists of the definition of a member of a
2352 // class template that appears outside of the member's class.
2353 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2354 << DefArgRange;
2355 return true;
2356
2359 // C++ [temp.param]p9:
2360 // A default template-argument shall not be specified in a
2361 // friend template declaration.
2362 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2363 << DefArgRange;
2364 return true;
2365
2366 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2367 // for friend function templates if there is only a single
2368 // declaration (and it is a definition). Strange!
2369 }
2370
2371 llvm_unreachable("Invalid TemplateParamListContext!");
2372}
2373
2374/// Check for unexpanded parameter packs within the template parameters
2375/// of a template template parameter, recursively.
2378 // A template template parameter which is a parameter pack is also a pack
2379 // expansion.
2380 if (TTP->isParameterPack())
2381 return false;
2382
2384 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2385 NamedDecl *P = Params->getParam(I);
2386 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2387 if (!TTP->isParameterPack())
2388 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2389 if (TC->hasExplicitTemplateArgs())
2390 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2393 return true;
2394 continue;
2395 }
2396
2397 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2398 if (!NTTP->isParameterPack() &&
2399 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2400 NTTP->getTypeSourceInfo(),
2402 return true;
2403
2404 continue;
2405 }
2406
2407 if (TemplateTemplateParmDecl *InnerTTP
2408 = dyn_cast<TemplateTemplateParmDecl>(P))
2409 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2410 return true;
2411 }
2412
2413 return false;
2414}
2415
2417 TemplateParameterList *OldParams,
2419 SkipBodyInfo *SkipBody) {
2420 bool Invalid = false;
2421
2422 // C++ [temp.param]p10:
2423 // The set of default template-arguments available for use with a
2424 // template declaration or definition is obtained by merging the
2425 // default arguments from the definition (if in scope) and all
2426 // declarations in scope in the same way default function
2427 // arguments are (8.3.6).
2428 bool SawDefaultArgument = false;
2429 SourceLocation PreviousDefaultArgLoc;
2430
2431 // Dummy initialization to avoid warnings.
2432 TemplateParameterList::iterator OldParam = NewParams->end();
2433 if (OldParams)
2434 OldParam = OldParams->begin();
2435
2436 bool RemoveDefaultArguments = false;
2437 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2438 NewParamEnd = NewParams->end();
2439 NewParam != NewParamEnd; ++NewParam) {
2440 // Whether we've seen a duplicate default argument in the same translation
2441 // unit.
2442 bool RedundantDefaultArg = false;
2443 // Whether we've found inconsis inconsitent default arguments in different
2444 // translation unit.
2445 bool InconsistentDefaultArg = false;
2446 // The name of the module which contains the inconsistent default argument.
2447 std::string PrevModuleName;
2448
2449 SourceLocation OldDefaultLoc;
2450 SourceLocation NewDefaultLoc;
2451
2452 // Variable used to diagnose missing default arguments
2453 bool MissingDefaultArg = false;
2454
2455 // Variable used to diagnose non-final parameter packs
2456 bool SawParameterPack = false;
2457
2458 if (TemplateTypeParmDecl *NewTypeParm
2459 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2460 // Check the presence of a default argument here.
2461 if (NewTypeParm->hasDefaultArgument() &&
2463 *this, TPC, NewTypeParm->getLocation(),
2464 NewTypeParm->getDefaultArgument().getSourceRange()))
2465 NewTypeParm->removeDefaultArgument();
2466
2467 // Merge default arguments for template type parameters.
2468 TemplateTypeParmDecl *OldTypeParm
2469 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2470 if (NewTypeParm->isParameterPack()) {
2471 assert(!NewTypeParm->hasDefaultArgument() &&
2472 "Parameter packs can't have a default argument!");
2473 SawParameterPack = true;
2474 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2475 NewTypeParm->hasDefaultArgument() &&
2476 (!SkipBody || !SkipBody->ShouldSkip)) {
2477 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2478 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2479 SawDefaultArgument = true;
2480
2481 if (!OldTypeParm->getOwningModule())
2482 RedundantDefaultArg = true;
2483 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2484 NewTypeParm)) {
2485 InconsistentDefaultArg = true;
2486 PrevModuleName =
2488 }
2489 PreviousDefaultArgLoc = NewDefaultLoc;
2490 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2491 // Merge the default argument from the old declaration to the
2492 // new declaration.
2493 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2494 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2495 } else if (NewTypeParm->hasDefaultArgument()) {
2496 SawDefaultArgument = true;
2497 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2498 } else if (SawDefaultArgument)
2499 MissingDefaultArg = true;
2500 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2501 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2502 // Check for unexpanded parameter packs, except in a template template
2503 // parameter pack, as in those any unexpanded packs should be expanded
2504 // along with the parameter itself.
2506 !NewNonTypeParm->isParameterPack() &&
2507 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2508 NewNonTypeParm->getTypeSourceInfo(),
2510 Invalid = true;
2511 continue;
2512 }
2513
2514 // Check the presence of a default argument here.
2515 if (NewNonTypeParm->hasDefaultArgument() &&
2517 *this, TPC, NewNonTypeParm->getLocation(),
2518 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2519 NewNonTypeParm->removeDefaultArgument();
2520 }
2521
2522 // Merge default arguments for non-type template parameters
2523 NonTypeTemplateParmDecl *OldNonTypeParm
2524 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2525 if (NewNonTypeParm->isParameterPack()) {
2526 assert(!NewNonTypeParm->hasDefaultArgument() &&
2527 "Parameter packs can't have a default argument!");
2528 if (!NewNonTypeParm->isPackExpansion())
2529 SawParameterPack = true;
2530 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2531 NewNonTypeParm->hasDefaultArgument() &&
2532 (!SkipBody || !SkipBody->ShouldSkip)) {
2533 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2534 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2535 SawDefaultArgument = true;
2536 if (!OldNonTypeParm->getOwningModule())
2537 RedundantDefaultArg = true;
2538 else if (!getASTContext().isSameDefaultTemplateArgument(
2539 OldNonTypeParm, NewNonTypeParm)) {
2540 InconsistentDefaultArg = true;
2541 PrevModuleName =
2542 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2543 }
2544 PreviousDefaultArgLoc = NewDefaultLoc;
2545 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2546 // Merge the default argument from the old declaration to the
2547 // new declaration.
2548 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2549 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2550 } else if (NewNonTypeParm->hasDefaultArgument()) {
2551 SawDefaultArgument = true;
2552 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2553 } else if (SawDefaultArgument)
2554 MissingDefaultArg = true;
2555 } else {
2556 TemplateTemplateParmDecl *NewTemplateParm
2557 = cast<TemplateTemplateParmDecl>(*NewParam);
2558
2559 // Check for unexpanded parameter packs, recursively.
2560 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2561 Invalid = true;
2562 continue;
2563 }
2564
2565 // Check the presence of a default argument here.
2566 if (NewTemplateParm->hasDefaultArgument() &&
2568 NewTemplateParm->getLocation(),
2569 NewTemplateParm->getDefaultArgument().getSourceRange()))
2570 NewTemplateParm->removeDefaultArgument();
2571
2572 // Merge default arguments for template template parameters
2573 TemplateTemplateParmDecl *OldTemplateParm
2574 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2575 if (NewTemplateParm->isParameterPack()) {
2576 assert(!NewTemplateParm->hasDefaultArgument() &&
2577 "Parameter packs can't have a default argument!");
2578 if (!NewTemplateParm->isPackExpansion())
2579 SawParameterPack = true;
2580 } else if (OldTemplateParm &&
2581 hasVisibleDefaultArgument(OldTemplateParm) &&
2582 NewTemplateParm->hasDefaultArgument() &&
2583 (!SkipBody || !SkipBody->ShouldSkip)) {
2584 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2585 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2586 SawDefaultArgument = true;
2587 if (!OldTemplateParm->getOwningModule())
2588 RedundantDefaultArg = true;
2589 else if (!getASTContext().isSameDefaultTemplateArgument(
2590 OldTemplateParm, NewTemplateParm)) {
2591 InconsistentDefaultArg = true;
2592 PrevModuleName =
2593 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2594 }
2595 PreviousDefaultArgLoc = NewDefaultLoc;
2596 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2597 // Merge the default argument from the old declaration to the
2598 // new declaration.
2599 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2600 PreviousDefaultArgLoc
2601 = OldTemplateParm->getDefaultArgument().getLocation();
2602 } else if (NewTemplateParm->hasDefaultArgument()) {
2603 SawDefaultArgument = true;
2604 PreviousDefaultArgLoc
2605 = NewTemplateParm->getDefaultArgument().getLocation();
2606 } else if (SawDefaultArgument)
2607 MissingDefaultArg = true;
2608 }
2609
2610 // C++11 [temp.param]p11:
2611 // If a template parameter of a primary class template or alias template
2612 // is a template parameter pack, it shall be the last template parameter.
2613 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2614 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2615 Diag((*NewParam)->getLocation(),
2616 diag::err_template_param_pack_must_be_last_template_parameter);
2617 Invalid = true;
2618 }
2619
2620 // [basic.def.odr]/13:
2621 // There can be more than one definition of a
2622 // ...
2623 // default template argument
2624 // ...
2625 // in a program provided that each definition appears in a different
2626 // translation unit and the definitions satisfy the [same-meaning
2627 // criteria of the ODR].
2628 //
2629 // Simply, the design of modules allows the definition of template default
2630 // argument to be repeated across translation unit. Note that the ODR is
2631 // checked elsewhere. But it is still not allowed to repeat template default
2632 // argument in the same translation unit.
2633 if (RedundantDefaultArg) {
2634 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2635 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2636 Invalid = true;
2637 } else if (InconsistentDefaultArg) {
2638 // We could only diagnose about the case that the OldParam is imported.
2639 // The case NewParam is imported should be handled in ASTReader.
2640 Diag(NewDefaultLoc,
2641 diag::err_template_param_default_arg_inconsistent_redefinition);
2642 Diag(OldDefaultLoc,
2643 diag::note_template_param_prev_default_arg_in_other_module)
2644 << PrevModuleName;
2645 Invalid = true;
2646 } else if (MissingDefaultArg &&
2647 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2648 TPC == TPC_FriendClassTemplate)) {
2649 // C++ 23[temp.param]p14:
2650 // If a template-parameter of a class template, variable template, or
2651 // alias template has a default template argument, each subsequent
2652 // template-parameter shall either have a default template argument
2653 // supplied or be a template parameter pack.
2654 Diag((*NewParam)->getLocation(),
2655 diag::err_template_param_default_arg_missing);
2656 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2657 Invalid = true;
2658 RemoveDefaultArguments = true;
2659 }
2660
2661 // If we have an old template parameter list that we're merging
2662 // in, move on to the next parameter.
2663 if (OldParams)
2664 ++OldParam;
2665 }
2666
2667 // We were missing some default arguments at the end of the list, so remove
2668 // all of the default arguments.
2669 if (RemoveDefaultArguments) {
2670 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2671 NewParamEnd = NewParams->end();
2672 NewParam != NewParamEnd; ++NewParam) {
2673 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2674 TTP->removeDefaultArgument();
2675 else if (NonTypeTemplateParmDecl *NTTP
2676 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2677 NTTP->removeDefaultArgument();
2678 else
2679 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2680 }
2681 }
2682
2683 return Invalid;
2684}
2685
2686namespace {
2687
2688/// A class which looks for a use of a certain level of template
2689/// parameter.
2690struct DependencyChecker : DynamicRecursiveASTVisitor {
2691 unsigned Depth;
2692
2693 // Whether we're looking for a use of a template parameter that makes the
2694 // overall construct type-dependent / a dependent type. This is strictly
2695 // best-effort for now; we may fail to match at all for a dependent type
2696 // in some cases if this is set.
2697 bool IgnoreNonTypeDependent;
2698
2699 bool Match;
2700 SourceLocation MatchLoc;
2701
2702 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2703 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2704 Match(false) {}
2705
2706 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2707 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2708 NamedDecl *ND = Params->getParam(0);
2709 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2710 Depth = PD->getDepth();
2711 } else if (NonTypeTemplateParmDecl *PD =
2712 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2713 Depth = PD->getDepth();
2714 } else {
2715 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2716 }
2717 }
2718
2719 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2720 if (ParmDepth >= Depth) {
2721 Match = true;
2722 MatchLoc = Loc;
2723 return true;
2724 }
2725 return false;
2726 }
2727
2728 bool TraverseStmt(Stmt *S) override {
2729 // Prune out non-type-dependent expressions if requested. This can
2730 // sometimes result in us failing to find a template parameter reference
2731 // (if a value-dependent expression creates a dependent type), but this
2732 // mode is best-effort only.
2733 if (auto *E = dyn_cast_or_null<Expr>(S))
2734 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2735 return true;
2737 }
2738
2739 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2740 if (IgnoreNonTypeDependent && !TL.isNull() &&
2741 !TL.getType()->isDependentType())
2742 return true;
2743 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2744 }
2745
2746 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2747 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2748 }
2749
2750 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2751 // For a best-effort search, keep looking until we find a location.
2752 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2753 }
2754
2755 bool TraverseTemplateName(TemplateName N) override {
2756 if (TemplateTemplateParmDecl *PD =
2757 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2758 if (Matches(PD->getDepth()))
2759 return false;
2761 }
2762
2763 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2764 if (NonTypeTemplateParmDecl *PD =
2765 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2766 if (Matches(PD->getDepth(), E->getExprLoc()))
2767 return false;
2768 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2769 }
2770
2771 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2772 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2773 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2774 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2775 return false;
2776 }
2777 for (auto &TLoc : ULE->template_arguments())
2779 }
2780 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2781 }
2782
2783 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2784 return TraverseType(T->getReplacementType());
2785 }
2786
2787 bool VisitSubstTemplateTypeParmPackType(
2788 SubstTemplateTypeParmPackType *T) override {
2789 return TraverseTemplateArgument(T->getArgumentPack());
2790 }
2791
2792 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2793 bool TraverseQualifier) override {
2794 // An InjectedClassNameType will never have a dependent template name,
2795 // so no need to traverse it.
2796 return TraverseTemplateArguments(
2797 T->getTemplateArgs(T->getDecl()->getASTContext()));
2798 }
2799};
2800} // end anonymous namespace
2801
2802/// Determines whether a given type depends on the given parameter
2803/// list.
2804static bool
2806 if (!Params->size())
2807 return false;
2808
2809 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2810 Checker.TraverseType(T);
2811 return Checker.Match;
2812}
2813
2814// Find the source range corresponding to the named type in the given
2815// nested-name-specifier, if any.
2817 QualType T,
2818 const CXXScopeSpec &SS) {
2820 for (;;) {
2823 break;
2824 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2825 return NNSLoc.castAsTypeLoc().getSourceRange();
2826 // FIXME: This will always be empty.
2827 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2828 }
2829
2830 return SourceRange();
2831}
2832
2834 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2835 TemplateIdAnnotation *TemplateId,
2836 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2837 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2838 IsMemberSpecialization = false;
2839 Invalid = false;
2840
2841 // The sequence of nested types to which we will match up the template
2842 // parameter lists. We first build this list by starting with the type named
2843 // by the nested-name-specifier and walking out until we run out of types.
2844 SmallVector<QualType, 4> NestedTypes;
2845 QualType T;
2846 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2847 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2848 if (CXXRecordDecl *Record =
2849 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2850 T = Context.getCanonicalTagType(Record);
2851 else
2852 T = QualType(Qualifier.getAsType(), 0);
2853 }
2854
2855 // If we found an explicit specialization that prevents us from needing
2856 // 'template<>' headers, this will be set to the location of that
2857 // explicit specialization.
2858 SourceLocation ExplicitSpecLoc;
2859
2860 while (!T.isNull()) {
2861 NestedTypes.push_back(T);
2862
2863 // Retrieve the parent of a record type.
2864 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2865 // If this type is an explicit specialization, we're done.
2867 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2869 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2870 ExplicitSpecLoc = Spec->getLocation();
2871 break;
2872 }
2873 } else if (Record->getTemplateSpecializationKind()
2875 ExplicitSpecLoc = Record->getLocation();
2876 break;
2877 }
2878
2879 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2880 T = Context.getTypeDeclType(Parent);
2881 else
2882 T = QualType();
2883 continue;
2884 }
2885
2886 if (const TemplateSpecializationType *TST
2887 = T->getAs<TemplateSpecializationType>()) {
2888 TemplateName Name = TST->getTemplateName();
2889 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2890 // Look one step prior in a dependent template specialization type.
2891 if (NestedNameSpecifier NNS = DTS->getQualifier();
2893 T = QualType(NNS.getAsType(), 0);
2894 else
2895 T = QualType();
2896 continue;
2897 }
2898 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2900 T = Context.getTypeDeclType(Parent);
2901 else
2902 T = QualType();
2903 continue;
2904 }
2905 }
2906
2907 // Look one step prior in a dependent name type.
2908 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2909 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2911 T = QualType(NNS.getAsType(), 0);
2912 else
2913 T = QualType();
2914 continue;
2915 }
2916
2917 // Retrieve the parent of an enumeration type.
2918 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2919 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2920 // check here.
2921 EnumDecl *Enum = EnumT->getDecl();
2922
2923 // Get to the parent type.
2924 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2925 T = Context.getCanonicalTypeDeclType(Parent);
2926 else
2927 T = QualType();
2928 continue;
2929 }
2930
2931 T = QualType();
2932 }
2933 // Reverse the nested types list, since we want to traverse from the outermost
2934 // to the innermost while checking template-parameter-lists.
2935 std::reverse(NestedTypes.begin(), NestedTypes.end());
2936
2937 // C++0x [temp.expl.spec]p17:
2938 // A member or a member template may be nested within many
2939 // enclosing class templates. In an explicit specialization for
2940 // such a member, the member declaration shall be preceded by a
2941 // template<> for each enclosing class template that is
2942 // explicitly specialized.
2943 bool SawNonEmptyTemplateParameterList = false;
2944
2945 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2946 if (SawNonEmptyTemplateParameterList) {
2947 if (!SuppressDiagnostic)
2948 Diag(DeclLoc, diag::err_specialize_member_of_template)
2949 << !Recovery << Range;
2950 Invalid = true;
2951 IsMemberSpecialization = false;
2952 return true;
2953 }
2954
2955 return false;
2956 };
2957
2958 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2959 // Check that we can have an explicit specialization here.
2960 if (CheckExplicitSpecialization(Range, true))
2961 return true;
2962
2963 // We don't have a template header, but we should.
2964 SourceLocation ExpectedTemplateLoc;
2965 if (!ParamLists.empty())
2966 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2967 else
2968 ExpectedTemplateLoc = DeclStartLoc;
2969
2970 if (!SuppressDiagnostic)
2971 Diag(DeclLoc, diag::err_template_spec_needs_header)
2972 << Range
2973 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2974 return false;
2975 };
2976
2977 unsigned ParamIdx = 0;
2978 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2979 ++TypeIdx) {
2980 T = NestedTypes[TypeIdx];
2981
2982 // Whether we expect a 'template<>' header.
2983 bool NeedEmptyTemplateHeader = false;
2984
2985 // Whether we expect a template header with parameters.
2986 bool NeedNonemptyTemplateHeader = false;
2987
2988 // For a dependent type, the set of template parameters that we
2989 // expect to see.
2990 TemplateParameterList *ExpectedTemplateParams = nullptr;
2991
2992 // C++0x [temp.expl.spec]p15:
2993 // A member or a member template may be nested within many enclosing
2994 // class templates. In an explicit specialization for such a member, the
2995 // member declaration shall be preceded by a template<> for each
2996 // enclosing class template that is explicitly specialized.
2997 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2999 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3000 ExpectedTemplateParams = Partial->getTemplateParameters();
3001 NeedNonemptyTemplateHeader = true;
3002 } else if (Record->isDependentType()) {
3003 if (Record->getDescribedClassTemplate()) {
3004 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3005 ->getTemplateParameters();
3006 NeedNonemptyTemplateHeader = true;
3007 }
3008 } else if (ClassTemplateSpecializationDecl *Spec
3009 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3010 // C++0x [temp.expl.spec]p4:
3011 // Members of an explicitly specialized class template are defined
3012 // in the same manner as members of normal classes, and not using
3013 // the template<> syntax.
3014 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3015 NeedEmptyTemplateHeader = true;
3016 else
3017 continue;
3018 } else if (Record->getTemplateSpecializationKind()) {
3019 if (Record->getTemplateSpecializationKind()
3021 TypeIdx == NumTypes - 1)
3022 IsMemberSpecialization = true;
3023
3024 continue;
3025 }
3026 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3027 TemplateName Name = TST->getTemplateName();
3028 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3029 ExpectedTemplateParams = Template->getTemplateParameters();
3030 NeedNonemptyTemplateHeader = true;
3031 } else if (Name.getAsDeducedTemplateName()) {
3032 // FIXME: We actually could/should check the template arguments here
3033 // against the corresponding template parameter list.
3034 NeedNonemptyTemplateHeader = false;
3035 }
3036 }
3037
3038 // C++ [temp.expl.spec]p16:
3039 // In an explicit specialization declaration for a member of a class
3040 // template or a member template that appears in namespace scope, the
3041 // member template and some of its enclosing class templates may remain
3042 // unspecialized, except that the declaration shall not explicitly
3043 // specialize a class member template if its enclosing class templates
3044 // are not explicitly specialized as well.
3045 if (ParamIdx < ParamLists.size()) {
3046 if (ParamLists[ParamIdx]->size() == 0) {
3047 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3048 false))
3049 return nullptr;
3050 } else
3051 SawNonEmptyTemplateParameterList = true;
3052 }
3053
3054 if (NeedEmptyTemplateHeader) {
3055 // If we're on the last of the types, and we need a 'template<>' header
3056 // here, then it's a member specialization.
3057 if (TypeIdx == NumTypes - 1)
3058 IsMemberSpecialization = true;
3059
3060 if (ParamIdx < ParamLists.size()) {
3061 if (ParamLists[ParamIdx]->size() > 0) {
3062 // The header has template parameters when it shouldn't. Complain.
3063 if (!SuppressDiagnostic)
3064 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3065 diag::err_template_param_list_matches_nontemplate)
3066 << T
3067 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3068 ParamLists[ParamIdx]->getRAngleLoc())
3070 Invalid = true;
3071 return nullptr;
3072 }
3073
3074 // Consume this template header.
3075 ++ParamIdx;
3076 continue;
3077 }
3078
3079 if (!IsFriend)
3080 if (DiagnoseMissingExplicitSpecialization(
3082 return nullptr;
3083
3084 continue;
3085 }
3086
3087 if (NeedNonemptyTemplateHeader) {
3088 // In friend declarations we can have template-ids which don't
3089 // depend on the corresponding template parameter lists. But
3090 // assume that empty parameter lists are supposed to match this
3091 // template-id.
3092 if (IsFriend && T->isDependentType()) {
3093 if (ParamIdx < ParamLists.size() &&
3094 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3095 ExpectedTemplateParams = nullptr;
3096 else
3097 continue;
3098 }
3099
3100 if (ParamIdx < ParamLists.size()) {
3101 // Check the template parameter list, if we can.
3102 if (ExpectedTemplateParams &&
3104 ExpectedTemplateParams,
3105 !SuppressDiagnostic, TPL_TemplateMatch))
3106 Invalid = true;
3107
3108 if (!Invalid &&
3109 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3111 Invalid = true;
3112
3113 ++ParamIdx;
3114 continue;
3115 }
3116
3117 if (!SuppressDiagnostic)
3118 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3119 << T
3121 Invalid = true;
3122 continue;
3123 }
3124 }
3125
3126 // If there were at least as many template-ids as there were template
3127 // parameter lists, then there are no template parameter lists remaining for
3128 // the declaration itself.
3129 if (ParamIdx >= ParamLists.size()) {
3130 if (TemplateId && !IsFriend) {
3131 // We don't have a template header for the declaration itself, but we
3132 // should.
3133 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3134 TemplateId->RAngleLoc));
3135
3136 // Fabricate an empty template parameter list for the invented header.
3138 SourceLocation(), {},
3139 SourceLocation(), nullptr);
3140 }
3141
3142 return nullptr;
3143 }
3144
3145 // If there were too many template parameter lists, complain about that now.
3146 if (ParamIdx < ParamLists.size() - 1) {
3147 bool HasAnyExplicitSpecHeader = false;
3148 bool AllExplicitSpecHeaders = true;
3149 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3150 if (ParamLists[I]->size() == 0)
3151 HasAnyExplicitSpecHeader = true;
3152 else
3153 AllExplicitSpecHeaders = false;
3154 }
3155
3156 if (!SuppressDiagnostic)
3157 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3158 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3159 : diag::err_template_spec_extra_headers)
3160 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3161 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3162
3163 // If there was a specialization somewhere, such that 'template<>' is
3164 // not required, and there were any 'template<>' headers, note where the
3165 // specialization occurred.
3166 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3167 !SuppressDiagnostic)
3168 Diag(ExplicitSpecLoc,
3169 diag::note_explicit_template_spec_does_not_need_header)
3170 << NestedTypes.back();
3171
3172 // We have a template parameter list with no corresponding scope, which
3173 // means that the resulting template declaration can't be instantiated
3174 // properly (we'll end up with dependent nodes when we shouldn't).
3175 if (!AllExplicitSpecHeaders)
3176 Invalid = true;
3177 }
3178
3179 // C++ [temp.expl.spec]p16:
3180 // In an explicit specialization declaration for a member of a class
3181 // template or a member template that ap- pears in namespace scope, the
3182 // member template and some of its enclosing class templates may remain
3183 // unspecialized, except that the declaration shall not explicitly
3184 // specialize a class member template if its en- closing class templates
3185 // are not explicitly specialized as well.
3186 if (ParamLists.back()->size() == 0 &&
3187 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3188 false))
3189 return nullptr;
3190
3191 // Return the last template parameter list, which corresponds to the
3192 // entity being declared.
3193 return ParamLists.back();
3194}
3195
3197 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3198 Diag(Template->getLocation(), diag::note_template_declared_here)
3200 ? 0
3202 ? 1
3204 ? 2
3206 << Template->getDeclName();
3207 return;
3208 }
3209
3211 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3212 IEnd = OST->end();
3213 I != IEnd; ++I)
3214 Diag((*I)->getLocation(), diag::note_template_declared_here)
3215 << 0 << (*I)->getDeclName();
3216
3217 return;
3218 }
3219}
3220
3222 TemplateName BaseTemplate,
3223 SourceLocation TemplateLoc,
3225 auto lookUpCommonType = [&](TemplateArgument T1,
3226 TemplateArgument T2) -> QualType {
3227 // Don't bother looking for other specializations if both types are
3228 // builtins - users aren't allowed to specialize for them
3229 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3230 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3231 {T1, T2});
3232
3236 Args.addArgument(TemplateArgumentLoc(
3237 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3238
3239 EnterExpressionEvaluationContext UnevaluatedContext(
3241 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3243
3244 QualType BaseTemplateInst = S.CheckTemplateIdType(
3245 Keyword, BaseTemplate, TemplateLoc, Args,
3246 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3247
3248 if (SFINAE.hasErrorOccurred())
3249 return QualType();
3250
3251 return BaseTemplateInst;
3252 };
3253
3254 // Note A: For the common_type trait applied to a template parameter pack T of
3255 // types, the member type shall be either defined or not present as follows:
3256 switch (Ts.size()) {
3257
3258 // If sizeof...(T) is zero, there shall be no member type.
3259 case 0:
3260 return QualType();
3261
3262 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3263 // pack T. The member typedef-name type shall denote the same type, if any, as
3264 // common_type_t<T0, T0>; otherwise there shall be no member type.
3265 case 1:
3266 return lookUpCommonType(Ts[0], Ts[0]);
3267
3268 // If sizeof...(T) is two, let the first and second types constituting T be
3269 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3270 // as decay_t<T1> and decay_t<T2>, respectively.
3271 case 2: {
3272 QualType T1 = Ts[0].getAsType();
3273 QualType T2 = Ts[1].getAsType();
3274 QualType D1 = S.BuiltinDecay(T1, {});
3275 QualType D2 = S.BuiltinDecay(T2, {});
3276
3277 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3278 // the same type, if any, as common_type_t<D1, D2>.
3279 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3280 return lookUpCommonType(D1, D2);
3281
3282 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3283 // denotes a valid type, let C denote that type.
3284 {
3285 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3286 EnterExpressionEvaluationContext UnevaluatedContext(
3288 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3290
3291 // false
3293 VK_PRValue);
3294 ExprResult Cond = &CondExpr;
3295
3296 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3297 if (ConstRefQual) {
3298 D1.addConst();
3299 D2.addConst();
3300 }
3301
3302 // declval<D1>()
3303 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3304 ExprResult LHS = &LHSExpr;
3305
3306 // declval<D2>()
3307 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3308 ExprResult RHS = &RHSExpr;
3309
3312
3313 // decltype(false ? declval<D1>() : declval<D2>())
3315 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3316
3317 if (Result.isNull() || SFINAE.hasErrorOccurred())
3318 return QualType();
3319
3320 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3321 return S.BuiltinDecay(Result, TemplateLoc);
3322 };
3323
3324 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3325 return Res;
3326
3327 // Let:
3328 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3329 // COND-RES(X, Y) be
3330 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3331
3332 // C++20 only
3333 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3334 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3335 if (!S.Context.getLangOpts().CPlusPlus20)
3336 return QualType();
3337 return CheckConditionalOperands(true);
3338 }
3339 }
3340
3341 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3342 // denote the first, second, and (pack of) remaining types constituting T. Let
3343 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3344 // a type C, the member typedef-name type shall denote the same type, if any,
3345 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3346 default: {
3347 QualType Result = Ts.front().getAsType();
3348 for (auto T : llvm::drop_begin(Ts)) {
3349 Result = lookUpCommonType(Result, T.getAsType());
3350 if (Result.isNull())
3351 return QualType();
3352 }
3353 return Result;
3354 }
3355 }
3356}
3357
3358static bool isInVkNamespace(const RecordType *RT) {
3359 DeclContext *DC = RT->getDecl()->getDeclContext();
3360 if (!DC)
3361 return false;
3362
3363 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3364 if (!ND)
3365 return false;
3366
3367 return ND->getQualifiedNameAsString() == "hlsl::vk";
3368}
3369
3370static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3371 QualType OperandArg,
3372 SourceLocation Loc) {
3373 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3374 bool Literal = false;
3375 SourceLocation LiteralLoc;
3376 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3377 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3378 assert(SpecDecl);
3379
3380 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3381 QualType ConstantType = LiteralArgs[0].getAsType();
3382 RT = ConstantType->getAsCanonical<RecordType>();
3383 Literal = true;
3384 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3385 }
3386
3387 if (RT && isInVkNamespace(RT) &&
3388 RT->getDecl()->getName() == "integral_constant") {
3389 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3390 assert(SpecDecl);
3391
3392 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3393
3394 QualType ConstantType = ConstantArgs[0].getAsType();
3395 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3396
3397 if (Literal)
3398 return SpirvOperand::createLiteral(Value);
3399 return SpirvOperand::createConstant(ConstantType, Value);
3400 } else if (Literal) {
3401 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3402 return SpirvOperand();
3403 }
3404 }
3405 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3406 diag::err_call_incomplete_argument))
3407 return SpirvOperand();
3408 return SpirvOperand::createType(OperandArg);
3409}
3410
3413 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3414 TemplateArgumentListInfo &TemplateArgs) {
3415 ASTContext &Context = SemaRef.getASTContext();
3416
3417 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3418 "Builtin template arguments do not match its parameters");
3419
3420 switch (BTD->getBuiltinTemplateKind()) {
3421 case BTK__make_integer_seq: {
3422 // Specializations of __make_integer_seq<S, T, N> are treated like
3423 // S<T, 0, ..., N-1>.
3424
3425 QualType OrigType = Converted[1].getAsType();
3426 // C++14 [inteseq.intseq]p1:
3427 // T shall be an integer type.
3428 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3429 SemaRef.Diag(TemplateArgs[1].getLocation(),
3430 diag::err_integer_sequence_integral_element_type);
3431 return QualType();
3432 }
3433
3434 TemplateArgument NumArgsArg = Converted[2];
3435 if (NumArgsArg.isDependent())
3436 return QualType();
3437
3438 TemplateArgumentListInfo SyntheticTemplateArgs;
3439 // The type argument, wrapped in substitution sugar, gets reused as the
3440 // first template argument in the synthetic template argument list.
3441 SyntheticTemplateArgs.addArgument(
3444 OrigType, TemplateArgs[1].getLocation())));
3445
3446 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3447 // Expand N into 0 ... N-1.
3448 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3449 I < NumArgs; ++I) {
3450 TemplateArgument TA(Context, I, OrigType);
3451 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3452 TA, OrigType, TemplateArgs[2].getLocation()));
3453 }
3454 } else {
3455 // C++14 [inteseq.make]p1:
3456 // If N is negative the program is ill-formed.
3457 SemaRef.Diag(TemplateArgs[2].getLocation(),
3458 diag::err_integer_sequence_negative_length);
3459 return QualType();
3460 }
3461
3462 // The first template argument will be reused as the template decl that
3463 // our synthetic template arguments will be applied to.
3464 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3465 TemplateLoc, SyntheticTemplateArgs,
3466 /*Scope=*/nullptr,
3467 /*ForNestedNameSpecifier=*/false);
3468 }
3469
3470 case BTK__type_pack_element: {
3471 // Specializations of
3472 // __type_pack_element<Index, T_1, ..., T_N>
3473 // are treated like T_Index.
3474 assert(Converted.size() == 2 &&
3475 "__type_pack_element should be given an index and a parameter pack");
3476
3477 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3478 if (IndexArg.isDependent() || Ts.isDependent())
3479 return QualType();
3480
3481 llvm::APSInt Index = IndexArg.getAsIntegral();
3482 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3483 "type std::size_t, and hence be non-negative");
3484 // If the Index is out of bounds, the program is ill-formed.
3485 if (Index >= Ts.pack_size()) {
3486 SemaRef.Diag(TemplateArgs[0].getLocation(),
3487 diag::err_type_pack_element_out_of_bounds);
3488 return QualType();
3489 }
3490
3491 // We simply return the type at index `Index`.
3492 int64_t N = Index.getExtValue();
3493 return Ts.getPackAsArray()[N].getAsType();
3494 }
3495
3496 case BTK__builtin_common_type: {
3497 assert(Converted.size() == 4);
3498 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3499 return QualType();
3500
3501 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3502 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3503 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3504 TemplateLoc, Ts);
3505 !CT.isNull()) {
3509 CT, TemplateArgs[1].getLocation())));
3510 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3511 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3512 TAs, /*Scope=*/nullptr,
3513 /*ForNestedNameSpecifier=*/false);
3514 }
3515 QualType HasNoTypeMember = Converted[2].getAsType();
3516 return HasNoTypeMember;
3517 }
3518
3519 case BTK__hlsl_spirv_type: {
3520 assert(Converted.size() == 4);
3521
3522 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3523 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3524 }
3525
3526 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3527 return QualType();
3528
3529 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3530 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3531 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3532
3533 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3534
3536
3537 for (auto &OperandTA : OperandArgs) {
3538 QualType OperandArg = OperandTA.getAsType();
3539 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3540 TemplateArgs[3].getLocation());
3541 if (!Operand.isValid())
3542 return QualType();
3543 Operands.push_back(Operand);
3544 }
3545
3546 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3547 }
3548 case BTK__builtin_dedup_pack: {
3549 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3550 "a parameter pack");
3551 TemplateArgument Ts = Converted[0];
3552 // Delay the computation until we can compute the final result. We choose
3553 // not to remove the duplicates upfront before substitution to keep the code
3554 // simple.
3555 if (Ts.isDependent())
3556 return QualType();
3557 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3559 llvm::SmallDenseSet<QualType> Seen;
3560 // Synthesize a new template argument list, removing duplicates.
3561 for (auto T : Ts.getPackAsArray()) {
3562 assert(T.getKind() == clang::TemplateArgument::Type);
3563 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3564 continue;
3565 OutArgs.push_back(T);
3566 }
3567 return Context.getSubstBuiltinTemplatePack(
3568 TemplateArgument::CreatePackCopy(Context, OutArgs));
3569 }
3570 }
3571 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3572}
3573
3574/// Determine whether this alias template is "enable_if_t".
3575/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3577 return AliasTemplate->getName() == "enable_if_t" ||
3578 AliasTemplate->getName() == "__enable_if_t";
3579}
3580
3581/// Collect all of the separable terms in the given condition, which
3582/// might be a conjunction.
3583///
3584/// FIXME: The right answer is to convert the logical expression into
3585/// disjunctive normal form, so we can find the first failed term
3586/// within each possible clause.
3587static void collectConjunctionTerms(Expr *Clause,
3588 SmallVectorImpl<Expr *> &Terms) {
3589 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3590 if (BinOp->getOpcode() == BO_LAnd) {
3591 collectConjunctionTerms(BinOp->getLHS(), Terms);
3592 collectConjunctionTerms(BinOp->getRHS(), Terms);
3593 return;
3594 }
3595 }
3596
3597 Terms.push_back(Clause);
3598}
3599
3600// The ranges-v3 library uses an odd pattern of a top-level "||" with
3601// a left-hand side that is value-dependent but never true. Identify
3602// the idiom and ignore that term.
3604 // Top-level '||'.
3605 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3606 if (!BinOp) return Cond;
3607
3608 if (BinOp->getOpcode() != BO_LOr) return Cond;
3609
3610 // With an inner '==' that has a literal on the right-hand side.
3611 Expr *LHS = BinOp->getLHS();
3612 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3613 if (!InnerBinOp) return Cond;
3614
3615 if (InnerBinOp->getOpcode() != BO_EQ ||
3616 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3617 return Cond;
3618
3619 // If the inner binary operation came from a macro expansion named
3620 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3621 // of the '||', which is the real, user-provided condition.
3622 SourceLocation Loc = InnerBinOp->getExprLoc();
3623 if (!Loc.isMacroID()) return Cond;
3624
3625 StringRef MacroName = PP.getImmediateMacroName(Loc);
3626 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3627 return BinOp->getRHS();
3628
3629 return Cond;
3630}
3631
3632namespace {
3633
3634// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3635// within failing boolean expression, such as substituting template parameters
3636// for actual types.
3637class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3638public:
3639 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3640 : Policy(P) {}
3641
3642 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3643 const auto *DR = dyn_cast<DeclRefExpr>(E);
3644 if (DR && DR->getQualifier()) {
3645 // If this is a qualified name, expand the template arguments in nested
3646 // qualifiers.
3647 DR->getQualifier().print(OS, Policy, true);
3648 // Then print the decl itself.
3649 const ValueDecl *VD = DR->getDecl();
3650 OS << VD->getName();
3651 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3652 // This is a template variable, print the expanded template arguments.
3653 printTemplateArgumentList(
3654 OS, IV->getTemplateArgs().asArray(), Policy,
3655 IV->getSpecializedTemplate()->getTemplateParameters());
3656 }
3657 return true;
3658 }
3659 return false;
3660 }
3661
3662private:
3663 const PrintingPolicy Policy;
3664};
3665
3666} // end anonymous namespace
3667
3668std::pair<Expr *, std::string>
3671
3672 // Separate out all of the terms in a conjunction.
3675
3676 // Determine which term failed.
3677 Expr *FailedCond = nullptr;
3678 for (Expr *Term : Terms) {
3679 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3680
3681 // Literals are uninteresting.
3682 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3683 isa<IntegerLiteral>(TermAsWritten))
3684 continue;
3685
3686 // The initialization of the parameter from the argument is
3687 // a constant-evaluated context.
3690
3691 bool Succeeded;
3692 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3693 !Succeeded) {
3694 FailedCond = TermAsWritten;
3695 break;
3696 }
3697 }
3698 if (!FailedCond)
3699 FailedCond = Cond->IgnoreParenImpCasts();
3700
3701 std::string Description;
3702 {
3703 llvm::raw_string_ostream Out(Description);
3705 Policy.PrintAsCanonical = true;
3706 FailedBooleanConditionPrinterHelper Helper(Policy);
3707 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3708 }
3709 return { FailedCond, Description };
3710}
3711
3712static TemplateName
3714 const AssumedTemplateStorage *ATN,
3715 SourceLocation NameLoc) {
3716 // We assumed this undeclared identifier to be an (ADL-only) function
3717 // template name, but it was used in a context where a type was required.
3718 // Try to typo-correct it now.
3719 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3720 struct CandidateCallback : CorrectionCandidateCallback {
3721 bool ValidateCandidate(const TypoCorrection &TC) override {
3722 return TC.getCorrectionDecl() &&
3724 }
3725 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3726 return std::make_unique<CandidateCallback>(*this);
3727 }
3728 } FilterCCC;
3729
3730 TypoCorrection Corrected =
3731 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3732 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3733 if (Corrected && Corrected.getFoundDecl()) {
3734 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3735 << ATN->getDeclName());
3737 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3739 }
3740
3741 return TemplateName();
3742}
3743
3745 TemplateName Name,
3746 SourceLocation TemplateLoc,
3747 TemplateArgumentListInfo &TemplateArgs,
3748 Scope *Scope, bool ForNestedNameSpecifier) {
3749 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3750
3751 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3752 if (!Template) {
3753 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3754 Template = S->getParameterPack();
3755 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3756 if (DTN->getName().getIdentifier())
3757 // When building a template-id where the template-name is dependent,
3758 // assume the template is a type template. Either our assumption is
3759 // correct, or the code is ill-formed and will be diagnosed when the
3760 // dependent name is substituted.
3761 return Context.getTemplateSpecializationType(Keyword, Name,
3762 TemplateArgs.arguments(),
3763 /*CanonicalArgs=*/{});
3764 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3766 *this, Scope, ATN, TemplateLoc);
3767 CorrectedName.isNull()) {
3768 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3769 return QualType();
3770 } else {
3771 Name = CorrectedName;
3772 Template = Name.getAsTemplateDecl();
3773 }
3774 }
3775 }
3776 if (!Template ||
3778 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3779 if (ForNestedNameSpecifier)
3780 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3781 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3782 else
3783 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3785 return QualType();
3786 }
3787
3788 // Check that the template argument list is well-formed for this
3789 // template.
3791 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3792 DefaultArgs, /*PartialTemplateArgs=*/false,
3793 CTAI,
3794 /*UpdateArgsWithConversions=*/true))
3795 return QualType();
3796
3797 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3798 // and there are no diagnsotics currently implemented for TemplateDecls,
3799 // so avoid doing it for now.
3800 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3801
3802 QualType CanonType;
3803
3805 // We might have a substituted template template parameter pack. If so,
3806 // build a template specialization type for it.
3808 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3809
3810 // C++0x [dcl.type.elab]p2:
3811 // If the identifier resolves to a typedef-name or the simple-template-id
3812 // resolves to an alias template specialization, the
3813 // elaborated-type-specifier is ill-formed.
3816 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3819 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3820 }
3821
3822 // Find the canonical type for this type alias template specialization.
3823 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3824
3825 // Diagnose uses of the pattern of this template.
3826 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3827 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3828
3829 if (Pattern->isInvalidDecl())
3830 return QualType();
3831
3832 // Only substitute for the innermost template argument list.
3833 MultiLevelTemplateArgumentList TemplateArgLists;
3835 /*Final=*/true);
3836 TemplateArgLists.addOuterRetainedLevels(
3837 AliasTemplate->getTemplateParameters()->getDepth());
3838
3840
3841 // FIXME: The TemplateArgs passed here are not used for the context note,
3842 // nor they should, because this note will be pointing to the specialization
3843 // anyway. These arguments are needed for a hack for instantiating lambdas
3844 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3845 // arguments will be used for collating the template arguments needed to
3846 // instantiate the lambda.
3847 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3848 /*Entity=*/AliasTemplate,
3849 /*TemplateArgs=*/CTAI.SugaredConverted);
3850 if (Inst.isInvalid())
3851 return QualType();
3852
3853 std::optional<ContextRAII> SavedContext;
3854 if (!AliasTemplate->getDeclContext()->isFileContext())
3855 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3856
3857 CanonType =
3858 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3859 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3860 if (CanonType.isNull()) {
3861 // If this was enable_if and we failed to find the nested type
3862 // within enable_if in a SFINAE context, dig out the specific
3863 // enable_if condition that failed and present that instead.
3865 if (SFINAETrap *Trap = getSFINAEContext();
3866 TemplateDeductionInfo *DeductionInfo =
3867 Trap ? Trap->getDeductionInfo() : nullptr) {
3868 if (DeductionInfo->hasSFINAEDiagnostic() &&
3869 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3870 diag::err_typename_nested_not_found_enable_if &&
3871 TemplateArgs[0].getArgument().getKind() ==
3873 Expr *FailedCond;
3874 std::string FailedDescription;
3875 std::tie(FailedCond, FailedDescription) =
3876 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3877
3878 // Remove the old SFINAE diagnostic.
3879 PartialDiagnosticAt OldDiag =
3881 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3882
3883 // Add a new SFINAE diagnostic specifying which condition
3884 // failed.
3885 DeductionInfo->addSFINAEDiagnostic(
3886 OldDiag.first,
3887 PDiag(diag::err_typename_nested_not_found_requirement)
3888 << FailedDescription << FailedCond->getSourceRange());
3889 }
3890 }
3891 }
3892
3893 return QualType();
3894 }
3895 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3896 CanonType = checkBuiltinTemplateIdType(
3897 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3898 } else if (Name.isDependent() ||
3899 TemplateSpecializationType::anyDependentTemplateArguments(
3900 TemplateArgs, CTAI.CanonicalConverted)) {
3901 // This class template specialization is a dependent
3902 // type. Therefore, its canonical type is another class template
3903 // specialization type that contains all of the converted
3904 // arguments in canonical form. This ensures that, e.g., A<T> and
3905 // A<T, T> have identical types when A is declared as:
3906 //
3907 // template<typename T, typename U = T> struct A;
3908 CanonType = Context.getCanonicalTemplateSpecializationType(
3910 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3911 CTAI.CanonicalConverted);
3912 assert(CanonType->isCanonicalUnqualified());
3913
3914 // This might work out to be a current instantiation, in which
3915 // case the canonical type needs to be the InjectedClassNameType.
3916 //
3917 // TODO: in theory this could be a simple hashtable lookup; most
3918 // changes to CurContext don't change the set of current
3919 // instantiations.
3921 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3922 // If we get out to a namespace, we're done.
3923 if (Ctx->isFileContext()) break;
3924
3925 // If this isn't a record, keep looking.
3926 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3927 if (!Record) continue;
3928
3929 // Look for one of the two cases with InjectedClassNameTypes
3930 // and check whether it's the same template.
3932 !Record->getDescribedClassTemplate())
3933 continue;
3934
3935 // Fetch the injected class name type and check whether its
3936 // injected type is equal to the type we just built.
3937 CanQualType ICNT = Context.getCanonicalTagType(Record);
3938 CanQualType Injected =
3939 Record->getCanonicalTemplateSpecializationType(Context);
3940
3941 if (CanonType != Injected)
3942 continue;
3943
3944 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3945 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3946
3947 // If so, the canonical type of this TST is the injected
3948 // class name type of the record we just found.
3949 CanonType = ICNT;
3950 break;
3951 }
3952 }
3953 } else if (ClassTemplateDecl *ClassTemplate =
3954 dyn_cast<ClassTemplateDecl>(Template)) {
3955 // Find the class template specialization declaration that
3956 // corresponds to these arguments.
3957 void *InsertPos = nullptr;
3959 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3960 if (!Decl) {
3961 // This is the first time we have referenced this class template
3962 // specialization. Create the canonical declaration and add it to
3963 // the set of specializations.
3965 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3966 ClassTemplate->getDeclContext(),
3967 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3968 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3969 CTAI.StrictPackMatch, nullptr);
3970 ClassTemplate->AddSpecialization(Decl, InsertPos);
3971 if (ClassTemplate->isOutOfLine())
3972 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3973 }
3974
3975 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3976 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3977 NonSFINAEContext _(*this);
3978 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3979 if (!Inst.isInvalid()) {
3981 CTAI.CanonicalConverted,
3982 /*Final=*/false);
3983 InstantiateAttrsForDecl(TemplateArgLists,
3984 ClassTemplate->getTemplatedDecl(), Decl);
3985 }
3986 }
3987
3988 // Diagnose uses of this specialization.
3989 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3990 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
3991
3992 CanonType = Context.getCanonicalTagType(Decl);
3993 assert(isa<RecordType>(CanonType) &&
3994 "type of non-dependent specialization is not a RecordType");
3995 } else {
3996 llvm_unreachable("Unhandled template kind");
3997 }
3998
3999 // Build the fully-sugared type for this class template
4000 // specialization, which refers back to the class template
4001 // specialization we created or found.
4002 return Context.getTemplateSpecializationType(
4003 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4004 CanonType);
4005}
4006
4008 TemplateNameKind &TNK,
4009 SourceLocation NameLoc,
4010 IdentifierInfo *&II) {
4011 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4012
4013 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4014 assert(ATN && "not an assumed template name");
4015 II = ATN->getDeclName().getAsIdentifierInfo();
4016
4017 if (TemplateName Name =
4018 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4019 !Name.isNull()) {
4020 // Resolved to a type template name.
4021 ParsedName = TemplateTy::make(Name);
4022 TNK = TNK_Type_template;
4023 }
4024}
4025
4027 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4028 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4029 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4030 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4031 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4032 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4033 ImplicitTypenameContext AllowImplicitTypename) {
4034 if (SS.isInvalid())
4035 return true;
4036
4037 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4038 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4039
4040 // C++ [temp.res]p3:
4041 // A qualified-id that refers to a type and in which the
4042 // nested-name-specifier depends on a template-parameter (14.6.2)
4043 // shall be prefixed by the keyword typename to indicate that the
4044 // qualified-id denotes a type, forming an
4045 // elaborated-type-specifier (7.1.5.3).
4046 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4047 // C++2a relaxes some of those restrictions in [temp.res]p5.
4048 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4049 SS.getScopeRep(), TemplateII);
4051 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4052 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4053 << NNS;
4054 if (!getLangOpts().CPlusPlus20)
4055 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4056 } else
4057 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4058
4059 // FIXME: This is not quite correct recovery as we don't transform SS
4060 // into the corresponding dependent form (and we don't diagnose missing
4061 // 'template' keywords within SS as a result).
4062 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4063 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4064 TemplateArgsIn, RAngleLoc);
4065 }
4066
4067 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4068 // it's not actually allowed to be used as a type in most cases. Because
4069 // we annotate it before we know whether it's valid, we have to check for
4070 // this case here.
4071 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4072 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4073 Diag(TemplateIILoc,
4074 TemplateKWLoc.isInvalid()
4075 ? diag::err_out_of_line_qualified_id_type_names_constructor
4076 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4077 << TemplateII << 0 /*injected-class-name used as template name*/
4078 << 1 /*if any keyword was present, it was 'template'*/;
4079 }
4080 }
4081
4082 // Translate the parser's template argument list in our AST format.
4083 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4084 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4085
4087 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4088 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4089 if (SpecTy.isNull())
4090 return true;
4091
4092 // Build type-source information.
4093 TypeLocBuilder TLB;
4094 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4095 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4096 TemplateIILoc, TemplateArgs);
4097 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4098}
4099
4101 TypeSpecifierType TagSpec,
4102 SourceLocation TagLoc,
4103 CXXScopeSpec &SS,
4104 SourceLocation TemplateKWLoc,
4105 TemplateTy TemplateD,
4106 SourceLocation TemplateLoc,
4107 SourceLocation LAngleLoc,
4108 ASTTemplateArgsPtr TemplateArgsIn,
4109 SourceLocation RAngleLoc) {
4110 if (SS.isInvalid())
4111 return TypeResult(true);
4112
4113 // Translate the parser's template argument list in our AST format.
4114 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4115 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4116
4117 // Determine the tag kind
4121
4123 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4124 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4125 if (Result.isNull())
4126 return TypeResult(true);
4127
4128 // Check the tag kind
4129 if (const RecordType *RT = Result->getAs<RecordType>()) {
4130 RecordDecl *D = RT->getDecl();
4131
4132 IdentifierInfo *Id = D->getIdentifier();
4133 assert(Id && "templated class must have an identifier");
4134
4136 TagLoc, Id)) {
4137 Diag(TagLoc, diag::err_use_with_wrong_tag)
4138 << Result
4140 Diag(D->getLocation(), diag::note_previous_use);
4141 }
4142 }
4143
4144 // Provide source-location information for the template specialization.
4145 TypeLocBuilder TLB;
4147 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4148 TemplateArgs);
4150}
4151
4152static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4153 NamedDecl *PrevDecl,
4154 SourceLocation Loc,
4156
4158
4160 unsigned Depth,
4161 unsigned Index) {
4162 switch (Arg.getKind()) {
4170 return false;
4171
4173 QualType Type = Arg.getAsType();
4174 const TemplateTypeParmType *TPT =
4175 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4176 return TPT && !Type.hasQualifiers() &&
4177 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4178 }
4179
4181 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4182 if (!DRE || !DRE->getDecl())
4183 return false;
4184 const NonTypeTemplateParmDecl *NTTP =
4185 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4186 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4187 }
4188
4190 const TemplateTemplateParmDecl *TTP =
4191 dyn_cast_or_null<TemplateTemplateParmDecl>(
4193 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4194 }
4195 llvm_unreachable("unexpected kind of template argument");
4196}
4197
4199 TemplateParameterList *SpecParams,
4201 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4202 return false;
4203
4204 unsigned Depth = Params->getDepth();
4205
4206 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4207 TemplateArgument Arg = Args[I];
4208
4209 // If the parameter is a pack expansion, the argument must be a pack
4210 // whose only element is a pack expansion.
4211 if (Params->getParam(I)->isParameterPack()) {
4212 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4213 !Arg.pack_begin()->isPackExpansion())
4214 return false;
4215 Arg = Arg.pack_begin()->getPackExpansionPattern();
4216 }
4217
4218 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4219 return false;
4220
4221 // For NTTPs further specialization is allowed via deduced types, so
4222 // we need to make sure to only reject here if primary template and
4223 // specialization use the same type for the NTTP.
4224 if (auto *SpecNTTP =
4225 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4226 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4227 if (!NTTP || NTTP->getType().getCanonicalType() !=
4228 SpecNTTP->getType().getCanonicalType())
4229 return false;
4230 }
4231 }
4232
4233 return true;
4234}
4235
4236template<typename PartialSpecDecl>
4237static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4238 if (Partial->getDeclContext()->isDependentContext())
4239 return;
4240
4241 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4242 // for non-substitution-failure issues?
4243 TemplateDeductionInfo Info(Partial->getLocation());
4244 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4245 return;
4246
4247 auto *Template = Partial->getSpecializedTemplate();
4248 S.Diag(Partial->getLocation(),
4249 diag::ext_partial_spec_not_more_specialized_than_primary)
4251
4252 if (Info.hasSFINAEDiagnostic()) {
4256 SmallString<128> SFINAEArgString;
4257 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4258 S.Diag(Diag.first,
4259 diag::note_partial_spec_not_more_specialized_than_primary)
4260 << SFINAEArgString;
4261 }
4262
4264 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4265 Template->getAssociatedConstraints(TemplateAC);
4266 Partial->getAssociatedConstraints(PartialAC);
4268 TemplateAC);
4269}
4270
4271static void
4273 const llvm::SmallBitVector &DeducibleParams) {
4274 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4275 if (!DeducibleParams[I]) {
4276 NamedDecl *Param = TemplateParams->getParam(I);
4277 if (Param->getDeclName())
4278 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4279 << Param->getDeclName();
4280 else
4281 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4282 << "(anonymous)";
4283 }
4284 }
4285}
4286
4287
4288template<typename PartialSpecDecl>
4290 PartialSpecDecl *Partial) {
4291 // C++1z [temp.class.spec]p8: (DR1495)
4292 // - The specialization shall be more specialized than the primary
4293 // template (14.5.5.2).
4295
4296 // C++ [temp.class.spec]p8: (DR1315)
4297 // - Each template-parameter shall appear at least once in the
4298 // template-id outside a non-deduced context.
4299 // C++1z [temp.class.spec.match]p3 (P0127R2)
4300 // If the template arguments of a partial specialization cannot be
4301 // deduced because of the structure of its template-parameter-list
4302 // and the template-id, the program is ill-formed.
4303 auto *TemplateParams = Partial->getTemplateParameters();
4304 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4305 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4306 TemplateParams->getDepth(), DeducibleParams);
4307
4308 if (!DeducibleParams.all()) {
4309 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4310 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4312 << (NumNonDeducible > 1)
4313 << SourceRange(Partial->getLocation(),
4314 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4315 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4316 }
4317}
4318
4323
4328
4330 // C++1z [temp.param]p11:
4331 // A template parameter of a deduction guide template that does not have a
4332 // default-argument shall be deducible from the parameter-type-list of the
4333 // deduction guide template.
4334 auto *TemplateParams = TD->getTemplateParameters();
4335 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4336 MarkDeducedTemplateParameters(TD, DeducibleParams);
4337 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4338 // A parameter pack is deducible (to an empty pack).
4339 auto *Param = TemplateParams->getParam(I);
4340 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4341 DeducibleParams[I] = true;
4342 }
4343
4344 if (!DeducibleParams.all()) {
4345 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4346 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4347 << (NumNonDeducible > 1);
4348 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4349 }
4350}
4351
4354 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4356 // D must be variable template id.
4358 "Variable template specialization is declared with a template id.");
4359
4360 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4361 TemplateArgumentListInfo TemplateArgs =
4362 makeTemplateArgumentListInfo(*this, *TemplateId);
4363 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4364 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4365 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4366
4367 TemplateName Name = TemplateId->Template.get();
4368
4369 // The template-id must name a variable template.
4371 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4372 if (!VarTemplate) {
4373 NamedDecl *FnTemplate;
4374 if (auto *OTS = Name.getAsOverloadedTemplate())
4375 FnTemplate = *OTS->begin();
4376 else
4377 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4378 if (FnTemplate)
4379 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4380 << FnTemplate->getDeclName();
4381 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4383 }
4384
4385 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4386 auto Message = DSA->getMessage();
4387 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4388 << VarTemplate << !Message.empty() << Message;
4389 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4390 }
4391
4392 // Check for unexpanded parameter packs in any of the template arguments.
4393 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4394 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4398 return true;
4399
4400 // Check that the template argument list is well-formed for this
4401 // template.
4403 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4404 /*DefaultArgs=*/{},
4405 /*PartialTemplateArgs=*/false, CTAI,
4406 /*UpdateArgsWithConversions=*/true))
4407 return true;
4408
4409 // Find the variable template (partial) specialization declaration that
4410 // corresponds to these arguments.
4413 TemplateArgs.size(),
4414 CTAI.CanonicalConverted))
4415 return true;
4416
4417 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4418 // we also do them during instantiation.
4419 if (!Name.isDependent() &&
4420 !TemplateSpecializationType::anyDependentTemplateArguments(
4421 TemplateArgs, CTAI.CanonicalConverted)) {
4422 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4423 << VarTemplate->getDeclName();
4425 }
4426
4427 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4428 TemplateParams, CTAI.CanonicalConverted) &&
4429 (!Context.getLangOpts().CPlusPlus20 ||
4430 !TemplateParams->hasAssociatedConstraints())) {
4431 // C++ [temp.class.spec]p9b3:
4432 //
4433 // -- The argument list of the specialization shall not be identical
4434 // to the implicit argument list of the primary template.
4435 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4436 << /*variable template*/ 1
4437 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4438 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4439 // FIXME: Recover from this by treating the declaration as a
4440 // redeclaration of the primary template.
4441 return true;
4442 }
4443 }
4444
4445 void *InsertPos = nullptr;
4446 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4447
4449 PrevDecl = VarTemplate->findPartialSpecialization(
4450 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4451 else
4452 PrevDecl =
4453 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4454
4456
4457 // Check whether we can declare a variable template specialization in
4458 // the current scope.
4459 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4460 TemplateNameLoc,
4462 return true;
4463
4464 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4465 // Since the only prior variable template specialization with these
4466 // arguments was referenced but not declared, reuse that
4467 // declaration node as our own, updating its source location and
4468 // the list of outer template parameters to reflect our new declaration.
4469 Specialization = PrevDecl;
4470 Specialization->setLocation(TemplateNameLoc);
4471 PrevDecl = nullptr;
4472 } else if (IsPartialSpecialization) {
4473 // Create a new class template partial specialization declaration node.
4475 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4478 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4479 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4480 SC, CTAI.CanonicalConverted);
4481 Partial->setTemplateArgsAsWritten(TemplateArgs);
4482
4483 if (!PrevPartial)
4484 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4485 Specialization = Partial;
4486
4488 } else {
4489 // Create a new class template specialization declaration node for
4490 // this explicit specialization or friend declaration.
4492 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4493 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4494 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4495
4496 if (!PrevDecl)
4497 VarTemplate->AddSpecialization(Specialization, InsertPos);
4498 }
4499
4500 // C++ [temp.expl.spec]p6:
4501 // If a template, a member template or the member of a class template is
4502 // explicitly specialized then that specialization shall be declared
4503 // before the first use of that specialization that would cause an implicit
4504 // instantiation to take place, in every translation unit in which such a
4505 // use occurs; no diagnostic is required.
4506 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4507 bool Okay = false;
4508 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4509 // Is there any previous explicit specialization declaration?
4511 Okay = true;
4512 break;
4513 }
4514 }
4515
4516 if (!Okay) {
4517 SourceRange Range(TemplateNameLoc, RAngleLoc);
4518 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4519 << Name << Range;
4520
4521 Diag(PrevDecl->getPointOfInstantiation(),
4522 diag::note_instantiation_required_here)
4523 << (PrevDecl->getTemplateSpecializationKind() !=
4525 return true;
4526 }
4527 }
4528
4529 Specialization->setLexicalDeclContext(CurContext);
4530
4531 // Add the specialization into its lexical context, so that it can
4532 // be seen when iterating through the list of declarations in that
4533 // context. However, specializations are not found by name lookup.
4534 CurContext->addDecl(Specialization);
4535
4536 // Note that this is an explicit specialization.
4537 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4538
4539 Previous.clear();
4540 if (PrevDecl)
4541 Previous.addDecl(PrevDecl);
4542 else if (Specialization->isStaticDataMember() &&
4543 Specialization->isOutOfLine())
4544 Specialization->setAccess(VarTemplate->getAccess());
4545
4546 return Specialization;
4547}
4548
4549namespace {
4550/// A partial specialization whose template arguments have matched
4551/// a given template-id.
4552struct PartialSpecMatchResult {
4555};
4556
4557// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4558// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4559static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4560 if (Var->getName() != "format_kind" ||
4561 !Var->getDeclContext()->isStdNamespace())
4562 return false;
4563
4564 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4565 // release in which users can access std::format_kind.
4566 // We can use 20250520 as the final date, see the following commits.
4567 // GCC releases/gcc-15 branch:
4568 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4569 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4570 // GCC master branch:
4571 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4572 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4573 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4574}
4575} // end anonymous namespace
4576
4579 SourceLocation TemplateNameLoc,
4580 const TemplateArgumentListInfo &TemplateArgs,
4581 bool SetWrittenArgs) {
4582 assert(Template && "A variable template id without template?");
4583
4584 // Check that the template argument list is well-formed for this template.
4587 Template, TemplateNameLoc,
4588 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4589 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4590 /*UpdateArgsWithConversions=*/true))
4591 return true;
4592
4593 // Produce a placeholder value if the specialization is dependent.
4594 if (Template->getDeclContext()->isDependentContext() ||
4595 TemplateSpecializationType::anyDependentTemplateArguments(
4596 TemplateArgs, CTAI.CanonicalConverted)) {
4597 if (ParsingInitForAutoVars.empty())
4598 return DeclResult();
4599
4600 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4601 const TemplateArgument &Arg2) {
4602 return Context.isSameTemplateArgument(Arg1, Arg2);
4603 };
4604
4605 if (VarDecl *Var = Template->getTemplatedDecl();
4606 ParsingInitForAutoVars.count(Var) &&
4607 // See comments on this function definition
4608 !IsLibstdcxxStdFormatKind(PP, Var) &&
4609 llvm::equal(
4610 CTAI.CanonicalConverted,
4611 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4612 IsSameTemplateArg)) {
4613 Diag(TemplateNameLoc,
4614 diag::err_auto_variable_cannot_appear_in_own_initializer)
4615 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4616 return true;
4617 }
4618
4620 Template->getPartialSpecializations(PartialSpecs);
4621 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4622 if (ParsingInitForAutoVars.count(Partial) &&
4623 llvm::equal(CTAI.CanonicalConverted,
4624 Partial->getTemplateArgs().asArray(),
4625 IsSameTemplateArg)) {
4626 Diag(TemplateNameLoc,
4627 diag::err_auto_variable_cannot_appear_in_own_initializer)
4628 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4629 << Partial->getType();
4630 return true;
4631 }
4632
4633 return DeclResult();
4634 }
4635
4636 // Find the variable template specialization declaration that
4637 // corresponds to these arguments.
4638 void *InsertPos = nullptr;
4640 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4641 checkSpecializationReachability(TemplateNameLoc, Spec);
4642 if (Spec->getType()->isUndeducedType()) {
4643 if (ParsingInitForAutoVars.count(Spec))
4644 Diag(TemplateNameLoc,
4645 diag::err_auto_variable_cannot_appear_in_own_initializer)
4646 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4647 << Spec->getType();
4648 else
4649 // We are substituting the initializer of this variable template
4650 // specialization.
4651 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4652 << Spec << Spec->getType();
4653
4654 return true;
4655 }
4656 // If we already have a variable template specialization, return it.
4657 return Spec;
4658 }
4659
4660 // This is the first time we have referenced this variable template
4661 // specialization. Create the canonical declaration and add it to
4662 // the set of specializations, based on the closest partial specialization
4663 // that it represents. That is,
4664 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4665 const TemplateArgumentList *PartialSpecArgs = nullptr;
4666 bool AmbiguousPartialSpec = false;
4667 typedef PartialSpecMatchResult MatchResult;
4669 SourceLocation PointOfInstantiation = TemplateNameLoc;
4670 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4671 /*ForTakingAddress=*/false);
4672
4673 // 1. Attempt to find the closest partial specialization that this
4674 // specializes, if any.
4675 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4676 // Perhaps better after unification of DeduceTemplateArguments() and
4677 // getMoreSpecializedPartialSpecialization().
4679 Template->getPartialSpecializations(PartialSpecs);
4680
4681 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4682 // C++ [temp.spec.partial.member]p2:
4683 // If the primary member template is explicitly specialized for a given
4684 // (implicit) specialization of the enclosing class template, the partial
4685 // specializations of the member template are ignored for this
4686 // specialization of the enclosing class template. If a partial
4687 // specialization of the member template is explicitly specialized for a
4688 // given (implicit) specialization of the enclosing class template, the
4689 // primary member template and its other partial specializations are still
4690 // considered for this specialization of the enclosing class template.
4691 if (Template->isMemberSpecialization() &&
4692 !Partial->isMemberSpecialization())
4693 continue;
4694
4695 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4696
4698 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4700 // Store the failed-deduction information for use in diagnostics, later.
4701 // TODO: Actually use the failed-deduction info?
4702 FailedCandidates.addCandidate().set(
4705 (void)Result;
4706 } else {
4707 Matched.push_back(PartialSpecMatchResult());
4708 Matched.back().Partial = Partial;
4709 Matched.back().Args = Info.takeSugared();
4710 }
4711 }
4712
4713 if (Matched.size() >= 1) {
4714 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4715 if (Matched.size() == 1) {
4716 // -- If exactly one matching specialization is found, the
4717 // instantiation is generated from that specialization.
4718 // We don't need to do anything for this.
4719 } else {
4720 // -- If more than one matching specialization is found, the
4721 // partial order rules (14.5.4.2) are used to determine
4722 // whether one of the specializations is more specialized
4723 // than the others. If none of the specializations is more
4724 // specialized than all of the other matching
4725 // specializations, then the use of the variable template is
4726 // ambiguous and the program is ill-formed.
4727 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4728 PEnd = Matched.end();
4729 P != PEnd; ++P) {
4730 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4731 PointOfInstantiation) ==
4732 P->Partial)
4733 Best = P;
4734 }
4735
4736 // Determine if the best partial specialization is more specialized than
4737 // the others.
4738 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4739 PEnd = Matched.end();
4740 P != PEnd; ++P) {
4742 P->Partial, Best->Partial,
4743 PointOfInstantiation) != Best->Partial) {
4744 AmbiguousPartialSpec = true;
4745 break;
4746 }
4747 }
4748 }
4749
4750 // Instantiate using the best variable template partial specialization.
4751 InstantiationPattern = Best->Partial;
4752 PartialSpecArgs = Best->Args;
4753 } else {
4754 // -- If no match is found, the instantiation is generated
4755 // from the primary template.
4756 // InstantiationPattern = Template->getTemplatedDecl();
4757 }
4758
4759 // 2. Create the canonical declaration.
4760 // Note that we do not instantiate a definition until we see an odr-use
4761 // in DoMarkVarDeclReferenced().
4762 // FIXME: LateAttrs et al.?
4763 if (AmbiguousPartialSpec) {
4764 // Partial ordering did not produce a clear winner. Complain.
4765 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4766 << Template;
4767 // Print the matching partial specializations.
4768 for (MatchResult P : Matched)
4769 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4770 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4771 *P.Args);
4772 return true;
4773 }
4774
4776 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4777 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4778 if (!Decl)
4779 return true;
4780 if (SetWrittenArgs)
4781 Decl->setTemplateArgsAsWritten(TemplateArgs);
4782
4784 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4785 Decl->setInstantiationOf(D, PartialSpecArgs);
4786
4787 checkSpecializationReachability(TemplateNameLoc, Decl);
4788
4789 assert(Decl && "No variable template specialization?");
4790 return Decl;
4791}
4792
4794 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4795 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4796 const TemplateArgumentListInfo *TemplateArgs) {
4797
4798 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4799 *TemplateArgs, /*SetWrittenArgs=*/false);
4800 if (Decl.isInvalid())
4801 return ExprError();
4802
4803 if (!Decl.get())
4804 return ExprResult();
4805
4806 VarDecl *Var = cast<VarDecl>(Decl.get());
4809 NameInfo.getLoc());
4810
4811 // Build an ordinary singleton decl ref.
4812 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4813}
4814
4816 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4818 const TemplateArgumentListInfo *TemplateArgs) {
4819 assert(Template && "A variable template id without template?");
4820
4821 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4822 Template->templateParameterKind() !=
4824 return ExprResult();
4825
4826 // Check that the template argument list is well-formed for this template.
4829 Template, TemplateLoc,
4830 // FIXME: TemplateArgs will not be modified because
4831 // UpdateArgsWithConversions is false, however, we should
4832 // CheckTemplateArgumentList to be const-correct.
4833 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4834 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4835 /*UpdateArgsWithConversions=*/false))
4836 return true;
4837
4839 R.addDecl(Template);
4840
4841 // FIXME: We model references to variable template and concept parameters
4842 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4843 // data, can generally be used in the same places and work the same way.
4844 // However, it might be cleaner to use a dedicated AST node in the long run.
4847 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4848 /*KnownDependent=*/false,
4849 /*KnownInstantiationDependent=*/false);
4850}
4851
4853 SourceLocation Loc) {
4854 Diag(Loc, diag::err_template_missing_args)
4855 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4856 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4857 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4858 }
4859}
4860
4862 bool TemplateKeyword,
4863 TemplateDecl *TD,
4864 SourceLocation Loc) {
4865 TemplateName Name = Context.getQualifiedTemplateName(
4866 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4868}
4869
4871 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4872 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4873 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4874 bool DoCheckConstraintSatisfaction) {
4875 assert(NamedConcept && "A concept template id without a template?");
4876
4877 if (NamedConcept->isInvalidDecl())
4878 return ExprError();
4879
4882 NamedConcept, ConceptNameInfo.getLoc(),
4883 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4884 /*DefaultArgs=*/{},
4885 /*PartialTemplateArgs=*/false, CTAI,
4886 /*UpdateArgsWithConversions=*/false))
4887 return ExprError();
4888
4889 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4890
4891 // There's a bug with CTAI.CanonicalConverted.
4892 // If the template argument contains a DependentDecltypeType that includes a
4893 // TypeAliasType, and the same written type had occurred previously in the
4894 // source, then the DependentDecltypeType would be canonicalized to that
4895 // previous type which would mess up the substitution.
4896 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4898 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4899 CTAI.SugaredConverted);
4900 ConstraintSatisfaction Satisfaction;
4901 bool AreArgsDependent =
4902 TemplateSpecializationType::anyDependentTemplateArguments(
4903 *TemplateArgs, CTAI.SugaredConverted);
4904 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4905 /*Final=*/false);
4907 Context,
4909 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4911
4912 bool Error = false;
4913 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4914 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4915 DoCheckConstraintSatisfaction) {
4916
4918
4921
4923 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4924 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4925 TemplateArgs->getRAngleLoc()),
4926 Satisfaction, CL);
4927 Satisfaction.ContainsErrors = Error;
4928 }
4929
4930 if (Error)
4931 return ExprError();
4932
4934 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4935}
4936
4938 SourceLocation TemplateKWLoc,
4939 LookupResult &R,
4940 bool RequiresADL,
4941 const TemplateArgumentListInfo *TemplateArgs) {
4942 // FIXME: Can we do any checking at this point? I guess we could check the
4943 // template arguments that we have against the template name, if the template
4944 // name refers to a single template. That's not a terribly common case,
4945 // though.
4946 // foo<int> could identify a single function unambiguously
4947 // This approach does NOT work, since f<int>(1);
4948 // gets resolved prior to resorting to overload resolution
4949 // i.e., template<class T> void f(double);
4950 // vs template<class T, class U> void f(U);
4951
4952 // These should be filtered out by our callers.
4953 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4954
4955 // Non-function templates require a template argument list.
4956 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4957 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4959 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4960 return ExprError();
4961 }
4962 }
4963 bool KnownDependent = false;
4964 // In C++1y, check variable template ids.
4965 if (R.getAsSingle<VarTemplateDecl>()) {
4967 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4968 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4969 if (Res.isInvalid() || Res.isUsable())
4970 return Res;
4971 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4972 KnownDependent = true;
4973 }
4974
4975 // We don't want lookup warnings at this point.
4976 R.suppressDiagnostics();
4977
4978 if (R.getAsSingle<ConceptDecl>()) {
4979 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4980 R.getRepresentativeDecl(),
4981 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4982 }
4983
4984 // Check variable template ids (C++17) and concept template parameters
4985 // (C++26).
4987 if (R.getAsSingle<TemplateTemplateParmDecl>())
4989 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
4990 TemplateKWLoc, TemplateArgs);
4991
4992 // Function templates
4994 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4995 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4996 R.begin(), R.end(), KnownDependent,
4997 /*KnownInstantiationDependent=*/false);
4998 // Model the templates with UnresolvedTemplateTy. The expression should then
4999 // either be transformed in an instantiation or be diagnosed in
5000 // CheckPlaceholderExpr.
5001 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5002 !R.getFoundDecl()->getAsFunction())
5003 ULE->setType(Context.UnresolvedTemplateTy);
5004
5005 return ULE;
5006}
5007
5009 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5010 const DeclarationNameInfo &NameInfo,
5011 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5012 assert(TemplateArgs || TemplateKWLoc.isValid());
5013
5014 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5015 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5016 /*EnteringContext=*/false, TemplateKWLoc))
5017 return ExprError();
5018
5019 if (R.isAmbiguous())
5020 return ExprError();
5021
5022 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5023 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5024
5025 if (R.empty()) {
5027 Diag(NameInfo.getLoc(), diag::err_no_member)
5028 << NameInfo.getName() << DC << SS.getRange();
5029 return ExprError();
5030 }
5031
5032 // If necessary, build an implicit class member access.
5033 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5034 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5035 /*S=*/nullptr);
5036
5037 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5038}
5039
5041 CXXScopeSpec &SS,
5042 SourceLocation TemplateKWLoc,
5043 const UnqualifiedId &Name,
5044 ParsedType ObjectType,
5045 bool EnteringContext,
5047 bool AllowInjectedClassName) {
5048 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5049 Diag(TemplateKWLoc,
5051 diag::warn_cxx98_compat_template_outside_of_template :
5052 diag::ext_template_outside_of_template)
5053 << FixItHint::CreateRemoval(TemplateKWLoc);
5054
5055 if (SS.isInvalid())
5056 return TNK_Non_template;
5057
5058 // Figure out where isTemplateName is going to look.
5059 DeclContext *LookupCtx = nullptr;
5060 if (SS.isNotEmpty())
5061 LookupCtx = computeDeclContext(SS, EnteringContext);
5062 else if (ObjectType)
5063 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5064
5065 // C++0x [temp.names]p5:
5066 // If a name prefixed by the keyword template is not the name of
5067 // a template, the program is ill-formed. [Note: the keyword
5068 // template may not be applied to non-template members of class
5069 // templates. -end note ] [ Note: as is the case with the
5070 // typename prefix, the template prefix is allowed in cases
5071 // where it is not strictly necessary; i.e., when the
5072 // nested-name-specifier or the expression on the left of the ->
5073 // or . is not dependent on a template-parameter, or the use
5074 // does not appear in the scope of a template. -end note]
5075 //
5076 // Note: C++03 was more strict here, because it banned the use of
5077 // the "template" keyword prior to a template-name that was not a
5078 // dependent name. C++ DR468 relaxed this requirement (the
5079 // "template" keyword is now permitted). We follow the C++0x
5080 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5081 bool MemberOfUnknownSpecialization;
5082 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5083 ObjectType, EnteringContext, Result,
5084 MemberOfUnknownSpecialization);
5085 if (TNK != TNK_Non_template) {
5086 // We resolved this to a (non-dependent) template name. Return it.
5087 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5088 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5090 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5091 // C++14 [class.qual]p2:
5092 // In a lookup in which function names are not ignored and the
5093 // nested-name-specifier nominates a class C, if the name specified
5094 // [...] is the injected-class-name of C, [...] the name is instead
5095 // considered to name the constructor
5096 //
5097 // We don't get here if naming the constructor would be valid, so we
5098 // just reject immediately and recover by treating the
5099 // injected-class-name as naming the template.
5100 Diag(Name.getBeginLoc(),
5101 diag::ext_out_of_line_qualified_id_type_names_constructor)
5102 << Name.Identifier
5103 << 0 /*injected-class-name used as template name*/
5104 << TemplateKWLoc.isValid();
5105 }
5106 return TNK;
5107 }
5108
5109 if (!MemberOfUnknownSpecialization) {
5110 // Didn't find a template name, and the lookup wasn't dependent.
5111 // Do the lookup again to determine if this is a "nothing found" case or
5112 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5113 // need to do this.
5115 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5117 // Tell LookupTemplateName that we require a template so that it diagnoses
5118 // cases where it finds a non-template.
5119 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5120 ? RequiredTemplateKind(TemplateKWLoc)
5122 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5123 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5124 !R.isAmbiguous()) {
5125 if (LookupCtx)
5126 Diag(Name.getBeginLoc(), diag::err_no_member)
5127 << DNI.getName() << LookupCtx << SS.getRange();
5128 else
5129 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5130 << DNI.getName() << SS.getRange();
5131 }
5132 return TNK_Non_template;
5133 }
5134
5135 NestedNameSpecifier Qualifier = SS.getScopeRep();
5136
5137 switch (Name.getKind()) {
5139 Result = TemplateTy::make(Context.getDependentTemplateName(
5140 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5142
5144 Result = TemplateTy::make(Context.getDependentTemplateName(
5145 {Qualifier, Name.OperatorFunctionId.Operator,
5146 TemplateKWLoc.isValid()}));
5147 return TNK_Function_template;
5148
5150 // This is a kind of template name, but can never occur in a dependent
5151 // scope (literal operators can only be declared at namespace scope).
5152 break;
5153
5154 default:
5155 break;
5156 }
5157
5158 // This name cannot possibly name a dependent template. Diagnose this now
5159 // rather than building a dependent template name that can never be valid.
5160 Diag(Name.getBeginLoc(),
5161 diag::err_template_kw_refers_to_dependent_non_template)
5163 << TemplateKWLoc.isValid() << TemplateKWLoc;
5164 return TNK_Non_template;
5165}
5166
5169 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5170 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5171 const TemplateArgument &Arg = AL.getArgument();
5173 TypeSourceInfo *TSI = nullptr;
5174
5175 // Check template type parameter.
5176 switch(Arg.getKind()) {
5178 // C++ [temp.arg.type]p1:
5179 // A template-argument for a template-parameter which is a
5180 // type shall be a type-id.
5181 ArgType = Arg.getAsType();
5182 TSI = AL.getTypeSourceInfo();
5183 break;
5186 // We have a template type parameter but the template argument
5187 // is a template without any arguments.
5188 SourceRange SR = AL.getSourceRange();
5191 return true;
5192 }
5194 // We have a template type parameter but the template argument is an
5195 // expression; see if maybe it is missing the "typename" keyword.
5196 CXXScopeSpec SS;
5197 DeclarationNameInfo NameInfo;
5198
5199 if (DependentScopeDeclRefExpr *ArgExpr =
5200 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5201 SS.Adopt(ArgExpr->getQualifierLoc());
5202 NameInfo = ArgExpr->getNameInfo();
5203 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5204 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5205 if (ArgExpr->isImplicitAccess()) {
5206 SS.Adopt(ArgExpr->getQualifierLoc());
5207 NameInfo = ArgExpr->getMemberNameInfo();
5208 }
5209 }
5210
5211 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5212 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5213 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5214
5215 if (Result.getAsSingle<TypeDecl>() ||
5216 Result.wasNotFoundInCurrentInstantiation()) {
5217 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5218 // Suggest that the user add 'typename' before the NNS.
5220 Diag(Loc, getLangOpts().MSVCCompat
5221 ? diag::ext_ms_template_type_arg_missing_typename
5222 : diag::err_template_arg_must_be_type_suggest)
5223 << FixItHint::CreateInsertion(Loc, "typename ");
5225
5226 // Recover by synthesizing a type using the location information that we
5227 // already have.
5228 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5229 SS.getScopeRep(), II);
5230 TypeLocBuilder TLB;
5232 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5234 TL.setNameLoc(NameInfo.getLoc());
5235 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5236
5237 // Overwrite our input TemplateArgumentLoc so that we can recover
5238 // properly.
5241
5242 break;
5243 }
5244 }
5245 // fallthrough
5246 [[fallthrough]];
5247 }
5248 default: {
5249 // We allow instantiating a template with template argument packs when
5250 // building deduction guides or mapping constraint template parameters.
5251 if (Arg.getKind() == TemplateArgument::Pack &&
5252 (CodeSynthesisContexts.back().Kind ==
5255 SugaredConverted.push_back(Arg);
5256 CanonicalConverted.push_back(Arg);
5257 return false;
5258 }
5259 // We have a template type parameter but the template argument
5260 // is not a type.
5261 SourceRange SR = AL.getSourceRange();
5262 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5264
5265 return true;
5266 }
5267 }
5268
5269 if (CheckTemplateArgument(TSI))
5270 return true;
5271
5272 // Objective-C ARC:
5273 // If an explicitly-specified template argument type is a lifetime type
5274 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5275 if (getLangOpts().ObjCAutoRefCount &&
5276 ArgType->isObjCLifetimeType() &&
5277 !ArgType.getObjCLifetime()) {
5278 Qualifiers Qs;
5280 ArgType = Context.getQualifiedType(ArgType, Qs);
5281 }
5282
5283 SugaredConverted.push_back(TemplateArgument(ArgType));
5284 CanonicalConverted.push_back(
5285 TemplateArgument(Context.getCanonicalType(ArgType)));
5286 return false;
5287}
5288
5289/// Substitute template arguments into the default template argument for
5290/// the given template type parameter.
5291///
5292/// \param SemaRef the semantic analysis object for which we are performing
5293/// the substitution.
5294///
5295/// \param Template the template that we are synthesizing template arguments
5296/// for.
5297///
5298/// \param TemplateLoc the location of the template name that started the
5299/// template-id we are checking.
5300///
5301/// \param RAngleLoc the location of the right angle bracket ('>') that
5302/// terminates the template-id.
5303///
5304/// \param Param the template template parameter whose default we are
5305/// substituting into.
5306///
5307/// \param Converted the list of template arguments provided for template
5308/// parameters that precede \p Param in the template parameter list.
5309///
5310/// \param Output the resulting substituted template argument.
5311///
5312/// \returns true if an error occurred.
5314 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5315 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5316 ArrayRef<TemplateArgument> SugaredConverted,
5317 ArrayRef<TemplateArgument> CanonicalConverted,
5318 TemplateArgumentLoc &Output) {
5319 Output = Param->getDefaultArgument();
5320
5321 // If the argument type is dependent, instantiate it now based
5322 // on the previously-computed template arguments.
5323 if (Output.getArgument().isInstantiationDependent()) {
5324 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5325 SugaredConverted,
5326 SourceRange(TemplateLoc, RAngleLoc));
5327 if (Inst.isInvalid())
5328 return true;
5329
5330 // Only substitute for the innermost template argument list.
5331 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5332 /*Final=*/true);
5333 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5334 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5335
5336 bool ForLambdaCallOperator = false;
5337 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5338 ForLambdaCallOperator = Rec->isLambda();
5339 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5340 !ForLambdaCallOperator);
5341
5342 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5343 Param->getDefaultArgumentLoc(),
5344 Param->getDeclName()))
5345 return true;
5346 }
5347
5348 return false;
5349}
5350
5351/// Substitute template arguments into the default template argument for
5352/// the given non-type template parameter.
5353///
5354/// \param SemaRef the semantic analysis object for which we are performing
5355/// the substitution.
5356///
5357/// \param Template the template that we are synthesizing template arguments
5358/// for.
5359///
5360/// \param TemplateLoc the location of the template name that started the
5361/// template-id we are checking.
5362///
5363/// \param RAngleLoc the location of the right angle bracket ('>') that
5364/// terminates the template-id.
5365///
5366/// \param Param the non-type template parameter whose default we are
5367/// substituting into.
5368///
5369/// \param Converted the list of template arguments provided for template
5370/// parameters that precede \p Param in the template parameter list.
5371///
5372/// \returns the substituted template argument, or NULL if an error occurred.
5374 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5375 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5376 ArrayRef<TemplateArgument> SugaredConverted,
5377 ArrayRef<TemplateArgument> CanonicalConverted,
5378 TemplateArgumentLoc &Output) {
5379 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5380 SugaredConverted,
5381 SourceRange(TemplateLoc, RAngleLoc));
5382 if (Inst.isInvalid())
5383 return true;
5384
5385 // Only substitute for the innermost template argument list.
5386 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5387 /*Final=*/true);
5388 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5389 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5390
5391 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5392 EnterExpressionEvaluationContext ConstantEvaluated(
5394 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5395 TemplateArgLists, Output);
5396}
5397
5398/// Substitute template arguments into the default template argument for
5399/// the given template template parameter.
5400///
5401/// \param SemaRef the semantic analysis object for which we are performing
5402/// the substitution.
5403///
5404/// \param Template the template that we are synthesizing template arguments
5405/// for.
5406///
5407/// \param TemplateLoc the location of the template name that started the
5408/// template-id we are checking.
5409///
5410/// \param RAngleLoc the location of the right angle bracket ('>') that
5411/// terminates the template-id.
5412///
5413/// \param Param the template template parameter whose default we are
5414/// substituting into.
5415///
5416/// \param Converted the list of template arguments provided for template
5417/// parameters that precede \p Param in the template parameter list.
5418///
5419/// \param QualifierLoc Will be set to the nested-name-specifier (with
5420/// source-location information) that precedes the template name.
5421///
5422/// \returns the substituted template argument, or NULL if an error occurred.
5424 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5425 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5427 ArrayRef<TemplateArgument> SugaredConverted,
5428 ArrayRef<TemplateArgument> CanonicalConverted,
5429 NestedNameSpecifierLoc &QualifierLoc) {
5431 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5432 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5433 if (Inst.isInvalid())
5434 return TemplateName();
5435
5436 // Only substitute for the innermost template argument list.
5437 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5438 /*Final=*/true);
5439 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5440 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5441
5442 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5443
5444 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5445 QualifierLoc = A.getTemplateQualifierLoc();
5446 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5448 A.getTemplateNameLoc(), TemplateArgLists);
5449}
5450
5452 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5453 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5454 ArrayRef<TemplateArgument> SugaredConverted,
5455 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5456 HasDefaultArg = false;
5457
5458 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5459 if (!hasReachableDefaultArgument(TypeParm))
5460 return TemplateArgumentLoc();
5461
5462 HasDefaultArg = true;
5463 TemplateArgumentLoc Output;
5464 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5465 RAngleLoc, TypeParm, SugaredConverted,
5466 CanonicalConverted, Output))
5467 return TemplateArgumentLoc();
5468 return Output;
5469 }
5470
5471 if (NonTypeTemplateParmDecl *NonTypeParm
5472 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5473 if (!hasReachableDefaultArgument(NonTypeParm))
5474 return TemplateArgumentLoc();
5475
5476 HasDefaultArg = true;
5477 TemplateArgumentLoc Output;
5478 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5479 RAngleLoc, NonTypeParm, SugaredConverted,
5480 CanonicalConverted, Output))
5481 return TemplateArgumentLoc();
5482 return Output;
5483 }
5484
5485 TemplateTemplateParmDecl *TempTempParm
5487 if (!hasReachableDefaultArgument(TempTempParm))
5488 return TemplateArgumentLoc();
5489
5490 HasDefaultArg = true;
5491 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5492 NestedNameSpecifierLoc QualifierLoc;
5494 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5495 SugaredConverted, CanonicalConverted, QualifierLoc);
5496 if (TName.isNull())
5497 return TemplateArgumentLoc();
5498
5499 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5500 QualifierLoc, A.getTemplateNameLoc());
5501}
5502
5503/// Convert a template-argument that we parsed as a type into a template, if
5504/// possible. C++ permits injected-class-names to perform dual service as
5505/// template template arguments and as template type arguments.
5508 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5509 if (!TagLoc)
5510 return TemplateArgumentLoc();
5511
5512 // If this type was written as an injected-class-name, it can be used as a
5513 // template template argument.
5514 // If this type was written as an injected-class-name, it may have been
5515 // converted to a RecordType during instantiation. If the RecordType is
5516 // *not* wrapped in a TemplateSpecializationType and denotes a class
5517 // template specialization, it must have come from an injected-class-name.
5518
5519 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5520 if (Name.isNull())
5521 return TemplateArgumentLoc();
5522
5523 return TemplateArgumentLoc(Context, Name,
5524 /*TemplateKWLoc=*/SourceLocation(),
5525 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5526}
5527
5530 SourceLocation TemplateLoc,
5531 SourceLocation RAngleLoc,
5532 unsigned ArgumentPackIndex,
5535 // Check template type parameters.
5536 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5537 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5538 CTAI.CanonicalConverted);
5539
5540 const TemplateArgument &Arg = ArgLoc.getArgument();
5541 // Check non-type template parameters.
5542 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5543 // Do substitution on the type of the non-type template parameter
5544 // with the template arguments we've seen thus far. But if the
5545 // template has a dependent context then we cannot substitute yet.
5546 QualType NTTPType = NTTP->getType();
5547 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5548 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5549
5550 if (NTTPType->isInstantiationDependentType()) {
5551 // Do substitution on the type of the non-type template parameter.
5552 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5553 CTAI.SugaredConverted,
5554 SourceRange(TemplateLoc, RAngleLoc));
5555 if (Inst.isInvalid())
5556 return true;
5557
5559 /*Final=*/true);
5560 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5561 // If the parameter is a pack expansion, expand this slice of the pack.
5562 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5563 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5564 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5565 NTTP->getDeclName());
5566 } else {
5567 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5568 NTTP->getDeclName());
5569 }
5570
5571 // If that worked, check the non-type template parameter type
5572 // for validity.
5573 if (!NTTPType.isNull())
5574 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5575 NTTP->getLocation());
5576 if (NTTPType.isNull())
5577 return true;
5578 }
5579
5580 auto checkExpr = [&](Expr *E) -> Expr * {
5581 TemplateArgument SugaredResult, CanonicalResult;
5583 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5584 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5585 // If the current template argument causes an error, give up now.
5586 if (Res.isInvalid())
5587 return nullptr;
5588 CTAI.SugaredConverted.push_back(SugaredResult);
5589 CTAI.CanonicalConverted.push_back(CanonicalResult);
5590 return Res.get();
5591 };
5592
5593 switch (Arg.getKind()) {
5595 llvm_unreachable("Should never see a NULL template argument here");
5596
5598 Expr *E = Arg.getAsExpr();
5599 Expr *R = checkExpr(E);
5600 if (!R)
5601 return true;
5602 // If the resulting expression is new, then use it in place of the
5603 // old expression in the template argument.
5604 if (R != E) {
5605 TemplateArgument TA(R, /*IsCanonical=*/false);
5606 ArgLoc = TemplateArgumentLoc(TA, R);
5607 }
5608 break;
5609 }
5610
5611 // As for the converted NTTP kinds, they still might need another
5612 // conversion, as the new corresponding parameter might be different.
5613 // Ideally, we would always perform substitution starting with sugared types
5614 // and never need these, as we would still have expressions. Since these are
5615 // needed so rarely, it's probably a better tradeoff to just convert them
5616 // back to expressions.
5621 // FIXME: StructuralValue is untested here.
5622 ExprResult R =
5624 assert(R.isUsable());
5625 if (!checkExpr(R.get()))
5626 return true;
5627 break;
5628 }
5629
5632 // We were given a template template argument. It may not be ill-formed;
5633 // see below.
5636 // We have a template argument such as \c T::template X, which we
5637 // parsed as a template template argument. However, since we now
5638 // know that we need a non-type template argument, convert this
5639 // template name into an expression.
5640
5641 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5642 ArgLoc.getTemplateNameLoc());
5643
5644 CXXScopeSpec SS;
5645 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5646 // FIXME: the template-template arg was a DependentTemplateName,
5647 // so it was provided with a template keyword. However, its source
5648 // location is not stored in the template argument structure.
5649 SourceLocation TemplateKWLoc;
5651 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5652 nullptr);
5653
5654 // If we parsed the template argument as a pack expansion, create a
5655 // pack expansion expression.
5658 if (E.isInvalid())
5659 return true;
5660 }
5661
5662 TemplateArgument SugaredResult, CanonicalResult;
5664 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5665 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5666 if (E.isInvalid())
5667 return true;
5668
5669 CTAI.SugaredConverted.push_back(SugaredResult);
5670 CTAI.CanonicalConverted.push_back(CanonicalResult);
5671 break;
5672 }
5673
5674 // We have a template argument that actually does refer to a class
5675 // template, alias template, or template template parameter, and
5676 // therefore cannot be a non-type template argument.
5677 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5678 << ArgLoc.getSourceRange();
5680
5681 return true;
5682
5684 // We have a non-type template parameter but the template
5685 // argument is a type.
5686
5687 // C++ [temp.arg]p2:
5688 // In a template-argument, an ambiguity between a type-id and
5689 // an expression is resolved to a type-id, regardless of the
5690 // form of the corresponding template-parameter.
5691 //
5692 // We warn specifically about this case, since it can be rather
5693 // confusing for users.
5694 QualType T = Arg.getAsType();
5695 SourceRange SR = ArgLoc.getSourceRange();
5696 if (T->isFunctionType())
5697 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5698 else
5699 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5701 return true;
5702 }
5703
5705 llvm_unreachable("Caller must expand template argument packs");
5706 }
5707
5708 return false;
5709 }
5710
5711
5712 // Check template template parameters.
5714
5715 TemplateParameterList *Params = TempParm->getTemplateParameters();
5716 if (TempParm->isExpandedParameterPack())
5717 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5718
5719 // Substitute into the template parameter list of the template
5720 // template parameter, since previously-supplied template arguments
5721 // may appear within the template template parameter.
5722 //
5723 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5724 {
5725 // Set up a template instantiation context.
5727 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5728 CTAI.SugaredConverted,
5729 SourceRange(TemplateLoc, RAngleLoc));
5730 if (Inst.isInvalid())
5731 return true;
5732
5733 Params = SubstTemplateParams(
5734 Params, CurContext,
5736 /*Final=*/true),
5737 /*EvaluateConstraints=*/false);
5738 if (!Params)
5739 return true;
5740 }
5741
5742 // C++1z [temp.local]p1: (DR1004)
5743 // When [the injected-class-name] is used [...] as a template-argument for
5744 // a template template-parameter [...] it refers to the class template
5745 // itself.
5746 if (Arg.getKind() == TemplateArgument::Type) {
5748 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5749 if (!ConvertedArg.getArgument().isNull())
5750 ArgLoc = ConvertedArg;
5751 }
5752
5753 switch (Arg.getKind()) {
5755 llvm_unreachable("Should never see a NULL template argument here");
5756
5759 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5760 CTAI.PartialOrdering,
5761 &CTAI.StrictPackMatch))
5762 return true;
5763
5764 CTAI.SugaredConverted.push_back(Arg);
5765 CTAI.CanonicalConverted.push_back(
5766 Context.getCanonicalTemplateArgument(Arg));
5767 break;
5768
5771 auto Kind = 0;
5772 switch (TempParm->templateParameterKind()) {
5774 Kind = 1;
5775 break;
5777 Kind = 2;
5778 break;
5779 default:
5780 break;
5781 }
5782
5783 // We have a template template parameter but the template
5784 // argument does not refer to a template.
5785 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5786 << Kind << getLangOpts().CPlusPlus11;
5787 return true;
5788 }
5789
5794 llvm_unreachable("non-type argument with template template parameter");
5795
5797 llvm_unreachable("Caller must expand template argument packs");
5798 }
5799
5800 return false;
5801}
5802
5803/// Diagnose a missing template argument.
5804template<typename TemplateParmDecl>
5806 TemplateDecl *TD,
5807 const TemplateParmDecl *D,
5809 // Dig out the most recent declaration of the template parameter; there may be
5810 // declarations of the template that are more recent than TD.
5812 ->getTemplateParameters()
5813 ->getParam(D->getIndex()));
5814
5815 // If there's a default argument that's not reachable, diagnose that we're
5816 // missing a module import.
5818 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5820 D->getDefaultArgumentLoc(), Modules,
5822 /*Recover*/true);
5823 return true;
5824 }
5825
5826 // FIXME: If there's a more recent default argument that *is* visible,
5827 // diagnose that it was declared too late.
5828
5830
5831 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5832 << /*not enough args*/0
5834 << TD;
5835 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5836 return true;
5837}
5838
5839/// Check that the given template argument list is well-formed
5840/// for specializing the given template.
5842 TemplateDecl *Template, SourceLocation TemplateLoc,
5843 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5844 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5845 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5847 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5848 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5850}
5851
5852/// Check that the given template argument list is well-formed
5853/// for specializing the given template.
5856 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5857 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5858 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5860
5862 *ConstraintsNotSatisfied = false;
5863
5864 // Make a copy of the template arguments for processing. Only make the
5865 // changes at the end when successful in matching the arguments to the
5866 // template.
5867 TemplateArgumentListInfo NewArgs = TemplateArgs;
5868
5869 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5870
5871 // C++23 [temp.arg.general]p1:
5872 // [...] The type and form of each template-argument specified in
5873 // a template-id shall match the type and form specified for the
5874 // corresponding parameter declared by the template in its
5875 // template-parameter-list.
5876 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5877 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5878 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5879 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5880 LocalInstantiationScope InstScope(*this, true);
5881 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5882 ParamEnd = Params->end(),
5883 Param = ParamBegin;
5884 Param != ParamEnd;
5885 /* increment in loop */) {
5886 if (size_t ParamIdx = Param - ParamBegin;
5887 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5888 // All written arguments should have been consumed by this point.
5889 assert(ArgIdx == NumArgs && "bad default argument deduction");
5890 if (ParamIdx == DefaultArgs.StartPos) {
5891 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5892 // Default arguments from a DeducedTemplateName are already converted.
5893 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5894 CTAI.SugaredConverted.push_back(DefArg);
5895 CTAI.CanonicalConverted.push_back(
5896 Context.getCanonicalTemplateArgument(DefArg));
5897 ++Param;
5898 }
5899 continue;
5900 }
5901 }
5902
5903 // If we have an expanded parameter pack, make sure we don't have too
5904 // many arguments.
5905 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5906 if (*Expansions == SugaredArgumentPack.size()) {
5907 // We're done with this parameter pack. Pack up its arguments and add
5908 // them to the list.
5909 CTAI.SugaredConverted.push_back(
5910 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5911 SugaredArgumentPack.clear();
5912
5913 CTAI.CanonicalConverted.push_back(
5914 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5915 CanonicalArgumentPack.clear();
5916
5917 // This argument is assigned to the next parameter.
5918 ++Param;
5919 continue;
5920 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5921 // Not enough arguments for this parameter pack.
5922 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5923 << /*not enough args*/0
5925 << Template;
5927 return true;
5928 }
5929 }
5930
5931 // Check for builtins producing template packs in this context, we do not
5932 // support them yet.
5933 if (const NonTypeTemplateParmDecl *NTTP =
5934 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5935 NTTP && NTTP->isPackExpansion()) {
5936 auto TL = NTTP->getTypeSourceInfo()
5937 ->getTypeLoc()
5940 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5941 for (const auto &UPP : Unexpanded) {
5942 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5943 if (!TST)
5944 continue;
5945 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5946 // Expanding a built-in pack in this context is not yet supported.
5947 Diag(TL.getEllipsisLoc(),
5948 diag::err_unsupported_builtin_template_pack_expansion)
5949 << TST->getTemplateName();
5950 return true;
5951 }
5952 }
5953
5954 if (ArgIdx < NumArgs) {
5955 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5956 bool NonPackParameter =
5957 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5958 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5959
5960 if (ArgIsExpansion && CTAI.MatchingTTP) {
5961 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5962 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5963 ++Param) {
5964 TemplateArgument &Arg = Args[Param - First];
5965 Arg = ArgLoc.getArgument();
5966 if (!(*Param)->isTemplateParameterPack() ||
5967 getExpandedPackSize(*Param))
5968 Arg = Arg.getPackExpansionPattern();
5969 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5970 SaveAndRestore _1(CTAI.PartialOrdering, false);
5971 SaveAndRestore _2(CTAI.MatchingTTP, true);
5972 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5973 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5975 return true;
5976 Arg = NewArgLoc.getArgument();
5977 CTAI.CanonicalConverted.back().setIsDefaulted(
5978 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5979 CTAI.CanonicalConverted,
5980 Params->getDepth()));
5981 }
5982 ArgLoc = TemplateArgumentLoc(
5985 } else {
5986 SaveAndRestore _1(CTAI.PartialOrdering, false);
5987 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5988 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5990 return true;
5991 CTAI.CanonicalConverted.back().setIsDefaulted(
5992 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5993 *Param, CTAI.CanonicalConverted,
5994 Params->getDepth()));
5995 if (ArgIsExpansion && NonPackParameter) {
5996 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5997 // alias template, builtin template, or concept, and it's not part of
5998 // a parameter pack. This can't be canonicalized, so reject it now.
6000 Template)) {
6001 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6003 : 0;
6004 Diag(ArgLoc.getLocation(),
6005 diag::err_template_expansion_into_fixed_list)
6006 << DiagSelect << ArgLoc.getSourceRange();
6008 return true;
6009 }
6010 }
6011 }
6012
6013 // We're now done with this argument.
6014 ++ArgIdx;
6015
6016 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6017 // Directly convert the remaining arguments, because we don't know what
6018 // parameters they'll match up with.
6019
6020 if (!SugaredArgumentPack.empty()) {
6021 // If we were part way through filling in an expanded parameter pack,
6022 // fall back to just producing individual arguments.
6023 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6024 SugaredArgumentPack.begin(),
6025 SugaredArgumentPack.end());
6026 SugaredArgumentPack.clear();
6027
6028 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6029 CanonicalArgumentPack.begin(),
6030 CanonicalArgumentPack.end());
6031 CanonicalArgumentPack.clear();
6032 }
6033
6034 while (ArgIdx < NumArgs) {
6035 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6036 CTAI.SugaredConverted.push_back(Arg);
6037 CTAI.CanonicalConverted.push_back(
6038 Context.getCanonicalTemplateArgument(Arg));
6039 ++ArgIdx;
6040 }
6041
6042 return false;
6043 }
6044
6045 if ((*Param)->isTemplateParameterPack()) {
6046 // The template parameter was a template parameter pack, so take the
6047 // deduced argument and place it on the argument pack. Note that we
6048 // stay on the same template parameter so that we can deduce more
6049 // arguments.
6050 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6051 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6052 } else {
6053 // Move to the next template parameter.
6054 ++Param;
6055 }
6056 continue;
6057 }
6058
6059 // If we're checking a partial template argument list, we're done.
6060 if (PartialTemplateArgs) {
6061 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6062 CTAI.SugaredConverted.push_back(
6063 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6064 CTAI.CanonicalConverted.push_back(
6065 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6066 }
6067 return false;
6068 }
6069
6070 // If we have a template parameter pack with no more corresponding
6071 // arguments, just break out now and we'll fill in the argument pack below.
6072 if ((*Param)->isTemplateParameterPack()) {
6073 assert(!getExpandedPackSize(*Param) &&
6074 "Should have dealt with this already");
6075
6076 // A non-expanded parameter pack before the end of the parameter list
6077 // only occurs for an ill-formed template parameter list, unless we've
6078 // got a partial argument list for a function template, so just bail out.
6079 if (Param + 1 != ParamEnd) {
6080 assert(
6081 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6082 "Concept templates must have parameter packs at the end.");
6083 return true;
6084 }
6085
6086 CTAI.SugaredConverted.push_back(
6087 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6088 SugaredArgumentPack.clear();
6089
6090 CTAI.CanonicalConverted.push_back(
6091 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6092 CanonicalArgumentPack.clear();
6093
6094 ++Param;
6095 continue;
6096 }
6097
6098 // Check whether we have a default argument.
6099 bool HasDefaultArg;
6100
6101 // Retrieve the default template argument from the template
6102 // parameter. For each kind of template parameter, we substitute the
6103 // template arguments provided thus far and any "outer" template arguments
6104 // (when the template parameter was part of a nested template) into
6105 // the default argument.
6107 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6108 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6109
6110 if (Arg.getArgument().isNull()) {
6111 if (!HasDefaultArg) {
6112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6113 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6114 NewArgs);
6115 if (NonTypeTemplateParmDecl *NTTP =
6116 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6117 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6118 NewArgs);
6119 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6121 NewArgs);
6122 }
6123 return true;
6124 }
6125
6126 // Introduce an instantiation record that describes where we are using
6127 // the default template argument. We're not actually instantiating a
6128 // template here, we just create this object to put a note into the
6129 // context stack.
6130 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6131 CTAI.SugaredConverted,
6132 SourceRange(TemplateLoc, RAngleLoc));
6133 if (Inst.isInvalid())
6134 return true;
6135
6136 SaveAndRestore _1(CTAI.PartialOrdering, false);
6137 SaveAndRestore _2(CTAI.MatchingTTP, false);
6138 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6139 // Check the default template argument.
6140 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6141 CTAI, CTAK_Specified))
6142 return true;
6143
6144 CTAI.SugaredConverted.back().setIsDefaulted(true);
6145 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6146
6147 // Core issue 150 (assumed resolution): if this is a template template
6148 // parameter, keep track of the default template arguments from the
6149 // template definition.
6150 if (isTemplateTemplateParameter)
6151 NewArgs.addArgument(Arg);
6152
6153 // Move to the next template parameter and argument.
6154 ++Param;
6155 ++ArgIdx;
6156 }
6157
6158 // If we're performing a partial argument substitution, allow any trailing
6159 // pack expansions; they might be empty. This can happen even if
6160 // PartialTemplateArgs is false (the list of arguments is complete but
6161 // still dependent).
6162 if (CTAI.MatchingTTP ||
6164 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6165 while (ArgIdx < NumArgs &&
6166 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6167 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6168 CTAI.SugaredConverted.push_back(Arg);
6169 CTAI.CanonicalConverted.push_back(
6170 Context.getCanonicalTemplateArgument(Arg));
6171 }
6172 }
6173
6174 // If we have any leftover arguments, then there were too many arguments.
6175 // Complain and fail.
6176 if (ArgIdx < NumArgs) {
6177 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6178 << /*too many args*/1
6180 << Template
6181 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6183 return true;
6184 }
6185
6186 // No problems found with the new argument list, propagate changes back
6187 // to caller.
6188 if (UpdateArgsWithConversions)
6189 TemplateArgs = std::move(NewArgs);
6190
6191 if (!PartialTemplateArgs) {
6192 // Setup the context/ThisScope for the case where we are needing to
6193 // re-instantiate constraints outside of normal instantiation.
6194 DeclContext *NewContext = Template->getDeclContext();
6195
6196 // If this template is in a template, make sure we extract the templated
6197 // decl.
6198 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6199 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6200 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6201
6202 Qualifiers ThisQuals;
6203 if (const auto *Method =
6204 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6205 ThisQuals = Method->getMethodQualifiers();
6206
6207 ContextRAII Context(*this, NewContext);
6208 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6209
6211 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6212 /*RelativeToPrimary=*/true,
6213 /*Pattern=*/nullptr,
6214 /*ForConceptInstantiation=*/true);
6215 if (!isa<ConceptDecl>(Template) &&
6217 Template, MLTAL,
6218 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6221 return true;
6222 }
6223 }
6224
6225 return false;
6226}
6227
6228namespace {
6229 class UnnamedLocalNoLinkageFinder
6230 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6231 {
6232 Sema &S;
6233 SourceRange SR;
6234
6236
6237 public:
6238 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6239
6240 bool Visit(QualType T) {
6241 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6242 }
6243
6244#define TYPE(Class, Parent) \
6245 bool Visit##Class##Type(const Class##Type *);
6246#define ABSTRACT_TYPE(Class, Parent) \
6247 bool Visit##Class##Type(const Class##Type *) { return false; }
6248#define NON_CANONICAL_TYPE(Class, Parent) \
6249 bool Visit##Class##Type(const Class##Type *) { return false; }
6250#include "clang/AST/TypeNodes.inc"
6251
6252 bool VisitTagDecl(const TagDecl *Tag);
6253 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6254 };
6255} // end anonymous namespace
6256
6257bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6258 return false;
6259}
6260
6261bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6262 return Visit(T->getElementType());
6263}
6264
6265bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6266 return Visit(T->getPointeeType());
6267}
6268
6269bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6270 const BlockPointerType* T) {
6271 return Visit(T->getPointeeType());
6272}
6273
6274bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6275 const LValueReferenceType* T) {
6276 return Visit(T->getPointeeType());
6277}
6278
6279bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6280 const RValueReferenceType* T) {
6281 return Visit(T->getPointeeType());
6282}
6283
6284bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6285 const MemberPointerType *T) {
6286 if (Visit(T->getPointeeType()))
6287 return true;
6288 if (auto *RD = T->getMostRecentCXXRecordDecl())
6289 return VisitTagDecl(RD);
6290 return VisitNestedNameSpecifier(T->getQualifier());
6291}
6292
6293bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6294 const ConstantArrayType* T) {
6295 return Visit(T->getElementType());
6296}
6297
6298bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6299 const IncompleteArrayType* T) {
6300 return Visit(T->getElementType());
6301}
6302
6303bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6304 const VariableArrayType* T) {
6305 return Visit(T->getElementType());
6306}
6307
6308bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6309 const DependentSizedArrayType* T) {
6310 return Visit(T->getElementType());
6311}
6312
6313bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6314 const DependentSizedExtVectorType* T) {
6315 return Visit(T->getElementType());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6319 const DependentSizedMatrixType *T) {
6320 return Visit(T->getElementType());
6321}
6322
6323bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6324 const DependentAddressSpaceType *T) {
6325 return Visit(T->getPointeeType());
6326}
6327
6328bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6329 return Visit(T->getElementType());
6330}
6331
6332bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6333 const DependentVectorType *T) {
6334 return Visit(T->getElementType());
6335}
6336
6337bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6338 return Visit(T->getElementType());
6339}
6340
6341bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6342 const ConstantMatrixType *T) {
6343 return Visit(T->getElementType());
6344}
6345
6346bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6347 const FunctionProtoType* T) {
6348 for (const auto &A : T->param_types()) {
6349 if (Visit(A))
6350 return true;
6351 }
6352
6353 return Visit(T->getReturnType());
6354}
6355
6356bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6357 const FunctionNoProtoType* T) {
6358 return Visit(T->getReturnType());
6359}
6360
6361bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6362 const UnresolvedUsingType*) {
6363 return false;
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6367 return false;
6368}
6369
6370bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6371 return Visit(T->getUnmodifiedType());
6372}
6373
6374bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6375 return false;
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6379 const PackIndexingType *) {
6380 return false;
6381}
6382
6383bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6384 const UnaryTransformType*) {
6385 return false;
6386}
6387
6388bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6389 return Visit(T->getDeducedType());
6390}
6391
6392bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6393 const DeducedTemplateSpecializationType *T) {
6394 return Visit(T->getDeducedType());
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6398 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6402 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6406 const TemplateTypeParmType*) {
6407 return false;
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6411 const SubstTemplateTypeParmPackType *) {
6412 return false;
6413}
6414
6415bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6416 const SubstBuiltinTemplatePackType *) {
6417 return false;
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6421 const TemplateSpecializationType*) {
6422 return false;
6423}
6424
6425bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6426 const InjectedClassNameType* T) {
6427 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6428}
6429
6430bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6431 const DependentNameType* T) {
6432 return VisitNestedNameSpecifier(T->getQualifier());
6433}
6434
6435bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6436 const PackExpansionType* T) {
6437 return Visit(T->getPattern());
6438}
6439
6440bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6441 return false;
6442}
6443
6444bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6445 const ObjCInterfaceType *) {
6446 return false;
6447}
6448
6449bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6450 const ObjCObjectPointerType *) {
6451 return false;
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6455 return Visit(T->getValueType());
6456}
6457
6458bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6459 const OverflowBehaviorType *T) {
6460 return Visit(T->getUnderlyingType());
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6464 return false;
6465}
6466
6467bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6468 return false;
6469}
6470
6471bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6472 const ArrayParameterType *T) {
6473 return VisitConstantArrayType(T);
6474}
6475
6476bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6477 const DependentBitIntType *T) {
6478 return false;
6479}
6480
6481bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6482 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6483 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6484 ? diag::warn_cxx98_compat_template_arg_local_type
6485 : diag::ext_template_arg_local_type)
6486 << S.Context.getCanonicalTagType(Tag) << SR;
6487 return true;
6488 }
6489
6490 if (!Tag->hasNameForLinkage()) {
6491 S.Diag(SR.getBegin(),
6492 S.getLangOpts().CPlusPlus11 ?
6493 diag::warn_cxx98_compat_template_arg_unnamed_type :
6494 diag::ext_template_arg_unnamed_type) << SR;
6495 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6496 return true;
6497 }
6498
6499 return false;
6500}
6501
6502bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6503 NestedNameSpecifier NNS) {
6504 switch (NNS.getKind()) {
6509 return false;
6511 return Visit(QualType(NNS.getAsType(), 0));
6512 }
6513 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6514}
6515
6516bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6517 const HLSLAttributedResourceType *T) {
6518 if (T->hasContainedType() && Visit(T->getContainedType()))
6519 return true;
6520 return Visit(T->getWrappedType());
6521}
6522
6523bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6524 const HLSLInlineSpirvType *T) {
6525 for (auto &Operand : T->getOperands())
6526 if (Operand.isConstant() && Operand.isLiteral())
6527 if (Visit(Operand.getResultType()))
6528 return true;
6529 return false;
6530}
6531
6533 assert(ArgInfo && "invalid TypeSourceInfo");
6534 QualType Arg = ArgInfo->getType();
6535 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6536 QualType CanonArg = Context.getCanonicalType(Arg);
6537
6538 if (CanonArg->isVariablyModifiedType()) {
6539 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6540 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6541 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6542 }
6543
6544 // C++03 [temp.arg.type]p2:
6545 // A local type, a type with no linkage, an unnamed type or a type
6546 // compounded from any of these types shall not be used as a
6547 // template-argument for a template type-parameter.
6548 //
6549 // C++11 allows these, and even in C++03 we allow them as an extension with
6550 // a warning.
6551 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6552 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6553 (void)Finder.Visit(CanonArg);
6554 }
6555
6556 return false;
6557}
6558
6564
6565/// Determine whether the given template argument is a null pointer
6566/// value of the appropriate type.
6569 QualType ParamType, Expr *Arg,
6570 Decl *Entity = nullptr) {
6571 if (Arg->isValueDependent() || Arg->isTypeDependent())
6572 return NPV_NotNullPointer;
6573
6574 // dllimport'd entities aren't constant but are available inside of template
6575 // arguments.
6576 if (Entity && Entity->hasAttr<DLLImportAttr>())
6577 return NPV_NotNullPointer;
6578
6579 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6580 llvm_unreachable(
6581 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6582
6583 if (!S.getLangOpts().CPlusPlus11)
6584 return NPV_NotNullPointer;
6585
6586 // Determine whether we have a constant expression.
6588 if (ArgRV.isInvalid())
6589 return NPV_Error;
6590 Arg = ArgRV.get();
6591
6592 Expr::EvalResult EvalResult;
6594 EvalResult.Diag = &Notes;
6595 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6596 EvalResult.HasSideEffects) {
6597 SourceLocation DiagLoc = Arg->getExprLoc();
6598
6599 // If our only note is the usual "invalid subexpression" note, just point
6600 // the caret at its location rather than producing an essentially
6601 // redundant note.
6602 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6603 diag::note_invalid_subexpr_in_const_expr) {
6604 DiagLoc = Notes[0].first;
6605 Notes.clear();
6606 }
6607
6608 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6609 << Arg->getType() << Arg->getSourceRange();
6610 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6611 S.Diag(Notes[I].first, Notes[I].second);
6612
6614 return NPV_Error;
6615 }
6616
6617 // C++11 [temp.arg.nontype]p1:
6618 // - an address constant expression of type std::nullptr_t
6619 if (Arg->getType()->isNullPtrType())
6620 return NPV_NullPointer;
6621
6622 // - a constant expression that evaluates to a null pointer value (4.10); or
6623 // - a constant expression that evaluates to a null member pointer value
6624 // (4.11); or
6625 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6626 (EvalResult.Val.isMemberPointer() &&
6627 !EvalResult.Val.getMemberPointerDecl())) {
6628 // If our expression has an appropriate type, we've succeeded.
6629 bool ObjCLifetimeConversion;
6630 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6631 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6632 ObjCLifetimeConversion))
6633 return NPV_NullPointer;
6634
6635 // The types didn't match, but we know we got a null pointer; complain,
6636 // then recover as if the types were correct.
6637 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6638 << Arg->getType() << ParamType << Arg->getSourceRange();
6640 return NPV_NullPointer;
6641 }
6642
6643 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6644 // We found a pointer that isn't null, but doesn't refer to an object.
6645 // We could just return NPV_NotNullPointer, but we can print a better
6646 // message with the information we have here.
6647 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6648 << EvalResult.Val.getAsString(S.Context, ParamType);
6650 return NPV_Error;
6651 }
6652
6653 // If we don't have a null pointer value, but we do have a NULL pointer
6654 // constant, suggest a cast to the appropriate type.
6656 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6657 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6658 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6660 ")");
6662 return NPV_NullPointer;
6663 }
6664
6665 // FIXME: If we ever want to support general, address-constant expressions
6666 // as non-type template arguments, we should return the ExprResult here to
6667 // be interpreted by the caller.
6668 return NPV_NotNullPointer;
6669}
6670
6671/// Checks whether the given template argument is compatible with its
6672/// template parameter.
6673static bool
6675 QualType ParamType, Expr *ArgIn,
6676 Expr *Arg, QualType ArgType) {
6677 bool ObjCLifetimeConversion;
6678 if (ParamType->isPointerType() &&
6679 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6680 S.IsQualificationConversion(ArgType, ParamType, false,
6681 ObjCLifetimeConversion)) {
6682 // For pointer-to-object types, qualification conversions are
6683 // permitted.
6684 } else {
6685 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6686 if (!ParamRef->getPointeeType()->isFunctionType()) {
6687 // C++ [temp.arg.nontype]p5b3:
6688 // For a non-type template-parameter of type reference to
6689 // object, no conversions apply. The type referred to by the
6690 // reference may be more cv-qualified than the (otherwise
6691 // identical) type of the template- argument. The
6692 // template-parameter is bound directly to the
6693 // template-argument, which shall be an lvalue.
6694
6695 // FIXME: Other qualifiers?
6696 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6697 unsigned ArgQuals = ArgType.getCVRQualifiers();
6698
6699 if ((ParamQuals | ArgQuals) != ParamQuals) {
6700 S.Diag(Arg->getBeginLoc(),
6701 diag::err_template_arg_ref_bind_ignores_quals)
6702 << ParamType << Arg->getType() << Arg->getSourceRange();
6704 return true;
6705 }
6706 }
6707 }
6708
6709 // At this point, the template argument refers to an object or
6710 // function with external linkage. We now need to check whether the
6711 // argument and parameter types are compatible.
6712 if (!S.Context.hasSameUnqualifiedType(ArgType,
6713 ParamType.getNonReferenceType())) {
6714 // We can't perform this conversion or binding.
6715 if (ParamType->isReferenceType())
6716 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6717 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6718 else
6719 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6720 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6722 return true;
6723 }
6724 }
6725
6726 return false;
6727}
6728
6729/// Checks whether the given template argument is the address
6730/// of an object or function according to C++ [temp.arg.nontype]p1.
6732 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6733 bool IsSpecified, TemplateArgument &SugaredConverted,
6734 TemplateArgument &CanonicalConverted) {
6735 Expr *Arg = ArgIn;
6736 QualType ArgType = Arg->getType();
6737
6738 bool AddressTaken = false;
6739 SourceLocation AddrOpLoc;
6740 if (S.getLangOpts().MicrosoftExt) {
6741 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6742 // dereference and address-of operators.
6743 Arg = Arg->IgnoreParenCasts();
6744
6745 bool ExtWarnMSTemplateArg = false;
6746 UnaryOperatorKind FirstOpKind;
6747 SourceLocation FirstOpLoc;
6748 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6749 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6750 if (UnOpKind == UO_Deref)
6751 ExtWarnMSTemplateArg = true;
6752 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6753 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6754 if (!AddrOpLoc.isValid()) {
6755 FirstOpKind = UnOpKind;
6756 FirstOpLoc = UnOp->getOperatorLoc();
6757 }
6758 } else
6759 break;
6760 }
6761 if (FirstOpLoc.isValid()) {
6762 if (ExtWarnMSTemplateArg)
6763 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6764 << ArgIn->getSourceRange();
6765
6766 if (FirstOpKind == UO_AddrOf)
6767 AddressTaken = true;
6768 else if (Arg->getType()->isPointerType()) {
6769 // We cannot let pointers get dereferenced here, that is obviously not a
6770 // constant expression.
6771 assert(FirstOpKind == UO_Deref);
6772 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6773 << Arg->getSourceRange();
6774 }
6775 }
6776 } else {
6777 // See through any implicit casts we added to fix the type.
6778 // Also ignore parentheses for deduced template arguments.
6779 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6780
6781 // C++ [temp.arg.nontype]p1:
6782 //
6783 // A template-argument for a non-type, non-template
6784 // template-parameter shall be one of: [...]
6785 //
6786 // -- the address of an object or function with external
6787 // linkage, including function templates and function
6788 // template-ids but excluding non-static class members,
6789 // expressed as & id-expression where the & is optional if
6790 // the name refers to a function or array, or if the
6791 // corresponding template-parameter is a reference; or
6792
6793 // In C++98/03 mode, give an extension warning on any extra parentheses.
6794 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6795 if (IsSpecified) {
6796 bool ExtraParens = false;
6797 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6798 if (!ExtraParens) {
6799 S.DiagCompat(Arg->getBeginLoc(),
6800 diag_compat::template_arg_extra_parens)
6801 << Arg->getSourceRange();
6802 ExtraParens = true;
6803 }
6804
6805 Arg = Parens->getSubExpr();
6806 }
6807 }
6808
6809 while (SubstNonTypeTemplateParmExpr *subst =
6810 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6811 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6812
6813 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6814 if (UnOp->getOpcode() == UO_AddrOf) {
6815 Arg = UnOp->getSubExpr();
6816 AddressTaken = true;
6817 AddrOpLoc = UnOp->getOperatorLoc();
6818 }
6819 }
6820
6821 while (SubstNonTypeTemplateParmExpr *subst =
6822 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6823 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6824 }
6825
6826 ValueDecl *Entity = nullptr;
6827 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6828 Entity = DRE->getDecl();
6829 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6830 Entity = CUE->getGuidDecl();
6831
6832 // If our parameter has pointer type, check for a null template value.
6833 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6834 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6835 Entity)) {
6836 case NPV_NullPointer:
6837 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6838 SugaredConverted = TemplateArgument(ParamType,
6839 /*isNullPtr=*/true);
6840 CanonicalConverted =
6842 /*isNullPtr=*/true);
6843 return false;
6844
6845 case NPV_Error:
6846 return true;
6847
6848 case NPV_NotNullPointer:
6849 break;
6850 }
6851 }
6852
6853 // Stop checking the precise nature of the argument if it is value dependent,
6854 // it should be checked when instantiated.
6855 if (Arg->isValueDependent()) {
6856 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6857 CanonicalConverted =
6858 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6859 return false;
6860 }
6861
6862 if (!Entity) {
6863 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6864 << Arg->getSourceRange();
6866 return true;
6867 }
6868
6869 // Cannot refer to non-static data members
6870 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6871 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6872 << Entity << Arg->getSourceRange();
6874 return true;
6875 }
6876
6877 // Cannot refer to non-static member functions
6878 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6879 if (!Method->isStatic()) {
6880 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6881 << Method << Arg->getSourceRange();
6883 return true;
6884 }
6885 }
6886
6887 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6888 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6889 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6890
6891 // A non-type template argument must refer to an object or function.
6892 if (!Func && !Var && !Guid) {
6893 // We found something, but we don't know specifically what it is.
6894 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6895 << Arg->getSourceRange();
6896 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6897 return true;
6898 }
6899
6900 // Address / reference template args must have external linkage in C++98.
6901 if (Entity->getFormalLinkage() == Linkage::Internal) {
6902 S.Diag(Arg->getBeginLoc(),
6903 S.getLangOpts().CPlusPlus11
6904 ? diag::warn_cxx98_compat_template_arg_object_internal
6905 : diag::ext_template_arg_object_internal)
6906 << !Func << Entity << Arg->getSourceRange();
6907 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6908 << !Func;
6909 } else if (!Entity->hasLinkage()) {
6910 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6911 << !Func << Entity << Arg->getSourceRange();
6912 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6913 << !Func;
6914 return true;
6915 }
6916
6917 if (Var) {
6918 // A value of reference type is not an object.
6919 if (Var->getType()->isReferenceType()) {
6920 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6921 << Var->getType() << Arg->getSourceRange();
6923 return true;
6924 }
6925
6926 // A template argument must have static storage duration.
6927 if (Var->getTLSKind()) {
6928 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6929 << Arg->getSourceRange();
6930 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6931 return true;
6932 }
6933 }
6934
6935 if (AddressTaken && ParamType->isReferenceType()) {
6936 // If we originally had an address-of operator, but the
6937 // parameter has reference type, complain and (if things look
6938 // like they will work) drop the address-of operator.
6939 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6940 ParamType.getNonReferenceType())) {
6941 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6942 << ParamType;
6944 return true;
6945 }
6946
6947 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6948 << ParamType
6949 << FixItHint::CreateRemoval(AddrOpLoc);
6951
6952 ArgType = Entity->getType();
6953 }
6954
6955 // If the template parameter has pointer type, either we must have taken the
6956 // address or the argument must decay to a pointer.
6957 if (!AddressTaken && ParamType->isPointerType()) {
6958 if (Func) {
6959 // Function-to-pointer decay.
6960 ArgType = S.Context.getPointerType(Func->getType());
6961 } else if (Entity->getType()->isArrayType()) {
6962 // Array-to-pointer decay.
6963 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6964 } else {
6965 // If the template parameter has pointer type but the address of
6966 // this object was not taken, complain and (possibly) recover by
6967 // taking the address of the entity.
6968 ArgType = S.Context.getPointerType(Entity->getType());
6969 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6970 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6971 << ParamType;
6973 return true;
6974 }
6975
6976 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6977 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6978
6980 }
6981 }
6982
6983 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6984 Arg, ArgType))
6985 return true;
6986
6987 // Create the template argument.
6988 SugaredConverted = TemplateArgument(Entity, ParamType);
6989 CanonicalConverted =
6991 S.Context.getCanonicalType(ParamType));
6992 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6993 return false;
6994}
6995
6996/// Checks whether the given template argument is a pointer to
6997/// member constant according to C++ [temp.arg.nontype]p1.
6999 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7000 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7001 bool Invalid = false;
7002
7003 Expr *Arg = ResultArg;
7004 bool ObjCLifetimeConversion;
7005
7006 // C++ [temp.arg.nontype]p1:
7007 //
7008 // A template-argument for a non-type, non-template
7009 // template-parameter shall be one of: [...]
7010 //
7011 // -- a pointer to member expressed as described in 5.3.1.
7012 DeclRefExpr *DRE = nullptr;
7013
7014 // In C++98/03 mode, give an extension warning on any extra parentheses.
7015 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7016 bool ExtraParens = false;
7017 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7018 if (!Invalid && !ExtraParens) {
7019 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7020 << Arg->getSourceRange();
7021 ExtraParens = true;
7022 }
7023
7024 Arg = Parens->getSubExpr();
7025 }
7026
7027 while (SubstNonTypeTemplateParmExpr *subst =
7028 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7029 Arg = subst->getReplacement()->IgnoreImpCasts();
7030
7031 // A pointer-to-member constant written &Class::member.
7032 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7033 if (UnOp->getOpcode() == UO_AddrOf) {
7034 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7035 if (DRE && !DRE->getQualifier())
7036 DRE = nullptr;
7037 }
7038 }
7039 // A constant of pointer-to-member type.
7040 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7041 ValueDecl *VD = DRE->getDecl();
7042 if (VD->getType()->isMemberPointerType()) {
7044 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7045 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7046 CanonicalConverted =
7047 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7048 } else {
7049 SugaredConverted = TemplateArgument(VD, ParamType);
7050 CanonicalConverted =
7052 S.Context.getCanonicalType(ParamType));
7053 }
7054 return Invalid;
7055 }
7056 }
7057
7058 DRE = nullptr;
7059 }
7060
7061 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7062
7063 // Check for a null pointer value.
7064 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7065 Entity)) {
7066 case NPV_Error:
7067 return true;
7068 case NPV_NullPointer:
7069 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7070 SugaredConverted = TemplateArgument(ParamType,
7071 /*isNullPtr*/ true);
7072 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7073 /*isNullPtr*/ true);
7074 return false;
7075 case NPV_NotNullPointer:
7076 break;
7077 }
7078
7079 if (S.IsQualificationConversion(ResultArg->getType(),
7080 ParamType.getNonReferenceType(), false,
7081 ObjCLifetimeConversion)) {
7082 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7083 ResultArg->getValueKind())
7084 .get();
7085 } else if (!S.Context.hasSameUnqualifiedType(
7086 ResultArg->getType(), ParamType.getNonReferenceType())) {
7087 // We can't perform this conversion.
7088 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7089 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7091 return true;
7092 }
7093
7094 if (!DRE)
7095 return S.Diag(Arg->getBeginLoc(),
7096 diag::err_template_arg_not_pointer_to_member_form)
7097 << Arg->getSourceRange();
7098
7099 if (isa<FieldDecl>(DRE->getDecl()) ||
7101 isa<CXXMethodDecl>(DRE->getDecl())) {
7102 assert((isa<FieldDecl>(DRE->getDecl()) ||
7105 ->isImplicitObjectMemberFunction()) &&
7106 "Only non-static member pointers can make it here");
7107
7108 // Okay: this is the address of a non-static member, and therefore
7109 // a member pointer constant.
7110 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7111 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7112 CanonicalConverted =
7113 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7114 } else {
7115 ValueDecl *D = DRE->getDecl();
7116 SugaredConverted = TemplateArgument(D, ParamType);
7117 CanonicalConverted =
7119 S.Context.getCanonicalType(ParamType));
7120 }
7121 return Invalid;
7122 }
7123
7124 // We found something else, but we don't know specifically what it is.
7125 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7126 << Arg->getSourceRange();
7127 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7128 return true;
7129}
7130
7131/// Check a template argument against its corresponding
7132/// non-type template parameter.
7133///
7134/// This routine implements the semantics of C++ [temp.arg.nontype].
7135/// If an error occurred, it returns ExprError(); otherwise, it
7136/// returns the converted template argument. \p ParamType is the
7137/// type of the non-type template parameter after it has been instantiated.
7139 Expr *Arg,
7140 TemplateArgument &SugaredConverted,
7141 TemplateArgument &CanonicalConverted,
7142 bool StrictCheck,
7144 SourceLocation StartLoc = Arg->getBeginLoc();
7145 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7146 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7147 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7148 DeductionArg = NewDeductionArg;
7149 if (ArgPE) {
7150 // Recreate a pack expansion if we unwrapped one.
7151 Arg = new (Context) PackExpansionExpr(
7152 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7153 } else {
7154 Arg = DeductionArg;
7155 }
7156 };
7157
7158 // If the parameter type somehow involves auto, deduce the type now.
7159 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7160 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7161 if (IsDeduced) {
7162 // When checking a deduced template argument, deduce from its type even if
7163 // the type is dependent, in order to check the types of non-type template
7164 // arguments line up properly in partial ordering.
7165 TypeSourceInfo *TSI =
7166 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7168 InitializedEntity Entity =
7171 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7172 Expr *Inits[1] = {DeductionArg};
7173 ParamType =
7175 if (ParamType.isNull())
7176 return ExprError();
7177 } else {
7178 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7179 Param->getTemplateDepth() + 1);
7180 ParamType = QualType();
7182 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7183 /*DependentDeduction=*/true,
7184 // We do not check constraints right now because the
7185 // immediately-declared constraint of the auto type is
7186 // also an associated constraint, and will be checked
7187 // along with the other associated constraints after
7188 // checking the template argument list.
7189 /*IgnoreConstraints=*/true);
7191 ParamType = TSI->getType();
7192 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7194 return ExprError();
7195 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7196 Diag(Arg->getExprLoc(),
7197 diag::err_non_type_template_parm_type_deduction_failure)
7198 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7199 << Arg->getSourceRange();
7201 return ExprError();
7202 }
7203 ParamType = SubstAutoTypeDependent(ParamType);
7204 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7205 }
7206 }
7207 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7208 // an error. The error message normally references the parameter
7209 // declaration, but here we'll pass the argument location because that's
7210 // where the parameter type is deduced.
7211 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7212 if (ParamType.isNull()) {
7214 return ExprError();
7215 }
7216 }
7217
7218 // We should have already dropped all cv-qualifiers by now.
7219 assert(!ParamType.hasQualifiers() &&
7220 "non-type template parameter type cannot be qualified");
7221
7222 // If either the parameter has a dependent type or the argument is
7223 // type-dependent, there's nothing we can check now.
7224 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7225 // Force the argument to the type of the parameter to maintain invariants.
7226 if (!IsDeduced) {
7228 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7229 ParamType->isLValueReferenceType() ? VK_LValue
7230 : ParamType->isRValueReferenceType() ? VK_XValue
7231 : VK_PRValue);
7232 if (E.isInvalid())
7233 return ExprError();
7234 setDeductionArg(E.get());
7235 }
7236 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7237 CanonicalConverted = TemplateArgument(
7238 Context.getCanonicalTemplateArgument(SugaredConverted));
7239 return Arg;
7240 }
7241
7242 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7243 if (CTAK == CTAK_Deduced && !StrictCheck &&
7244 (ParamType->isReferenceType()
7245 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7246 DeductionArg->getType())
7247 : !Context.hasSameUnqualifiedType(ParamType,
7248 DeductionArg->getType()))) {
7249 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7250 // we should actually be checking the type of the template argument in P,
7251 // not the type of the template argument deduced from A, against the
7252 // template parameter type.
7253 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7254 << Arg->getType() << ParamType.getUnqualifiedType();
7256 return ExprError();
7257 }
7258
7259 // If the argument is a pack expansion, we don't know how many times it would
7260 // expand. If we continue checking the argument, this will make the template
7261 // definition ill-formed if it would be ill-formed for any number of
7262 // expansions during instantiation time. When partial ordering or matching
7263 // template template parameters, this is exactly what we want. Otherwise, the
7264 // normal template rules apply: we accept the template if it would be valid
7265 // for any number of expansions (i.e. none).
7266 if (ArgPE && !StrictCheck) {
7267 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7268 CanonicalConverted = TemplateArgument(
7269 Context.getCanonicalTemplateArgument(SugaredConverted));
7270 return Arg;
7271 }
7272
7273 // Avoid making a copy when initializing a template parameter of class type
7274 // from a template parameter object of the same type. This is going beyond
7275 // the standard, but is required for soundness: in
7276 // template<A a> struct X { X *p; X<a> *q; };
7277 // ... we need p and q to have the same type.
7278 //
7279 // Similarly, don't inject a call to a copy constructor when initializing
7280 // from a template parameter of the same type.
7281 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7282 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7283 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7284 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7285 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7286
7287 SugaredConverted = TemplateArgument(TPO, ParamType);
7288 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7289 ParamType.getCanonicalType());
7290 return Arg;
7291 }
7293 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7294 CanonicalConverted =
7295 Context.getCanonicalTemplateArgument(SugaredConverted);
7296 return Arg;
7297 }
7298 }
7299
7300 // The initialization of the parameter from the argument is
7301 // a constant-evaluated context.
7304
7305 bool IsConvertedConstantExpression = true;
7306 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7308 StartLoc, /*DirectInit=*/false, DeductionArg);
7309 Expr *Inits[1] = {DeductionArg};
7310 InitializedEntity Entity =
7312 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7313 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7314 if (Result.isInvalid() || !Result.get())
7315 return ExprError();
7317 if (Result.isInvalid() || !Result.get())
7318 return ExprError();
7319 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7320 /*DiscardedValue=*/false,
7321 /*IsConstexpr=*/true,
7322 /*IsTemplateArgument=*/true)
7323 .get());
7324 IsConvertedConstantExpression = false;
7325 }
7326
7327 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7328 // C++17 [temp.arg.nontype]p1:
7329 // A template-argument for a non-type template parameter shall be
7330 // a converted constant expression of the type of the template-parameter.
7331 APValue Value;
7332 ExprResult ArgResult;
7333 if (IsConvertedConstantExpression) {
7335 DeductionArg, ParamType,
7336 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7337 assert(!ArgResult.isUnset());
7338 if (ArgResult.isInvalid()) {
7340 return ExprError();
7341 }
7342 } else {
7343 ArgResult = DeductionArg;
7344 }
7345
7346 // For a value-dependent argument, CheckConvertedConstantExpression is
7347 // permitted (and expected) to be unable to determine a value.
7348 if (ArgResult.get()->isValueDependent()) {
7349 setDeductionArg(ArgResult.get());
7350 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7351 CanonicalConverted =
7352 Context.getCanonicalTemplateArgument(SugaredConverted);
7353 return Arg;
7354 }
7355
7356 APValue PreNarrowingValue;
7358 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7359 false, PreNarrowingValue);
7360 if (ArgResult.isInvalid())
7361 return ExprError();
7362 setDeductionArg(ArgResult.get());
7363
7364 if (Value.isLValue()) {
7365 APValue::LValueBase Base = Value.getLValueBase();
7366 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7367 // For a non-type template-parameter of pointer or reference type,
7368 // the value of the constant expression shall not refer to
7369 assert(ParamType->isPointerOrReferenceType() ||
7370 ParamType->isNullPtrType());
7371 // -- a temporary object
7372 // -- a string literal
7373 // -- the result of a typeid expression, or
7374 // -- a predefined __func__ variable
7375 if (Base &&
7376 (!VD ||
7378 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7379 << Arg->getSourceRange();
7380 return ExprError();
7381 }
7382
7383 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7384 VD->getType()->isArrayType() &&
7385 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7386 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7387 if (ArgPE) {
7388 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7389 CanonicalConverted =
7390 Context.getCanonicalTemplateArgument(SugaredConverted);
7391 } else {
7392 SugaredConverted = TemplateArgument(VD, ParamType);
7393 CanonicalConverted =
7395 ParamType.getCanonicalType());
7396 }
7397 return Arg;
7398 }
7399
7400 // -- a subobject [until C++20]
7401 if (!getLangOpts().CPlusPlus20) {
7402 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7403 Value.isLValueOnePastTheEnd()) {
7404 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7405 << Value.getAsString(Context, ParamType);
7406 return ExprError();
7407 }
7408 assert((VD || !ParamType->isReferenceType()) &&
7409 "null reference should not be a constant expression");
7410 assert((!VD || !ParamType->isNullPtrType()) &&
7411 "non-null value of type nullptr_t?");
7412 }
7413 }
7414
7415 if (Value.isAddrLabelDiff())
7416 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7417
7418 if (ArgPE) {
7419 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7420 CanonicalConverted =
7421 Context.getCanonicalTemplateArgument(SugaredConverted);
7422 } else {
7423 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7424 CanonicalConverted =
7426 }
7427 return Arg;
7428 }
7429
7430 // These should have all been handled above using the C++17 rules.
7431 assert(!ArgPE && !StrictCheck);
7432
7433 // C++ [temp.arg.nontype]p5:
7434 // The following conversions are performed on each expression used
7435 // as a non-type template-argument. If a non-type
7436 // template-argument cannot be converted to the type of the
7437 // corresponding template-parameter then the program is
7438 // ill-formed.
7439 if (ParamType->isIntegralOrEnumerationType()) {
7440 // C++11:
7441 // -- for a non-type template-parameter of integral or
7442 // enumeration type, conversions permitted in a converted
7443 // constant expression are applied.
7444 //
7445 // C++98:
7446 // -- for a non-type template-parameter of integral or
7447 // enumeration type, integral promotions (4.5) and integral
7448 // conversions (4.7) are applied.
7449
7450 if (getLangOpts().CPlusPlus11) {
7451 // C++ [temp.arg.nontype]p1:
7452 // A template-argument for a non-type, non-template template-parameter
7453 // shall be one of:
7454 //
7455 // -- for a non-type template-parameter of integral or enumeration
7456 // type, a converted constant expression of the type of the
7457 // template-parameter; or
7458 llvm::APSInt Value;
7460 Arg, ParamType, Value, CCEKind::TemplateArg);
7461 if (ArgResult.isInvalid())
7462 return ExprError();
7463 Arg = ArgResult.get();
7464
7465 // We can't check arbitrary value-dependent arguments.
7466 if (Arg->isValueDependent()) {
7467 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7468 CanonicalConverted =
7469 Context.getCanonicalTemplateArgument(SugaredConverted);
7470 return Arg;
7471 }
7472
7473 // Widen the argument value to sizeof(parameter type). This is almost
7474 // always a no-op, except when the parameter type is bool. In
7475 // that case, this may extend the argument from 1 bit to 8 bits.
7476 QualType IntegerType = ParamType;
7477 if (const auto *ED = IntegerType->getAsEnumDecl())
7478 IntegerType = ED->getIntegerType();
7479 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7480 ? Context.getIntWidth(IntegerType)
7481 : Context.getTypeSize(IntegerType));
7482
7483 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7484 CanonicalConverted =
7485 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7486 return Arg;
7487 }
7488
7489 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7490 if (ArgResult.isInvalid())
7491 return ExprError();
7492 Arg = ArgResult.get();
7493
7494 QualType ArgType = Arg->getType();
7495
7496 // C++ [temp.arg.nontype]p1:
7497 // A template-argument for a non-type, non-template
7498 // template-parameter shall be one of:
7499 //
7500 // -- an integral constant-expression of integral or enumeration
7501 // type; or
7502 // -- the name of a non-type template-parameter; or
7503 llvm::APSInt Value;
7504 if (!ArgType->isIntegralOrEnumerationType()) {
7505 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7506 << ArgType << Arg->getSourceRange();
7508 return ExprError();
7509 }
7510 if (!Arg->isValueDependent()) {
7511 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7512 QualType T;
7513
7514 public:
7515 TmplArgICEDiagnoser(QualType T) : T(T) { }
7516
7517 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7518 SourceLocation Loc) override {
7519 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7520 }
7521 } Diagnoser(ArgType);
7522
7523 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7524 if (!Arg)
7525 return ExprError();
7526 }
7527
7528 // From here on out, all we care about is the unqualified form
7529 // of the argument type.
7530 ArgType = ArgType.getUnqualifiedType();
7531
7532 // Try to convert the argument to the parameter's type.
7533 if (Context.hasSameType(ParamType, ArgType)) {
7534 // Okay: no conversion necessary
7535 } else if (ParamType->isBooleanType()) {
7536 // This is an integral-to-boolean conversion.
7537 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7538 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7539 !ParamType->isEnumeralType()) {
7540 // This is an integral promotion or conversion.
7541 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7542 } else {
7543 // We can't perform this conversion.
7544 Diag(StartLoc, diag::err_template_arg_not_convertible)
7545 << Arg->getType() << ParamType << Arg->getSourceRange();
7547 return ExprError();
7548 }
7549
7550 // Add the value of this argument to the list of converted
7551 // arguments. We use the bitwidth and signedness of the template
7552 // parameter.
7553 if (Arg->isValueDependent()) {
7554 // The argument is value-dependent. Create a new
7555 // TemplateArgument with the converted expression.
7556 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7557 CanonicalConverted =
7558 Context.getCanonicalTemplateArgument(SugaredConverted);
7559 return Arg;
7560 }
7561
7562 QualType IntegerType = ParamType;
7563 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7564 IntegerType = ED->getIntegerType();
7565 }
7566
7567 if (ParamType->isBooleanType()) {
7568 // Value must be zero or one.
7569 Value = Value != 0;
7570 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7571 if (Value.getBitWidth() != AllowedBits)
7572 Value = Value.extOrTrunc(AllowedBits);
7573 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7574 } else {
7575 llvm::APSInt OldValue = Value;
7576
7577 // Coerce the template argument's value to the value it will have
7578 // based on the template parameter's type.
7579 unsigned AllowedBits = IntegerType->isBitIntType()
7580 ? Context.getIntWidth(IntegerType)
7581 : Context.getTypeSize(IntegerType);
7582 if (Value.getBitWidth() != AllowedBits)
7583 Value = Value.extOrTrunc(AllowedBits);
7584 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7585
7586 // Complain if an unsigned parameter received a negative value.
7587 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7588 (OldValue.isSigned() && OldValue.isNegative())) {
7589 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7590 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7591 << Arg->getSourceRange();
7593 }
7594
7595 // Complain if we overflowed the template parameter's type.
7596 unsigned RequiredBits;
7597 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7598 RequiredBits = OldValue.getActiveBits();
7599 else if (OldValue.isUnsigned())
7600 RequiredBits = OldValue.getActiveBits() + 1;
7601 else
7602 RequiredBits = OldValue.getSignificantBits();
7603 if (RequiredBits > AllowedBits) {
7604 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7605 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7606 << Arg->getSourceRange();
7608 }
7609 }
7610
7611 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7612 SugaredConverted = TemplateArgument(Context, Value, T);
7613 CanonicalConverted =
7614 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7615 return Arg;
7616 }
7617
7618 QualType ArgType = Arg->getType();
7619 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7620 bool IsSpecified = CTAK == CTAK_Specified;
7621
7622 // Handle pointer-to-function, reference-to-function, and
7623 // pointer-to-member-function all in (roughly) the same way.
7624 if (// -- For a non-type template-parameter of type pointer to
7625 // function, only the function-to-pointer conversion (4.3) is
7626 // applied. If the template-argument represents a set of
7627 // overloaded functions (or a pointer to such), the matching
7628 // function is selected from the set (13.4).
7629 (ParamType->isPointerType() &&
7630 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7631 // -- For a non-type template-parameter of type reference to
7632 // function, no conversions apply. If the template-argument
7633 // represents a set of overloaded functions, the matching
7634 // function is selected from the set (13.4).
7635 (ParamType->isReferenceType() &&
7636 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7637 // -- For a non-type template-parameter of type pointer to
7638 // member function, no conversions apply. If the
7639 // template-argument represents a set of overloaded member
7640 // functions, the matching member function is selected from
7641 // the set (13.4).
7642 (ParamType->isMemberPointerType() &&
7643 ParamType->castAs<MemberPointerType>()->getPointeeType()
7644 ->isFunctionType())) {
7645
7646 if (Arg->getType() == Context.OverloadTy) {
7647 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7648 true,
7649 FoundResult)) {
7650 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7651 return ExprError();
7652
7653 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7654 if (Res.isInvalid())
7655 return ExprError();
7656 Arg = Res.get();
7657 ArgType = Arg->getType();
7658 } else
7659 return ExprError();
7660 }
7661
7662 if (!ParamType->isMemberPointerType()) {
7664 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7665 CanonicalConverted))
7666 return ExprError();
7667 return Arg;
7668 }
7669
7671 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7672 return ExprError();
7673 return Arg;
7674 }
7675
7676 if (ParamType->isPointerType()) {
7677 // -- for a non-type template-parameter of type pointer to
7678 // object, qualification conversions (4.4) and the
7679 // array-to-pointer conversion (4.2) are applied.
7680 // C++0x also allows a value of std::nullptr_t.
7681 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7682 "Only object pointers allowed here");
7683
7685 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7686 CanonicalConverted))
7687 return ExprError();
7688 return Arg;
7689 }
7690
7691 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7692 // -- For a non-type template-parameter of type reference to
7693 // object, no conversions apply. The type referred to by the
7694 // reference may be more cv-qualified than the (otherwise
7695 // identical) type of the template-argument. The
7696 // template-parameter is bound directly to the
7697 // template-argument, which must be an lvalue.
7698 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7699 "Only object references allowed here");
7700
7701 if (Arg->getType() == Context.OverloadTy) {
7703 ParamRefType->getPointeeType(),
7704 true,
7705 FoundResult)) {
7706 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7707 return ExprError();
7708 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7709 if (Res.isInvalid())
7710 return ExprError();
7711 Arg = Res.get();
7712 ArgType = Arg->getType();
7713 } else
7714 return ExprError();
7715 }
7716
7718 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7719 CanonicalConverted))
7720 return ExprError();
7721 return Arg;
7722 }
7723
7724 // Deal with parameters of type std::nullptr_t.
7725 if (ParamType->isNullPtrType()) {
7726 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7727 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7728 CanonicalConverted =
7729 Context.getCanonicalTemplateArgument(SugaredConverted);
7730 return Arg;
7731 }
7732
7733 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7734 case NPV_NotNullPointer:
7735 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7736 << Arg->getType() << ParamType;
7738 return ExprError();
7739
7740 case NPV_Error:
7741 return ExprError();
7742
7743 case NPV_NullPointer:
7744 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7745 SugaredConverted = TemplateArgument(ParamType,
7746 /*isNullPtr=*/true);
7747 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7748 /*isNullPtr=*/true);
7749 return Arg;
7750 }
7751 }
7752
7753 // -- For a non-type template-parameter of type pointer to data
7754 // member, qualification conversions (4.4) are applied.
7755 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7756
7758 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7759 return ExprError();
7760 return Arg;
7761}
7762
7766
7769 const TemplateArgumentLoc &Arg) {
7770 // C++0x [temp.arg.template]p1:
7771 // A template-argument for a template template-parameter shall be
7772 // the name of a class template or an alias template, expressed as an
7773 // id-expression. When the template-argument names a class template, only
7774 // primary class templates are considered when matching the
7775 // template template argument with the corresponding parameter;
7776 // partial specializations are not considered even if their
7777 // parameter lists match that of the template template parameter.
7778 //
7779
7781 unsigned DiagFoundKind = 0;
7782
7783 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7784 switch (TTP->templateParameterKind()) {
7786 DiagFoundKind = 3;
7787 break;
7789 DiagFoundKind = 2;
7790 break;
7791 default:
7792 DiagFoundKind = 1;
7793 break;
7794 }
7795 Kind = TTP->templateParameterKind();
7796 } else if (isa<ConceptDecl>(Template)) {
7798 DiagFoundKind = 3;
7799 } else if (isa<FunctionTemplateDecl>(Template)) {
7801 DiagFoundKind = 0;
7802 } else if (isa<VarTemplateDecl>(Template)) {
7804 DiagFoundKind = 2;
7805 } else if (isa<ClassTemplateDecl>(Template) ||
7809 DiagFoundKind = 1;
7810 } else {
7811 assert(false && "Unexpected Decl");
7812 }
7813
7814 if (Kind == Param->templateParameterKind()) {
7815 return true;
7816 }
7817
7818 unsigned DiagKind = 0;
7819 switch (Param->templateParameterKind()) {
7821 DiagKind = 2;
7822 break;
7824 DiagKind = 1;
7825 break;
7826 default:
7827 DiagKind = 0;
7828 break;
7829 }
7830 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7831 << DiagKind;
7832 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7833 << DiagFoundKind << Template;
7834 return false;
7835}
7836
7837/// Check a template argument against its corresponding
7838/// template template parameter.
7839///
7840/// This routine implements the semantics of C++ [temp.arg.template].
7841/// It returns true if an error occurred, and false otherwise.
7843 TemplateParameterList *Params,
7845 bool PartialOrdering,
7846 bool *StrictPackMatch) {
7848 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7849 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7850 if (!Template) {
7851 // FIXME: Handle AssumedTemplateNames
7852 // Any dependent template name is fine.
7853 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7854 return false;
7855 }
7856
7857 if (Template->isInvalidDecl())
7858 return true;
7859
7861 return true;
7862 }
7863
7864 // C++1z [temp.arg.template]p3: (DR 150)
7865 // A template-argument matches a template template-parameter P when P
7866 // is at least as specialized as the template-argument A.
7868 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7869 PartialOrdering, StrictPackMatch))
7870 return true;
7871 // P2113
7872 // C++20[temp.func.order]p2
7873 // [...] If both deductions succeed, the partial ordering selects the
7874 // more constrained template (if one exists) as determined below.
7875 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7876 Params->getAssociatedConstraints(ParamsAC);
7877 // C++20[temp.arg.template]p3
7878 // [...] In this comparison, if P is unconstrained, the constraints on A
7879 // are not considered.
7880 if (ParamsAC.empty())
7881 return false;
7882
7883 Template->getAssociatedConstraints(TemplateAC);
7884
7885 bool IsParamAtLeastAsConstrained;
7886 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7887 IsParamAtLeastAsConstrained))
7888 return true;
7889 if (!IsParamAtLeastAsConstrained) {
7890 Diag(Arg.getLocation(),
7891 diag::err_template_template_parameter_not_at_least_as_constrained)
7892 << Template << Param << Arg.getSourceRange();
7893 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7894 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7896 TemplateAC);
7897 return true;
7898 }
7899 return false;
7900}
7901
7903 unsigned HereDiagID,
7904 unsigned ExternalDiagID) {
7905 if (Decl.getLocation().isValid())
7906 return S.Diag(Decl.getLocation(), HereDiagID);
7907
7908 SmallString<128> Str;
7909 llvm::raw_svector_ostream Out(Str);
7911 PP.TerseOutput = 1;
7912 Decl.print(Out, PP);
7913 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7914}
7915
7917 std::optional<SourceRange> ParamRange) {
7919 noteLocation(*this, Decl, diag::note_template_decl_here,
7920 diag::note_template_decl_external);
7921 if (ParamRange && ParamRange->isValid()) {
7922 assert(Decl.getLocation().isValid() &&
7923 "Parameter range has location when Decl does not");
7924 DB << *ParamRange;
7925 }
7926}
7927
7929 noteLocation(*this, Decl, diag::note_template_param_here,
7930 diag::note_template_param_external);
7931}
7932
7933/// Given a non-type template argument that refers to a
7934/// declaration and the type of its corresponding non-type template
7935/// parameter, produce an expression that properly refers to that
7936/// declaration.
7938 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7939 // C++ [temp.param]p8:
7940 //
7941 // A non-type template-parameter of type "array of T" or
7942 // "function returning T" is adjusted to be of type "pointer to
7943 // T" or "pointer to function returning T", respectively.
7944 if (ParamType->isArrayType())
7945 ParamType = Context.getArrayDecayedType(ParamType);
7946 else if (ParamType->isFunctionType())
7947 ParamType = Context.getPointerType(ParamType);
7948
7949 // For a NULL non-type template argument, return nullptr casted to the
7950 // parameter's type.
7951 if (Arg.getKind() == TemplateArgument::NullPtr) {
7952 return ImpCastExprToType(
7953 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7954 ParamType,
7955 ParamType->getAs<MemberPointerType>()
7956 ? CK_NullToMemberPointer
7957 : CK_NullToPointer);
7958 }
7959 assert(Arg.getKind() == TemplateArgument::Declaration &&
7960 "Only declaration template arguments permitted here");
7961
7962 ValueDecl *VD = Arg.getAsDecl();
7963
7964 CXXScopeSpec SS;
7965 if (ParamType->isMemberPointerType()) {
7966 // If this is a pointer to member, we need to use a qualified name to
7967 // form a suitable pointer-to-member constant.
7968 assert(VD->getDeclContext()->isRecord() &&
7969 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7971 CanQualType ClassType =
7972 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7973 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7974 SS.MakeTrivial(Context, Qualifier, Loc);
7975 }
7976
7978 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7979 if (RefExpr.isInvalid())
7980 return ExprError();
7981
7982 // For a pointer, the argument declaration is the pointee. Take its address.
7983 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7984 if (ParamType->isPointerType() && !ElemT.isNull() &&
7985 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7986 // Decay an array argument if we want a pointer to its first element.
7987 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7988 if (RefExpr.isInvalid())
7989 return ExprError();
7990 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7991 // For any other pointer, take the address (or form a pointer-to-member).
7992 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7993 if (RefExpr.isInvalid())
7994 return ExprError();
7995 } else if (ParamType->isRecordType()) {
7996 assert(isa<TemplateParamObjectDecl>(VD) &&
7997 "arg for class template param not a template parameter object");
7998 // No conversions apply in this case.
7999 return RefExpr;
8000 } else {
8001 assert(ParamType->isReferenceType() &&
8002 "unexpected type for decl template argument");
8003 // If the parameter has reference type, wrap it in paretheses so that this
8004 // expression will have the correct type under `decltype`.
8005 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8006 }
8007
8008 // At this point we should have the right value category.
8009 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8010 "value kind mismatch for non-type template argument");
8011
8012 // The type of the template parameter can differ from the type of the
8013 // argument in various ways; convert it now if necessary.
8014 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8015 QualType SrcExprType = RefExpr.get()->getType();
8016 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8017 CastKind CK;
8018 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8019 IsFunctionConversion(SrcExprType, DestExprType)) {
8020 CK = CK_NoOp;
8021 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8022 CK = CK_BitCast;
8023 } else {
8024 // FIXME: Pointers to members can need conversion derived-to-base or
8025 // base-to-derived conversions. We currently don't retain enough
8026 // information to convert properly (we need to track a cast path or
8027 // subobject number in the template argument).
8028 llvm_unreachable(
8029 "unexpected conversion required for non-type template argument");
8030 }
8031 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8032 RefExpr.get()->getValueKind());
8033 }
8034
8035 return RefExpr;
8036}
8037
8038/// Construct a new expression that refers to the given
8039/// integral template argument with the given source-location
8040/// information.
8041///
8042/// This routine takes care of the mapping from an integral template
8043/// argument (which may have any integral type) to the appropriate
8044/// literal value.
8046 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8047 assert(OrigT->isIntegralOrEnumerationType());
8048
8049 // If this is an enum type that we're instantiating, we need to use an integer
8050 // type the same size as the enumerator. We don't want to build an
8051 // IntegerLiteral with enum type. The integer type of an enum type can be of
8052 // any integral type with C++11 enum classes, make sure we create the right
8053 // type of literal for it.
8054 QualType T = OrigT;
8055 if (const auto *ED = OrigT->getAsEnumDecl())
8056 T = ED->getIntegerType();
8057
8058 Expr *E;
8059 if (T->isAnyCharacterType()) {
8061 if (T->isWideCharType())
8063 else if (T->isChar8Type() && S.getLangOpts().Char8)
8065 else if (T->isChar16Type())
8067 else if (T->isChar32Type())
8069 else
8071
8072 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8073 } else if (T->isBooleanType()) {
8074 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8075 } else {
8076 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8077 }
8078
8079 if (OrigT->isEnumeralType()) {
8080 // FIXME: This is a hack. We need a better way to handle substituted
8081 // non-type template parameters.
8082 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8083 nullptr, S.CurFPFeatureOverrides(),
8084 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8085 Loc, Loc);
8086 }
8087
8088 return E;
8089}
8090
8092 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8093 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8094 auto *ILE = new (S.Context)
8095 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8096 ILE->setType(T);
8097 return ILE;
8098 };
8099
8100 switch (Val.getKind()) {
8102 // This cannot occur in a template argument at all.
8103 case APValue::Array:
8104 case APValue::Struct:
8105 case APValue::Union:
8106 // These can only occur within a template parameter object, which is
8107 // represented as a TemplateArgument::Declaration.
8108 llvm_unreachable("unexpected template argument value");
8109
8110 case APValue::Int:
8112 Loc);
8113
8114 case APValue::Float:
8115 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8116 T, Loc);
8117
8120 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8121 Val.getFixedPoint().getScale());
8122
8123 case APValue::ComplexInt: {
8124 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8126 S, ElemT, Val.getComplexIntReal(), Loc),
8128 S, ElemT, Val.getComplexIntImag(), Loc)});
8129 }
8130
8131 case APValue::ComplexFloat: {
8132 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8133 return MakeInitList(
8135 ElemT, Loc),
8137 ElemT, Loc)});
8138 }
8139
8140 case APValue::Vector: {
8141 QualType ElemT = T->castAs<VectorType>()->getElementType();
8143 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8145 S, ElemT, Val.getVectorElt(I), Loc));
8146 return MakeInitList(Elts);
8147 }
8148
8149 case APValue::Matrix:
8150 llvm_unreachable("Matrix template argument expression not yet supported");
8151
8152 case APValue::None:
8154 llvm_unreachable("Unexpected APValue kind.");
8155 case APValue::LValue:
8157 // There isn't necessarily a valid equivalent source-level syntax for
8158 // these; in particular, a naive lowering might violate access control.
8159 // So for now we lower to a ConstantExpr holding the value, wrapped around
8160 // an OpaqueValueExpr.
8161 // FIXME: We should have a better representation for this.
8163 if (T->isReferenceType()) {
8164 T = T->getPointeeType();
8165 VK = VK_LValue;
8166 }
8167 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8168 return ConstantExpr::Create(S.Context, OVE, Val);
8169 }
8170 llvm_unreachable("Unhandled APValue::ValueKind enum");
8171}
8172
8175 SourceLocation Loc) {
8176 switch (Arg.getKind()) {
8182 llvm_unreachable("not a non-type template argument");
8183
8185 return Arg.getAsExpr();
8186
8190 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8191
8194 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8195
8198 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8199 }
8200 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8201}
8202
8203/// Match two template parameters within template parameter lists.
8205 Sema &S, NamedDecl *New,
8206 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8207 const NamedDecl *OldInstFrom, bool Complain,
8209 // Check the actual kind (type, non-type, template).
8210 if (Old->getKind() != New->getKind()) {
8211 if (Complain) {
8212 unsigned NextDiag = diag::err_template_param_different_kind;
8213 if (TemplateArgLoc.isValid()) {
8214 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8215 NextDiag = diag::note_template_param_different_kind;
8216 }
8217 S.Diag(New->getLocation(), NextDiag)
8218 << (Kind != Sema::TPL_TemplateMatch);
8219 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8220 << (Kind != Sema::TPL_TemplateMatch);
8221 }
8222
8223 return false;
8224 }
8225
8226 // Check that both are parameter packs or neither are parameter packs.
8227 // However, if we are matching a template template argument to a
8228 // template template parameter, the template template parameter can have
8229 // a parameter pack where the template template argument does not.
8230 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8231 if (Complain) {
8232 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8233 if (TemplateArgLoc.isValid()) {
8234 S.Diag(TemplateArgLoc,
8235 diag::err_template_arg_template_params_mismatch);
8236 NextDiag = diag::note_template_parameter_pack_non_pack;
8237 }
8238
8239 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8241 : 2;
8242 S.Diag(New->getLocation(), NextDiag)
8243 << ParamKind << New->isParameterPack();
8244 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8245 << ParamKind << Old->isParameterPack();
8246 }
8247
8248 return false;
8249 }
8250 // For non-type template parameters, check the type of the parameter.
8251 if (NonTypeTemplateParmDecl *OldNTTP =
8252 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8254
8255 // If we are matching a template template argument to a template
8256 // template parameter and one of the non-type template parameter types
8257 // is dependent, then we must wait until template instantiation time
8258 // to actually compare the arguments.
8260 (!OldNTTP->getType()->isDependentType() &&
8261 !NewNTTP->getType()->isDependentType())) {
8262 // C++20 [temp.over.link]p6:
8263 // Two [non-type] template-parameters are equivalent [if] they have
8264 // equivalent types ignoring the use of type-constraints for
8265 // placeholder types
8266 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8267 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8268 if (!S.Context.hasSameType(OldType, NewType)) {
8269 if (Complain) {
8270 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8271 if (TemplateArgLoc.isValid()) {
8272 S.Diag(TemplateArgLoc,
8273 diag::err_template_arg_template_params_mismatch);
8274 NextDiag = diag::note_template_nontype_parm_different_type;
8275 }
8276 S.Diag(NewNTTP->getLocation(), NextDiag)
8277 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8278 S.Diag(OldNTTP->getLocation(),
8279 diag::note_template_nontype_parm_prev_declaration)
8280 << OldNTTP->getType();
8281 }
8282 return false;
8283 }
8284 }
8285 }
8286 // For template template parameters, check the template parameter types.
8287 // The template parameter lists of template template
8288 // parameters must agree.
8289 else if (TemplateTemplateParmDecl *OldTTP =
8290 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8292 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8293 return false;
8295 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8296 OldTTP->getTemplateParameters(), Complain,
8299 : Kind),
8300 TemplateArgLoc))
8301 return false;
8302 }
8303
8307 const Expr *NewC = nullptr, *OldC = nullptr;
8308
8310 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8311 NewC = TC->getImmediatelyDeclaredConstraint();
8312 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8313 OldC = TC->getImmediatelyDeclaredConstraint();
8314 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8315 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8316 ->getPlaceholderTypeConstraint())
8317 NewC = E;
8318 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8319 ->getPlaceholderTypeConstraint())
8320 OldC = E;
8321 } else
8322 llvm_unreachable("unexpected template parameter type");
8323
8324 auto Diagnose = [&] {
8325 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8326 diag::err_template_different_type_constraint);
8327 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8328 diag::note_template_prev_declaration) << /*declaration*/0;
8329 };
8330
8331 if (!NewC != !OldC) {
8332 if (Complain)
8333 Diagnose();
8334 return false;
8335 }
8336
8337 if (NewC) {
8338 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8339 NewC)) {
8340 if (Complain)
8341 Diagnose();
8342 return false;
8343 }
8344 }
8345 }
8346
8347 return true;
8348}
8349
8350/// Diagnose a known arity mismatch when comparing template argument
8351/// lists.
8352static
8357 SourceLocation TemplateArgLoc) {
8358 unsigned NextDiag = diag::err_template_param_list_different_arity;
8359 if (TemplateArgLoc.isValid()) {
8360 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8361 NextDiag = diag::note_template_param_list_different_arity;
8362 }
8363 S.Diag(New->getTemplateLoc(), NextDiag)
8364 << (New->size() > Old->size())
8365 << (Kind != Sema::TPL_TemplateMatch)
8366 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8367 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8368 << (Kind != Sema::TPL_TemplateMatch)
8369 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8370}
8371
8374 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8375 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8376 if (Old->size() != New->size()) {
8377 if (Complain)
8379 TemplateArgLoc);
8380
8381 return false;
8382 }
8383
8384 // C++0x [temp.arg.template]p3:
8385 // A template-argument matches a template template-parameter (call it P)
8386 // when each of the template parameters in the template-parameter-list of
8387 // the template-argument's corresponding class template or alias template
8388 // (call it A) matches the corresponding template parameter in the
8389 // template-parameter-list of P. [...]
8390 TemplateParameterList::iterator NewParm = New->begin();
8391 TemplateParameterList::iterator NewParmEnd = New->end();
8392 for (TemplateParameterList::iterator OldParm = Old->begin(),
8393 OldParmEnd = Old->end();
8394 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8395 if (NewParm == NewParmEnd) {
8396 if (Complain)
8398 TemplateArgLoc);
8399 return false;
8400 }
8401 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8402 OldInstFrom, Complain, Kind,
8403 TemplateArgLoc))
8404 return false;
8405 }
8406
8407 // Make sure we exhausted all of the arguments.
8408 if (NewParm != NewParmEnd) {
8409 if (Complain)
8411 TemplateArgLoc);
8412
8413 return false;
8414 }
8415
8416 if (Kind != TPL_TemplateParamsEquivalent) {
8417 const Expr *NewRC = New->getRequiresClause();
8418 const Expr *OldRC = Old->getRequiresClause();
8419
8420 auto Diagnose = [&] {
8421 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8422 diag::err_template_different_requires_clause);
8423 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8424 diag::note_template_prev_declaration) << /*declaration*/0;
8425 };
8426
8427 if (!NewRC != !OldRC) {
8428 if (Complain)
8429 Diagnose();
8430 return false;
8431 }
8432
8433 if (NewRC) {
8434 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8435 NewRC)) {
8436 if (Complain)
8437 Diagnose();
8438 return false;
8439 }
8440 }
8441 }
8442
8443 return true;
8444}
8445
8446bool
8448 if (!S)
8449 return false;
8450
8451 // Find the nearest enclosing declaration scope.
8452 S = S->getDeclParent();
8453
8454 // C++ [temp.pre]p6: [P2096]
8455 // A template, explicit specialization, or partial specialization shall not
8456 // have C linkage.
8457 DeclContext *Ctx = S->getEntity();
8458 if (Ctx && Ctx->isExternCContext()) {
8459 SourceRange Range =
8460 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8461 ? TemplateParams->getParam(0)->getSourceRange()
8462 : TemplateParams->getSourceRange();
8463 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8464 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8465 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8466 return true;
8467 }
8468 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8469
8470 // C++ [temp]p2:
8471 // A template-declaration can appear only as a namespace scope or
8472 // class scope declaration.
8473 // C++ [temp.expl.spec]p3:
8474 // An explicit specialization may be declared in any scope in which the
8475 // corresponding primary template may be defined.
8476 // C++ [temp.class.spec]p6: [P2096]
8477 // A partial specialization may be declared in any scope in which the
8478 // corresponding primary template may be defined.
8479 if (Ctx) {
8480 if (Ctx->isFileContext())
8481 return false;
8482 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8483 // C++ [temp.mem]p2:
8484 // A local class shall not have member templates.
8485 if (RD->isLocalClass())
8486 return Diag(TemplateParams->getTemplateLoc(),
8487 diag::err_template_inside_local_class)
8488 << TemplateParams->getSourceRange();
8489 else
8490 return false;
8491 }
8492 }
8493
8494 return Diag(TemplateParams->getTemplateLoc(),
8495 diag::err_template_outside_namespace_or_class_scope)
8496 << TemplateParams->getSourceRange();
8497}
8498
8499/// Determine what kind of template specialization the given declaration
8500/// is.
8502 if (!D)
8503 return TSK_Undeclared;
8504
8505 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8506 return Record->getTemplateSpecializationKind();
8507 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8508 return Function->getTemplateSpecializationKind();
8509 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8510 return Var->getTemplateSpecializationKind();
8511
8512 return TSK_Undeclared;
8513}
8514
8515/// Check whether a specialization is well-formed in the current
8516/// context.
8517///
8518/// This routine determines whether a template specialization can be declared
8519/// in the current context (C++ [temp.expl.spec]p2).
8520///
8521/// \param S the semantic analysis object for which this check is being
8522/// performed.
8523///
8524/// \param Specialized the entity being specialized or instantiated, which
8525/// may be a kind of template (class template, function template, etc.) or
8526/// a member of a class template (member function, static data member,
8527/// member class).
8528///
8529/// \param PrevDecl the previous declaration of this entity, if any.
8530///
8531/// \param Loc the location of the explicit specialization or instantiation of
8532/// this entity.
8533///
8534/// \param IsPartialSpecialization whether this is a partial specialization of
8535/// a class template.
8536///
8537/// \returns true if there was an error that we cannot recover from, false
8538/// otherwise.
8540 NamedDecl *Specialized,
8541 NamedDecl *PrevDecl,
8542 SourceLocation Loc,
8544 // Keep these "kind" numbers in sync with the %select statements in the
8545 // various diagnostics emitted by this routine.
8546 int EntityKind = 0;
8547 if (isa<ClassTemplateDecl>(Specialized))
8548 EntityKind = IsPartialSpecialization? 1 : 0;
8549 else if (isa<VarTemplateDecl>(Specialized))
8550 EntityKind = IsPartialSpecialization ? 3 : 2;
8551 else if (isa<FunctionTemplateDecl>(Specialized))
8552 EntityKind = 4;
8553 else if (isa<CXXMethodDecl>(Specialized))
8554 EntityKind = 5;
8555 else if (isa<VarDecl>(Specialized))
8556 EntityKind = 6;
8557 else if (isa<RecordDecl>(Specialized))
8558 EntityKind = 7;
8559 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8560 EntityKind = 8;
8561 else {
8562 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8563 << S.getLangOpts().CPlusPlus11;
8564 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8565 return true;
8566 }
8567
8568 // C++ [temp.expl.spec]p2:
8569 // An explicit specialization may be declared in any scope in which
8570 // the corresponding primary template may be defined.
8572 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8573 << Specialized;
8574 return true;
8575 }
8576
8577 // C++ [temp.class.spec]p6:
8578 // A class template partial specialization may be declared in any
8579 // scope in which the primary template may be defined.
8580 DeclContext *SpecializedContext =
8581 Specialized->getDeclContext()->getRedeclContext();
8583
8584 // Make sure that this redeclaration (or definition) occurs in the same
8585 // scope or an enclosing namespace.
8586 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8587 : DC->Equals(SpecializedContext))) {
8588 if (isa<TranslationUnitDecl>(SpecializedContext))
8589 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8590 << EntityKind << Specialized;
8591 else {
8592 auto *ND = cast<NamedDecl>(SpecializedContext);
8593 int Diag = diag::err_template_spec_redecl_out_of_scope;
8594 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8595 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8596 S.Diag(Loc, Diag) << EntityKind << Specialized
8597 << ND << isa<CXXRecordDecl>(ND);
8598 }
8599
8600 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8601
8602 // Don't allow specializing in the wrong class during error recovery.
8603 // Otherwise, things can go horribly wrong.
8604 if (DC->isRecord())
8605 return true;
8606 }
8607
8608 return false;
8609}
8610
8612 if (!E->isTypeDependent())
8613 return SourceLocation();
8614 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8615 Checker.TraverseStmt(E);
8616 if (Checker.MatchLoc.isInvalid())
8617 return E->getSourceRange();
8618 return Checker.MatchLoc;
8619}
8620
8621static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8622 if (!TL.getType()->isDependentType())
8623 return SourceLocation();
8624 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8625 Checker.TraverseTypeLoc(TL);
8626 if (Checker.MatchLoc.isInvalid())
8627 return TL.getSourceRange();
8628 return Checker.MatchLoc;
8629}
8630
8631/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8632/// that checks non-type template partial specialization arguments.
8634 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8635 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8636 bool HasError = false;
8637 for (unsigned I = 0; I != NumArgs; ++I) {
8638 if (Args[I].getKind() == TemplateArgument::Pack) {
8640 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8641 Args[I].pack_size(), IsDefaultArgument))
8642 return true;
8643
8644 continue;
8645 }
8646
8647 if (Args[I].getKind() != TemplateArgument::Expression)
8648 continue;
8649
8650 Expr *ArgExpr = Args[I].getAsExpr();
8651 if (ArgExpr->containsErrors()) {
8652 HasError = true;
8653 continue;
8654 }
8655
8656 // We can have a pack expansion of any of the bullets below.
8657 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8658 ArgExpr = Expansion->getPattern();
8659
8660 // Strip off any implicit casts we added as part of type checking.
8661 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8662 ArgExpr = ICE->getSubExpr();
8663
8664 // C++ [temp.class.spec]p8:
8665 // A non-type argument is non-specialized if it is the name of a
8666 // non-type parameter. All other non-type arguments are
8667 // specialized.
8668 //
8669 // Below, we check the two conditions that only apply to
8670 // specialized non-type arguments, so skip any non-specialized
8671 // arguments.
8672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8673 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8674 continue;
8675
8676 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8677 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8678 continue;
8679 }
8680
8681 // C++ [temp.class.spec]p9:
8682 // Within the argument list of a class template partial
8683 // specialization, the following restrictions apply:
8684 // -- A partially specialized non-type argument expression
8685 // shall not involve a template parameter of the partial
8686 // specialization except when the argument expression is a
8687 // simple identifier.
8688 // -- The type of a template parameter corresponding to a
8689 // specialized non-type argument shall not be dependent on a
8690 // parameter of the specialization.
8691 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8692 // We implement a compromise between the original rules and DR1315:
8693 // -- A specialized non-type template argument shall not be
8694 // type-dependent and the corresponding template parameter
8695 // shall have a non-dependent type.
8696 SourceRange ParamUseRange =
8697 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8698 if (ParamUseRange.isValid()) {
8699 if (IsDefaultArgument) {
8700 S.Diag(TemplateNameLoc,
8701 diag::err_dependent_non_type_arg_in_partial_spec);
8702 S.Diag(ParamUseRange.getBegin(),
8703 diag::note_dependent_non_type_default_arg_in_partial_spec)
8704 << ParamUseRange;
8705 } else {
8706 S.Diag(ParamUseRange.getBegin(),
8707 diag::err_dependent_non_type_arg_in_partial_spec)
8708 << ParamUseRange;
8709 }
8710 return true;
8711 }
8712
8713 ParamUseRange = findTemplateParameter(
8714 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8715 if (ParamUseRange.isValid()) {
8716 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8717 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8718 << Param->getType();
8720 return true;
8721 }
8722 }
8723
8724 return HasError;
8725}
8726
8728 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8729 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8730 // We have to be conservative when checking a template in a dependent
8731 // context.
8732 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8733 return false;
8734
8735 TemplateParameterList *TemplateParams =
8736 PrimaryTemplate->getTemplateParameters();
8737 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8739 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8740 if (!Param)
8741 continue;
8742
8743 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8744 Param, &TemplateArgs[I],
8745 1, I >= NumExplicit))
8746 return true;
8747 }
8748
8749 return false;
8750}
8751
8753 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8754 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8756 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8757 assert(TUK != TagUseKind::Reference && "References are not specializations");
8758
8759 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8760 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8761 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8762
8763 // Find the class template we're specializing
8764 TemplateName Name = TemplateId.Template.get();
8766 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8767
8768 if (!ClassTemplate) {
8769 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8770 << (Name.getAsTemplateDecl() &&
8772 return true;
8773 }
8774
8775 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8776 auto Message = DSA->getMessage();
8777 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8778 << ClassTemplate << !Message.empty() << Message;
8779 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8780 }
8781
8782 if (S->isTemplateParamScope())
8783 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8784
8785 DeclContext *DC = ClassTemplate->getDeclContext();
8786
8787 bool isMemberSpecialization = false;
8788 bool isPartialSpecialization = false;
8789
8790 if (SS.isSet()) {
8791 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8792 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8793 TemplateNameLoc, &TemplateId,
8794 /*IsMemberSpecialization=*/false))
8795 return true;
8796 }
8797
8798 // Check the validity of the template headers that introduce this
8799 // template.
8800 // FIXME: We probably shouldn't complain about these headers for
8801 // friend declarations.
8802 bool Invalid = false;
8803 TemplateParameterList *TemplateParams =
8805 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8806 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8807 if (Invalid)
8808 return true;
8809
8810 // Check that we can declare a template specialization here.
8811 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8812 return true;
8813
8814 if (TemplateParams && DC->isDependentContext()) {
8815 ContextRAII SavedContext(*this, DC);
8817 return true;
8818 }
8819
8820 if (TemplateParams && TemplateParams->size() > 0) {
8821 isPartialSpecialization = true;
8822
8823 if (TUK == TagUseKind::Friend) {
8824 Diag(KWLoc, diag::err_partial_specialization_friend)
8825 << SourceRange(LAngleLoc, RAngleLoc);
8826 return true;
8827 }
8828
8829 // C++ [temp.class.spec]p10:
8830 // The template parameter list of a specialization shall not
8831 // contain default template argument values.
8832 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8833 Decl *Param = TemplateParams->getParam(I);
8834 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8835 if (TTP->hasDefaultArgument()) {
8836 Diag(TTP->getDefaultArgumentLoc(),
8837 diag::err_default_arg_in_partial_spec);
8838 TTP->removeDefaultArgument();
8839 }
8840 } else if (NonTypeTemplateParmDecl *NTTP
8841 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8842 if (NTTP->hasDefaultArgument()) {
8843 Diag(NTTP->getDefaultArgumentLoc(),
8844 diag::err_default_arg_in_partial_spec)
8845 << NTTP->getDefaultArgument().getSourceRange();
8846 NTTP->removeDefaultArgument();
8847 }
8848 } else {
8850 if (TTP->hasDefaultArgument()) {
8852 diag::err_default_arg_in_partial_spec)
8854 TTP->removeDefaultArgument();
8855 }
8856 }
8857 }
8858 } else if (TemplateParams) {
8859 if (TUK == TagUseKind::Friend)
8860 Diag(KWLoc, diag::err_template_spec_friend)
8862 SourceRange(TemplateParams->getTemplateLoc(),
8863 TemplateParams->getRAngleLoc()))
8864 << SourceRange(LAngleLoc, RAngleLoc);
8865 } else {
8866 assert(TUK == TagUseKind::Friend &&
8867 "should have a 'template<>' for this decl");
8868 }
8869
8870 // Check that the specialization uses the same tag kind as the
8871 // original template.
8873 assert(Kind != TagTypeKind::Enum &&
8874 "Invalid enum tag in class template spec!");
8875 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8876 TUK == TagUseKind::Definition, KWLoc,
8877 ClassTemplate->getIdentifier())) {
8878 Diag(KWLoc, diag::err_use_with_wrong_tag)
8879 << ClassTemplate
8881 ClassTemplate->getTemplatedDecl()->getKindName());
8882 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8883 diag::note_previous_use);
8884 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8885 }
8886
8887 // Translate the parser's template argument list in our AST format.
8888 TemplateArgumentListInfo TemplateArgs =
8889 makeTemplateArgumentListInfo(*this, TemplateId);
8890
8891 // Check for unexpanded parameter packs in any of the template arguments.
8892 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8893 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8894 isPartialSpecialization
8897 return true;
8898
8899 // Check that the template argument list is well-formed for this
8900 // template.
8902 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8903 /*DefaultArgs=*/{},
8904 /*PartialTemplateArgs=*/false, CTAI,
8905 /*UpdateArgsWithConversions=*/true))
8906 return true;
8907
8908 // Find the class template (partial) specialization declaration that
8909 // corresponds to these arguments.
8910 if (isPartialSpecialization) {
8912 TemplateArgs.size(),
8913 CTAI.CanonicalConverted))
8914 return true;
8915
8916 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8917 // also do it during instantiation.
8918 if (!Name.isDependent() &&
8919 !TemplateSpecializationType::anyDependentTemplateArguments(
8920 TemplateArgs, CTAI.CanonicalConverted)) {
8921 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8922 << ClassTemplate->getDeclName();
8923 isPartialSpecialization = false;
8924 Invalid = true;
8925 }
8926 }
8927
8928 void *InsertPos = nullptr;
8929 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8930
8931 if (isPartialSpecialization)
8932 PrevDecl = ClassTemplate->findPartialSpecialization(
8933 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8934 else
8935 PrevDecl =
8936 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8937
8939
8940 // Check whether we can declare a class template specialization in
8941 // the current scope.
8942 if (TUK != TagUseKind::Friend &&
8944 TemplateNameLoc,
8945 isPartialSpecialization))
8946 return true;
8947
8948 if (!isPartialSpecialization) {
8949 // Create a new class template specialization declaration node for
8950 // this explicit specialization or friend declaration.
8952 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8953 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8954 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8956 if (TemplateParameterLists.size() > 0) {
8957 Specialization->setTemplateParameterListsInfo(Context,
8958 TemplateParameterLists);
8959 }
8960
8961 if (!PrevDecl)
8962 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8963 } else {
8965 Context.getCanonicalTemplateSpecializationType(
8967 TemplateName(ClassTemplate->getCanonicalDecl()),
8968 CTAI.CanonicalConverted));
8969 if (Context.hasSameType(
8970 CanonType,
8971 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8972 (!Context.getLangOpts().CPlusPlus20 ||
8973 !TemplateParams->hasAssociatedConstraints())) {
8974 // C++ [temp.class.spec]p9b3:
8975 //
8976 // -- The argument list of the specialization shall not be identical
8977 // to the implicit argument list of the primary template.
8978 //
8979 // This rule has since been removed, because it's redundant given DR1495,
8980 // but we keep it because it produces better diagnostics and recovery.
8981 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8982 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8983 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8984 return CheckClassTemplate(
8985 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8986 TemplateNameLoc, Attr, TemplateParams, AS_none,
8987 /*ModulePrivateLoc=*/SourceLocation(),
8988 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8989 TemplateParameterLists.data(), isMemberSpecialization);
8990 }
8991
8992 // Create a new class template partial specialization declaration node.
8994 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8997 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8998 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8999 Partial->setTemplateArgsAsWritten(TemplateArgs);
9000 SetNestedNameSpecifier(*this, Partial, SS);
9001 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9003 Context, TemplateParameterLists.drop_back(1));
9004 }
9005
9006 if (!PrevPartial)
9007 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9008 Specialization = Partial;
9009
9010 // If we are providing an explicit specialization of a member class
9011 // template specialization, make a note of that.
9012 if (isMemberSpecialization)
9013 Partial->setMemberSpecialization();
9014
9016 }
9017
9018 // C++ [temp.expl.spec]p6:
9019 // If a template, a member template or the member of a class template is
9020 // explicitly specialized then that specialization shall be declared
9021 // before the first use of that specialization that would cause an implicit
9022 // instantiation to take place, in every translation unit in which such a
9023 // use occurs; no diagnostic is required.
9024 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9025 bool Okay = false;
9026 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9027 // Is there any previous explicit specialization declaration?
9029 Okay = true;
9030 break;
9031 }
9032 }
9033
9034 if (!Okay) {
9035 SourceRange Range(TemplateNameLoc, RAngleLoc);
9036 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9037 << Context.getCanonicalTagType(Specialization) << Range;
9038
9039 Diag(PrevDecl->getPointOfInstantiation(),
9040 diag::note_instantiation_required_here)
9041 << (PrevDecl->getTemplateSpecializationKind()
9043 return true;
9044 }
9045 }
9046
9047 // If this is not a friend, note that this is an explicit specialization.
9048 if (TUK != TagUseKind::Friend)
9049 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9050
9051 // Check that this isn't a redefinition of this specialization.
9052 if (TUK == TagUseKind::Definition) {
9053 RecordDecl *Def = Specialization->getDefinition();
9054 NamedDecl *Hidden = nullptr;
9055 bool HiddenDefVisible = false;
9056 if (Def && SkipBody &&
9057 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9058 SkipBody->ShouldSkip = true;
9059 SkipBody->Previous = Def;
9060 if (!HiddenDefVisible && Hidden)
9062 } else if (Def) {
9063 SourceRange Range(TemplateNameLoc, RAngleLoc);
9064 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9065 Diag(Def->getLocation(), diag::note_previous_definition);
9066 Specialization->setInvalidDecl();
9067 return true;
9068 }
9069 }
9070
9073
9074 // Add alignment attributes if necessary; these attributes are checked when
9075 // the ASTContext lays out the structure.
9076 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9077 if (LangOpts.HLSL)
9078 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9081 }
9082
9083 if (ModulePrivateLoc.isValid())
9084 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9085 << (isPartialSpecialization? 1 : 0)
9086 << FixItHint::CreateRemoval(ModulePrivateLoc);
9087
9088 // C++ [temp.expl.spec]p9:
9089 // A template explicit specialization is in the scope of the
9090 // namespace in which the template was defined.
9091 //
9092 // We actually implement this paragraph where we set the semantic
9093 // context (in the creation of the ClassTemplateSpecializationDecl),
9094 // but we also maintain the lexical context where the actual
9095 // definition occurs.
9096 Specialization->setLexicalDeclContext(CurContext);
9097
9098 // We may be starting the definition of this specialization.
9099 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9100 Specialization->startDefinition();
9101
9102 if (TUK == TagUseKind::Friend) {
9103 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9104 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9105 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9107 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9108 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9109
9110 // Build the fully-sugared type for this class template
9111 // specialization as the user wrote in the specialization
9112 // itself. This means that we'll pretty-print the type retrieved
9113 // from the specialization's declaration the way that the user
9114 // actually wrote the specialization, rather than formatting the
9115 // name based on the "canonical" representation used to store the
9116 // template arguments in the specialization.
9118 TemplateNameLoc,
9119 WrittenTy,
9120 /*FIXME:*/KWLoc);
9121 Friend->setAccess(AS_public);
9122 CurContext->addDecl(Friend);
9123 } else {
9124 // Add the specialization into its lexical context, so that it can
9125 // be seen when iterating through the list of declarations in that
9126 // context. However, specializations are not found by name lookup.
9127 CurContext->addDecl(Specialization);
9128 }
9129
9130 if (SkipBody && SkipBody->ShouldSkip)
9131 return SkipBody->Previous;
9132
9133 Specialization->setInvalidDecl(Invalid);
9135 return Specialization;
9136}
9137
9139 MultiTemplateParamsArg TemplateParameterLists,
9140 Declarator &D) {
9141 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9142 ActOnDocumentableDecl(NewDecl);
9143 return NewDecl;
9144}
9145
9147 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9148 const IdentifierInfo *Name, SourceLocation NameLoc) {
9149 DeclContext *DC = CurContext;
9150
9151 if (!DC->getRedeclContext()->isFileContext()) {
9152 Diag(NameLoc,
9153 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9154 return nullptr;
9155 }
9156
9157 if (TemplateParameterLists.size() > 1) {
9158 Diag(NameLoc, diag::err_concept_extra_headers);
9159 return nullptr;
9160 }
9161
9162 TemplateParameterList *Params = TemplateParameterLists.front();
9163
9164 if (Params->size() == 0) {
9165 Diag(NameLoc, diag::err_concept_no_parameters);
9166 return nullptr;
9167 }
9168
9169 // Ensure that the parameter pack, if present, is the last parameter in the
9170 // template.
9171 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9172 ParamEnd = Params->end();
9173 ParamIt != ParamEnd; ++ParamIt) {
9174 Decl const *Param = *ParamIt;
9175 if (Param->isParameterPack()) {
9176 if (++ParamIt == ParamEnd)
9177 break;
9178 Diag(Param->getLocation(),
9179 diag::err_template_param_pack_must_be_last_template_parameter);
9180 return nullptr;
9181 }
9182 }
9183
9184 ConceptDecl *NewDecl =
9185 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9186
9187 if (NewDecl->hasAssociatedConstraints()) {
9188 // C++2a [temp.concept]p4:
9189 // A concept shall not have associated constraints.
9190 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9191 NewDecl->setInvalidDecl();
9192 }
9193
9194 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9195 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9197 LookupName(Previous, S);
9198 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9199 /*AllowInlineNamespace*/ false);
9200
9201 // We cannot properly handle redeclarations until we parse the constraint
9202 // expression, so only inject the name if we are sure we are not redeclaring a
9203 // symbol
9204 if (Previous.empty())
9205 PushOnScopeChains(NewDecl, S, true);
9206
9207 return NewDecl;
9208}
9209
9211 bool Found = false;
9212 LookupResult::Filter F = R.makeFilter();
9213 while (F.hasNext()) {
9214 NamedDecl *D = F.next();
9215 if (D == C) {
9216 F.erase();
9217 Found = true;
9218 break;
9219 }
9220 }
9221 F.done();
9222 return Found;
9223}
9224
9227 Expr *ConstraintExpr,
9228 const ParsedAttributesView &Attrs) {
9229 assert(!C->hasDefinition() && "Concept already defined");
9230 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9231 C->setInvalidDecl();
9232 return nullptr;
9233 }
9234 C->setDefinition(ConstraintExpr);
9235 ProcessDeclAttributeList(S, C, Attrs);
9236
9237 // Check for conflicting previous declaration.
9238 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9239 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9241 LookupName(Previous, S);
9242 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9243 /*AllowInlineNamespace*/ false);
9244 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9245 bool AddToScope = true;
9246 CheckConceptRedefinition(C, Previous, AddToScope);
9247
9249 if (!WasAlreadyAdded && AddToScope)
9250 PushOnScopeChains(C, S);
9251
9252 return C;
9253}
9254
9256 LookupResult &Previous, bool &AddToScope) {
9257 AddToScope = true;
9258
9259 if (Previous.empty())
9260 return;
9261
9262 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9263 if (!OldConcept) {
9264 auto *Old = Previous.getRepresentativeDecl();
9265 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9266 << NewDecl->getDeclName();
9267 notePreviousDefinition(Old, NewDecl->getLocation());
9268 AddToScope = false;
9269 return;
9270 }
9271 // Check if we can merge with a concept declaration.
9272 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9273 if (!IsSame) {
9274 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9275 << NewDecl->getDeclName();
9276 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9277 AddToScope = false;
9278 return;
9279 }
9280 if (hasReachableDefinition(OldConcept) &&
9281 IsRedefinitionInModule(NewDecl, OldConcept)) {
9282 Diag(NewDecl->getLocation(), diag::err_redefinition)
9283 << NewDecl->getDeclName();
9284 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9285 AddToScope = false;
9286 return;
9287 }
9288 if (!Previous.isSingleResult()) {
9289 // FIXME: we should produce an error in case of ambig and failed lookups.
9290 // Other decls (e.g. namespaces) also have this shortcoming.
9291 return;
9292 }
9293 // We unwrap canonical decl late to check for module visibility.
9294 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9295}
9296
9298 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9299 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9300 Diag(Loc, diag::err_recursive_concept) << CE;
9301 Diag(CE->getLocation(), diag::note_declared_at);
9302 return true;
9303 }
9304 // Concept template parameters don't have a definition and can't
9305 // be defined recursively.
9306 return false;
9307}
9308
9309/// \brief Strips various properties off an implicit instantiation
9310/// that has just been explicitly specialized.
9311static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9312 if (MinGW || (isa<FunctionDecl>(D) &&
9313 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9314 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9315
9316 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9317 FD->setInlineSpecified(false);
9318}
9319
9320/// Create an ExplicitInstantiationDecl to record source-location info for an
9321/// explicit template instantiation statement, and add it to \p CurContext.
9322///
9323/// For class templates / nested classes, the caller should build a
9324/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9325/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9326///
9327/// For function / variable templates, the caller should pass TypeAsWritten for
9328/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9330 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9331 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9332 NestedNameSpecifierLoc QualifierLoc,
9333 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9334 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9336 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9337 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9338 Context.addExplicitInstantiationDecl(Spec, EID);
9339 CurContext->addDecl(EID);
9340}
9341
9342/// Compute the diagnostic location for an explicit instantiation
9343// declaration or definition.
9344static SourceLocation
9346 SourceLocation PointOfInstantiation) {
9347 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9348 if (EID->getTemplateSpecializationKind() ==
9350 return EID->getTemplateLoc();
9351
9352 // Explicit instantiations following a specialization have no effect and
9353 // hence no PointOfInstantiation. In that case, walk decl backwards
9354 // until a valid name loc is found.
9355 SourceLocation PrevDiagLoc = PointOfInstantiation;
9356 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9357 Prev = Prev->getPreviousDecl()) {
9358 PrevDiagLoc = Prev->getLocation();
9359 }
9360 assert(PrevDiagLoc.isValid() &&
9361 "Explicit instantiation without point of instantiation?");
9362 return PrevDiagLoc;
9363}
9364
9365bool
9368 NamedDecl *PrevDecl,
9370 SourceLocation PrevPointOfInstantiation,
9371 bool &HasNoEffect) {
9372 HasNoEffect = false;
9373
9374 switch (NewTSK) {
9375 case TSK_Undeclared:
9377 assert(
9378 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9379 "previous declaration must be implicit!");
9380 return false;
9381
9383 switch (PrevTSK) {
9384 case TSK_Undeclared:
9386 // Okay, we're just specializing something that is either already
9387 // explicitly specialized or has merely been mentioned without any
9388 // instantiation.
9389 return false;
9390
9392 if (PrevPointOfInstantiation.isInvalid()) {
9393 // The declaration itself has not actually been instantiated, so it is
9394 // still okay to specialize it.
9396 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9397 return false;
9398 }
9399 // Fall through
9400 [[fallthrough]];
9401
9404 assert((PrevTSK == TSK_ImplicitInstantiation ||
9405 PrevPointOfInstantiation.isValid()) &&
9406 "Explicit instantiation without point of instantiation?");
9407
9408 // C++ [temp.expl.spec]p6:
9409 // If a template, a member template or the member of a class template
9410 // is explicitly specialized then that specialization shall be declared
9411 // before the first use of that specialization that would cause an
9412 // implicit instantiation to take place, in every translation unit in
9413 // which such a use occurs; no diagnostic is required.
9414 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9415 // Is there any previous explicit specialization declaration?
9417 return false;
9418 }
9419
9420 Diag(NewLoc, diag::err_specialization_after_instantiation)
9421 << PrevDecl;
9422 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9423 << (PrevTSK != TSK_ImplicitInstantiation);
9424
9425 return true;
9426 }
9427 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9428
9430 switch (PrevTSK) {
9432 // This explicit instantiation declaration is redundant (that's okay).
9433 HasNoEffect = true;
9434 return false;
9435
9436 case TSK_Undeclared:
9438 // We're explicitly instantiating something that may have already been
9439 // implicitly instantiated; that's fine.
9440 return false;
9441
9443 // C++0x [temp.explicit]p4:
9444 // For a given set of template parameters, if an explicit instantiation
9445 // of a template appears after a declaration of an explicit
9446 // specialization for that template, the explicit instantiation has no
9447 // effect.
9448 HasNoEffect = true;
9449 return false;
9450
9452 // C++0x [temp.explicit]p10:
9453 // If an entity is the subject of both an explicit instantiation
9454 // declaration and an explicit instantiation definition in the same
9455 // translation unit, the definition shall follow the declaration.
9456 Diag(NewLoc,
9457 diag::err_explicit_instantiation_declaration_after_definition);
9458
9459 // Explicit instantiations following a specialization have no effect and
9460 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9461 // until a valid name loc is found.
9462 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9463 diag::note_explicit_instantiation_definition_here);
9464 HasNoEffect = true;
9465 return false;
9466 }
9467 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9468
9470 switch (PrevTSK) {
9471 case TSK_Undeclared:
9473 // We're explicitly instantiating something that may have already been
9474 // implicitly instantiated; that's fine.
9475 return false;
9476
9478 // C++ DR 259, C++0x [temp.explicit]p4:
9479 // For a given set of template parameters, if an explicit
9480 // instantiation of a template appears after a declaration of
9481 // an explicit specialization for that template, the explicit
9482 // instantiation has no effect.
9483 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9484 << PrevDecl;
9485 Diag(PrevDecl->getLocation(),
9486 diag::note_previous_template_specialization);
9487 HasNoEffect = true;
9488 return false;
9489
9491 // We're explicitly instantiating a definition for something for which we
9492 // were previously asked to suppress instantiations. That's fine.
9493
9494 // C++0x [temp.explicit]p4:
9495 // For a given set of template parameters, if an explicit instantiation
9496 // of a template appears after a declaration of an explicit
9497 // specialization for that template, the explicit instantiation has no
9498 // effect.
9499 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9500 // Is there any previous explicit specialization declaration?
9502 HasNoEffect = true;
9503 break;
9504 }
9505 }
9506
9507 return false;
9508
9510 // C++0x [temp.spec]p5:
9511 // For a given template and a given set of template-arguments,
9512 // - an explicit instantiation definition shall appear at most once
9513 // in a program,
9514
9515 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9516 Diag(NewLoc, (getLangOpts().MSVCCompat)
9517 ? diag::ext_explicit_instantiation_duplicate
9518 : diag::err_explicit_instantiation_duplicate)
9519 << PrevDecl;
9520 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9521 diag::note_previous_explicit_instantiation);
9522 HasNoEffect = true;
9523 return false;
9524 }
9525 }
9526
9527 llvm_unreachable("Missing specialization/instantiation case?");
9528}
9529
9531 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9533 // Remove anything from Previous that isn't a function template in
9534 // the correct context.
9535 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9536 LookupResult::Filter F = Previous.makeFilter();
9537 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9538 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9539 while (F.hasNext()) {
9540 NamedDecl *D = F.next()->getUnderlyingDecl();
9541 if (!isa<FunctionTemplateDecl>(D)) {
9542 F.erase();
9543 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9544 continue;
9545 }
9546
9547 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9549 F.erase();
9550 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9551 continue;
9552 }
9553 }
9554 F.done();
9555
9556 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9557 if (Previous.empty()) {
9558 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9559 << IsFriend;
9560 for (auto &P : DiscardedCandidates)
9561 Diag(P.second->getLocation(),
9562 diag::note_dependent_function_template_spec_discard_reason)
9563 << P.first << IsFriend;
9564 return true;
9565 }
9566
9568 ExplicitTemplateArgs);
9569 return false;
9570}
9571
9573 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9574 LookupResult &Previous, bool QualifiedFriend) {
9575 // The set of function template specializations that could match this
9576 // explicit function template specialization.
9577 UnresolvedSet<8> Candidates;
9578 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9579 /*ForTakingAddress=*/false);
9580
9581 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9582 ConvertedTemplateArgs;
9583
9584 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9586 I != E; ++I) {
9587 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9588 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9589 // Only consider templates found within the same semantic lookup scope as
9590 // FD.
9591 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9593 continue;
9594
9595 QualType FT = FD->getType();
9596 // C++11 [dcl.constexpr]p8:
9597 // A constexpr specifier for a non-static member function that is not
9598 // a constructor declares that member function to be const.
9599 //
9600 // When matching a constexpr member function template specialization
9601 // against the primary template, we don't yet know whether the
9602 // specialization has an implicit 'const' (because we don't know whether
9603 // it will be a static member function until we know which template it
9604 // specializes). This rule was removed in C++14.
9605 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9606 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9608 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9609 if (OldMD && OldMD->isConst()) {
9610 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9612 EPI.TypeQuals.addConst();
9613 FT = Context.getFunctionType(FPT->getReturnType(),
9614 FPT->getParamTypes(), EPI);
9615 }
9616 }
9617
9619 if (ExplicitTemplateArgs)
9620 Args = *ExplicitTemplateArgs;
9621
9622 // C++ [temp.expl.spec]p11:
9623 // A trailing template-argument can be left unspecified in the
9624 // template-id naming an explicit function template specialization
9625 // provided it can be deduced from the function argument type.
9626 // Perform template argument deduction to determine whether we may be
9627 // specializing this template.
9628 // FIXME: It is somewhat wasteful to build
9629 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9630 FunctionDecl *Specialization = nullptr;
9632 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9633 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9635 // Template argument deduction failed; record why it failed, so
9636 // that we can provide nifty diagnostics.
9637 FailedCandidates.addCandidate().set(
9638 I.getPair(), FunTmpl->getTemplatedDecl(),
9639 MakeDeductionFailureInfo(Context, TDK, Info));
9640 (void)TDK;
9641 continue;
9642 }
9643
9644 // Target attributes are part of the cuda function signature, so
9645 // the deduced template's cuda target must match that of the
9646 // specialization. Given that C++ template deduction does not
9647 // take target attributes into account, we reject candidates
9648 // here that have a different target.
9649 if (LangOpts.CUDA &&
9650 CUDA().IdentifyTarget(Specialization,
9651 /* IgnoreImplicitHDAttr = */ true) !=
9652 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9653 FailedCandidates.addCandidate().set(
9654 I.getPair(), FunTmpl->getTemplatedDecl(),
9657 continue;
9658 }
9659
9660 // Record this candidate.
9661 if (ExplicitTemplateArgs)
9662 ConvertedTemplateArgs[Specialization] = std::move(Args);
9663 Candidates.addDecl(Specialization, I.getAccess());
9664 }
9665 }
9666
9667 // For a qualified friend declaration (with no explicit marker to indicate
9668 // that a template specialization was intended), note all (template and
9669 // non-template) candidates.
9670 if (QualifiedFriend && Candidates.empty()) {
9671 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9672 << FD->getDeclName() << FDLookupContext;
9673 // FIXME: We should form a single candidate list and diagnose all
9674 // candidates at once, to get proper sorting and limiting.
9675 for (auto *OldND : Previous) {
9676 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9677 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9678 }
9679 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9680 return true;
9681 }
9682
9683 // Find the most specialized function template.
9685 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9686 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9687 PDiag(diag::err_function_template_spec_ambiguous)
9688 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9689 PDiag(diag::note_function_template_spec_matched));
9690
9691 if (Result == Candidates.end())
9692 return true;
9693
9694 // Ignore access information; it doesn't figure into redeclaration checking.
9696
9697 if (const auto *PT = Specialization->getPrimaryTemplate();
9698 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9699 auto Message = DSA->getMessage();
9700 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9701 << PT << !Message.empty() << Message;
9702 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9703 }
9704
9705 // C++23 [except.spec]p13:
9706 // An exception specification is considered to be needed when:
9707 // - [...]
9708 // - the exception specification is compared to that of another declaration
9709 // (e.g., an explicit specialization or an overriding virtual function);
9710 // - [...]
9711 //
9712 // The exception specification of a defaulted function is evaluated as
9713 // described above only when needed; similarly, the noexcept-specifier of a
9714 // specialization of a function template or member function of a class
9715 // template is instantiated only when needed.
9716 //
9717 // The standard doesn't specify what the "comparison with another declaration"
9718 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9719 // not state which properties of an explicit specialization must match the
9720 // primary template.
9721 //
9722 // We assume that an explicit specialization must correspond with (per
9723 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9724 // the declaration produced by substitution into the function template.
9725 //
9726 // Since the determination whether two function declarations correspond does
9727 // not consider exception specification, we only need to instantiate it once
9728 // we determine the primary template when comparing types per
9729 // [basic.link]p11.1.
9730 auto *SpecializationFPT =
9731 Specialization->getType()->castAs<FunctionProtoType>();
9732 // If the function has a dependent exception specification, resolve it after
9733 // we have selected the primary template so we can check whether it matches.
9734 if (getLangOpts().CPlusPlus17 &&
9735 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9736 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9737 return true;
9738
9740 = Specialization->getTemplateSpecializationInfo();
9741 assert(SpecInfo && "Function template specialization info missing?");
9742
9743 // Note: do not overwrite location info if previous template
9744 // specialization kind was explicit.
9746 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9747 Specialization->setLocation(FD->getLocation());
9748 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9749 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9750 // function can differ from the template declaration with respect to
9751 // the constexpr specifier.
9752 // FIXME: We need an update record for this AST mutation.
9753 // FIXME: What if there are multiple such prior declarations (for instance,
9754 // from different modules)?
9755 Specialization->setConstexprKind(FD->getConstexprKind());
9756 }
9757
9758 // FIXME: Check if the prior specialization has a point of instantiation.
9759 // If so, we have run afoul of .
9760
9761 // If this is a friend declaration, then we're not really declaring
9762 // an explicit specialization.
9763 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9764
9765 // Check the scope of this explicit specialization.
9766 if (!isFriend &&
9768 Specialization->getPrimaryTemplate(),
9770 false))
9771 return true;
9772
9773 // C++ [temp.expl.spec]p6:
9774 // If a template, a member template or the member of a class template is
9775 // explicitly specialized then that specialization shall be declared
9776 // before the first use of that specialization that would cause an implicit
9777 // instantiation to take place, in every translation unit in which such a
9778 // use occurs; no diagnostic is required.
9779 bool HasNoEffect = false;
9780 if (!isFriend &&
9785 SpecInfo->getPointOfInstantiation(),
9786 HasNoEffect))
9787 return true;
9788
9789 // Mark the prior declaration as an explicit specialization, so that later
9790 // clients know that this is an explicit specialization.
9791 // A dependent friend specialization which has a definition should be treated
9792 // as explicit specialization, despite being invalid.
9793 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9794 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9795 // Since explicit specializations do not inherit '=delete' from their
9796 // primary function template - check if the 'specialization' that was
9797 // implicitly generated (during template argument deduction for partial
9798 // ordering) from the most specialized of all the function templates that
9799 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9800 // first check that it was implicitly generated during template argument
9801 // deduction by making sure it wasn't referenced, and then reset the deleted
9802 // flag to not-deleted, so that we can inherit that information from 'FD'.
9803 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9804 !Specialization->getCanonicalDecl()->isReferenced()) {
9805 // FIXME: This assert will not hold in the presence of modules.
9806 assert(
9807 Specialization->getCanonicalDecl() == Specialization &&
9808 "This must be the only existing declaration of this specialization");
9809 // FIXME: We need an update record for this AST mutation.
9810 Specialization->setDeletedAsWritten(false);
9811 }
9812 // FIXME: We need an update record for this AST mutation.
9815 }
9816
9817 // Turn the given function declaration into a function template
9818 // specialization, with the template arguments from the previous
9819 // specialization.
9820 // Take copies of (semantic and syntactic) template argument lists.
9822 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9823 FD->setFunctionTemplateSpecialization(
9824 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9826 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9827
9828 // A function template specialization inherits the target attributes
9829 // of its template. (We require the attributes explicitly in the
9830 // code to match, but a template may have implicit attributes by
9831 // virtue e.g. of being constexpr, and it passes these implicit
9832 // attributes on to its specializations.)
9833 if (LangOpts.CUDA)
9834 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9835
9836 // The "previous declaration" for this function template specialization is
9837 // the prior function template specialization.
9838 Previous.clear();
9839 Previous.addDecl(Specialization);
9840 return false;
9841}
9842
9843bool
9845 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9846 "Only for non-template members");
9847
9848 // Try to find the member we are instantiating.
9849 NamedDecl *FoundInstantiation = nullptr;
9850 NamedDecl *Instantiation = nullptr;
9851 NamedDecl *InstantiatedFrom = nullptr;
9852 MemberSpecializationInfo *MSInfo = nullptr;
9853
9854 if (Previous.empty()) {
9855 // Nowhere to look anyway.
9856 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9857 UnresolvedSet<8> Candidates;
9858 for (NamedDecl *Candidate : Previous) {
9859 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9860 // Ignore any candidates that aren't member functions.
9861 if (!Method)
9862 continue;
9863
9864 QualType Adjusted = Function->getType();
9865 if (!hasExplicitCallingConv(Adjusted))
9866 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9867 // Ignore any candidates with the wrong type.
9868 // This doesn't handle deduced return types, but both function
9869 // declarations should be undeduced at this point.
9870 // FIXME: The exception specification should probably be ignored when
9871 // comparing the types.
9872 if (!Context.hasSameType(Adjusted, Method->getType()))
9873 continue;
9874
9875 // Ignore any candidates with unsatisfied constraints.
9876 if (ConstraintSatisfaction Satisfaction;
9877 Method->getTrailingRequiresClause() &&
9878 (CheckFunctionConstraints(Method, Satisfaction,
9879 /*UsageLoc=*/Member->getLocation(),
9880 /*ForOverloadResolution=*/true) ||
9881 !Satisfaction.IsSatisfied))
9882 continue;
9883
9884 Candidates.addDecl(Candidate);
9885 }
9886
9887 // If we have no viable candidates left after filtering, we are done.
9888 if (Candidates.empty())
9889 return false;
9890
9891 // Find the function that is more constrained than every other function it
9892 // has been compared to.
9893 UnresolvedSetIterator Best = Candidates.begin();
9894 CXXMethodDecl *BestMethod = nullptr;
9895 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9896 I != E; ++I) {
9897 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9898 if (I == Best ||
9899 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9900 Best = I;
9901 BestMethod = Method;
9902 }
9903 }
9904
9905 FoundInstantiation = *Best;
9906 Instantiation = BestMethod;
9907 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9908 MSInfo = BestMethod->getMemberSpecializationInfo();
9909
9910 // Make sure the best candidate is more constrained than all of the others.
9911 bool Ambiguous = false;
9912 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9913 I != E; ++I) {
9914 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9915 if (I != Best &&
9916 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9917 Ambiguous = true;
9918 break;
9919 }
9920 }
9921
9922 if (Ambiguous) {
9923 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9924 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9925 for (NamedDecl *Candidate : Candidates) {
9926 Candidate = Candidate->getUnderlyingDecl();
9927 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9928 << Candidate;
9929 }
9930 return true;
9931 }
9932 } else if (isa<VarDecl>(Member)) {
9933 VarDecl *PrevVar;
9934 if (Previous.isSingleResult() &&
9935 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9936 if (PrevVar->isStaticDataMember()) {
9937 FoundInstantiation = Previous.getRepresentativeDecl();
9938 Instantiation = PrevVar;
9939 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9940 MSInfo = PrevVar->getMemberSpecializationInfo();
9941 }
9942 } else if (isa<RecordDecl>(Member)) {
9943 CXXRecordDecl *PrevRecord;
9944 if (Previous.isSingleResult() &&
9945 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9946 FoundInstantiation = Previous.getRepresentativeDecl();
9947 Instantiation = PrevRecord;
9948 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9949 MSInfo = PrevRecord->getMemberSpecializationInfo();
9950 }
9951 } else if (isa<EnumDecl>(Member)) {
9952 EnumDecl *PrevEnum;
9953 if (Previous.isSingleResult() &&
9954 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9955 FoundInstantiation = Previous.getRepresentativeDecl();
9956 Instantiation = PrevEnum;
9957 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9958 MSInfo = PrevEnum->getMemberSpecializationInfo();
9959 }
9960 }
9961
9962 if (!Instantiation) {
9963 // There is no previous declaration that matches. Since member
9964 // specializations are always out-of-line, the caller will complain about
9965 // this mismatch later.
9966 return false;
9967 }
9968
9969 // A member specialization in a friend declaration isn't really declaring
9970 // an explicit specialization, just identifying a specific (possibly implicit)
9971 // specialization. Don't change the template specialization kind.
9972 //
9973 // FIXME: Is this really valid? Other compilers reject.
9974 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9975 // Preserve instantiation information.
9976 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9977 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9978 cast<CXXMethodDecl>(InstantiatedFrom),
9980 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9981 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9982 cast<CXXRecordDecl>(InstantiatedFrom),
9984 }
9985
9986 Previous.clear();
9987 Previous.addDecl(FoundInstantiation);
9988 return false;
9989 }
9990
9991 // Make sure that this is a specialization of a member.
9992 if (!InstantiatedFrom) {
9993 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9994 << Member;
9995 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9996 return true;
9997 }
9998
9999 // C++ [temp.expl.spec]p6:
10000 // If a template, a member template or the member of a class template is
10001 // explicitly specialized then that specialization shall be declared
10002 // before the first use of that specialization that would cause an implicit
10003 // instantiation to take place, in every translation unit in which such a
10004 // use occurs; no diagnostic is required.
10005 assert(MSInfo && "Member specialization info missing?");
10006
10007 bool HasNoEffect = false;
10010 Instantiation,
10012 MSInfo->getPointOfInstantiation(),
10013 HasNoEffect))
10014 return true;
10015
10016 // Check the scope of this explicit specialization.
10018 InstantiatedFrom,
10019 Instantiation, Member->getLocation(),
10020 false))
10021 return true;
10022
10023 // Note that this member specialization is an "instantiation of" the
10024 // corresponding member of the original template.
10025 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10026 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10027 if (InstantiationFunction->getTemplateSpecializationKind() ==
10029 // Explicit specializations of member functions of class templates do not
10030 // inherit '=delete' from the member function they are specializing.
10031 if (InstantiationFunction->isDeleted()) {
10032 // FIXME: This assert will not hold in the presence of modules.
10033 assert(InstantiationFunction->getCanonicalDecl() ==
10034 InstantiationFunction);
10035 // FIXME: We need an update record for this AST mutation.
10036 InstantiationFunction->setDeletedAsWritten(false);
10037 }
10038 }
10039
10040 MemberFunction->setInstantiationOfMemberFunction(
10042 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10043 MemberVar->setInstantiationOfStaticDataMember(
10044 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10045 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10046 MemberClass->setInstantiationOfMemberClass(
10048 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10049 MemberEnum->setInstantiationOfMemberEnum(
10050 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10051 } else {
10052 llvm_unreachable("unknown member specialization kind");
10053 }
10054
10055 // Save the caller the trouble of having to figure out which declaration
10056 // this specialization matches.
10057 Previous.clear();
10058 Previous.addDecl(FoundInstantiation);
10059 return false;
10060}
10061
10062/// Complete the explicit specialization of a member of a class template by
10063/// updating the instantiated member to be marked as an explicit specialization.
10064///
10065/// \param OrigD The member declaration instantiated from the template.
10066/// \param Loc The location of the explicit specialization of the member.
10067template<typename DeclT>
10068static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10069 SourceLocation Loc) {
10070 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10071 return;
10072
10073 // FIXME: Inform AST mutation listeners of this AST mutation.
10074 // FIXME: If there are multiple in-class declarations of the member (from
10075 // multiple modules, or a declaration and later definition of a member type),
10076 // should we update all of them?
10077 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10078 OrigD->setLocation(Loc);
10079}
10080
10083 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10084 if (Instantiation == Member)
10085 return;
10086
10087 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10088 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10089 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10090 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10091 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10092 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10093 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10094 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10095 else
10096 llvm_unreachable("unknown member specialization kind");
10097}
10098
10099/// Check the scope of an explicit instantiation.
10100///
10101/// \returns true if a serious error occurs, false otherwise.
10103 SourceLocation InstLoc,
10104 bool WasQualifiedName) {
10106 DeclContext *CurContext = S.CurContext->getRedeclContext();
10107
10108 if (CurContext->isRecord()) {
10109 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10110 << D;
10111 return true;
10112 }
10113
10114 // C++11 [temp.explicit]p3:
10115 // An explicit instantiation shall appear in an enclosing namespace of its
10116 // template. If the name declared in the explicit instantiation is an
10117 // unqualified name, the explicit instantiation shall appear in the
10118 // namespace where its template is declared or, if that namespace is inline
10119 // (7.3.1), any namespace from its enclosing namespace set.
10120 //
10121 // This is DR275, which we do not retroactively apply to C++98/03.
10122 if (WasQualifiedName) {
10123 if (CurContext->Encloses(OrigContext))
10124 return false;
10125 } else {
10126 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10127 return false;
10128 }
10129
10130 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10131 if (WasQualifiedName)
10132 S.Diag(InstLoc,
10133 S.getLangOpts().CPlusPlus11?
10134 diag::err_explicit_instantiation_out_of_scope :
10135 diag::warn_explicit_instantiation_out_of_scope_0x)
10136 << D << NS;
10137 else
10138 S.Diag(InstLoc,
10139 S.getLangOpts().CPlusPlus11?
10140 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10141 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10142 << D << NS;
10143 } else
10144 S.Diag(InstLoc,
10145 S.getLangOpts().CPlusPlus11?
10146 diag::err_explicit_instantiation_must_be_global :
10147 diag::warn_explicit_instantiation_must_be_global_0x)
10148 << D;
10149 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10150 return false;
10151}
10152
10153/// Common checks for whether an explicit instantiation of \p D is valid.
10155 SourceLocation InstLoc,
10156 bool WasQualifiedName,
10158 // C++ [temp.explicit]p13:
10159 // An explicit instantiation declaration shall not name a specialization of
10160 // a template with internal linkage.
10163 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10164 return true;
10165 }
10166
10167 // C++11 [temp.explicit]p3: [DR 275]
10168 // An explicit instantiation shall appear in an enclosing namespace of its
10169 // template.
10170 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10171 return true;
10172
10173 return false;
10174}
10175
10176/// Determine whether the given scope specifier has a template-id in it.
10178 // C++11 [temp.explicit]p3:
10179 // If the explicit instantiation is for a member function, a member class
10180 // or a static data member of a class template specialization, the name of
10181 // the class template specialization in the qualified-id for the member
10182 // name shall be a simple-template-id.
10183 //
10184 // C++98 has the same restriction, just worded differently.
10185 for (NestedNameSpecifier NNS = SS.getScopeRep();
10187 /**/) {
10188 const Type *T = NNS.getAsType();
10190 return true;
10191 NNS = T->getPrefix();
10192 }
10193 return false;
10194}
10195
10196/// Make a dllexport or dllimport attr on a class template specialization take
10197/// effect.
10200 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10201 assert(A && "dllExportImportClassTemplateSpecialization called "
10202 "on Def without dllexport or dllimport");
10203
10204 // We reject explicit instantiations in class scope, so there should
10205 // never be any delayed exported classes to worry about.
10206 assert(S.DelayedDllExportClasses.empty() &&
10207 "delayed exports present at explicit instantiation");
10209
10210 // Propagate attribute to base class templates.
10211 for (auto &B : Def->bases()) {
10212 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10213 B.getType()->getAsCXXRecordDecl()))
10215 }
10216
10218}
10219
10221 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10222 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10223 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10224 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10225 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10226 // Find the class template we're specializing
10227 TemplateName Name = TemplateD.get();
10228 TemplateDecl *TD = Name.getAsTemplateDecl();
10229 // Check that the specialization uses the same tag kind as the
10230 // original template.
10232 assert(Kind != TagTypeKind::Enum &&
10233 "Invalid enum tag in class template explicit instantiation!");
10234
10235 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10236
10237 if (!ClassTemplate) {
10238 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10239 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10240 Diag(TD->getLocation(), diag::note_previous_use);
10241 return true;
10242 }
10243
10244 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10245 Kind, /*isDefinition*/false, KWLoc,
10246 ClassTemplate->getIdentifier())) {
10247 Diag(KWLoc, diag::err_use_with_wrong_tag)
10248 << ClassTemplate
10250 ClassTemplate->getTemplatedDecl()->getKindName());
10251 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10252 diag::note_previous_use);
10253 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10254 }
10255
10256 // C++0x [temp.explicit]p2:
10257 // There are two forms of explicit instantiation: an explicit instantiation
10258 // definition and an explicit instantiation declaration. An explicit
10259 // instantiation declaration begins with the extern keyword. [...]
10260 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10263
10265 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10266 // Check for dllexport class template instantiation declarations,
10267 // except for MinGW mode.
10268 for (const ParsedAttr &AL : Attr) {
10269 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10270 Diag(ExternLoc,
10271 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10272 Diag(AL.getLoc(), diag::note_attribute);
10273 break;
10274 }
10275 }
10276
10277 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10278 Diag(ExternLoc,
10279 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10280 Diag(A->getLocation(), diag::note_attribute);
10281 }
10282 }
10283
10284 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10285 // instantiation declarations for most purposes.
10286 bool DLLImportExplicitInstantiationDef = false;
10288 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10289 // Check for dllimport class template instantiation definitions.
10290 bool DLLImport =
10291 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10292 for (const ParsedAttr &AL : Attr) {
10293 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10294 DLLImport = true;
10295 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10296 // dllexport trumps dllimport here.
10297 DLLImport = false;
10298 break;
10299 }
10300 }
10301 if (DLLImport) {
10303 DLLImportExplicitInstantiationDef = true;
10304 }
10305 }
10306
10307 // Translate the parser's template argument list in our AST format.
10308 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10309 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10310
10311 // Check that the template argument list is well-formed for this
10312 // template.
10314 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10315 /*DefaultArgs=*/{}, false, CTAI,
10316 /*UpdateArgsWithConversions=*/true,
10317 /*ConstraintsNotSatisfied=*/nullptr))
10318 return true;
10319
10320 // Find the class template specialization declaration that
10321 // corresponds to these arguments.
10322 void *InsertPos = nullptr;
10324 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10325
10326 TemplateSpecializationKind PrevDecl_TSK
10327 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10328
10329 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10330 Context.getTargetInfo().getTriple().isOSCygMing()) {
10331 // Check for dllexport class template instantiation definitions in MinGW
10332 // mode, if a previous declaration of the instantiation was seen.
10333 for (const ParsedAttr &AL : Attr) {
10334 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10335 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10336 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10337 } else {
10338 Diag(AL.getLoc(),
10339 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10340 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10341 }
10342 break;
10343 }
10344 }
10345 }
10346
10347 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10348 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10349 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10350 return AL.getKind() == ParsedAttr::AT_DLLExport;
10351 })) {
10352 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10353 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10354 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10355 }
10356 }
10357
10358 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10359 SS.isSet(), TSK))
10360 return true;
10361
10363
10364 bool HasNoEffect = false;
10365 if (PrevDecl) {
10366 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10367 PrevDecl, PrevDecl_TSK,
10368 PrevDecl->getPointOfInstantiation(),
10369 HasNoEffect))
10370 return PrevDecl;
10371
10372 // Even though HasNoEffect == true means that this explicit instantiation
10373 // has no effect on semantics, we go on to put its syntax in the AST.
10374
10375 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10376 PrevDecl_TSK == TSK_Undeclared) {
10377 // Since the only prior class template specialization with these
10378 // arguments was referenced but not declared, reuse that
10379 // declaration node as our own, updating the source location
10380 // for the template name to reflect our new declaration.
10381 // (Other source locations will be updated later.)
10382 Specialization = PrevDecl;
10383 Specialization->setLocation(TemplateNameLoc);
10384 PrevDecl = nullptr;
10385 }
10386
10387 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10388 DLLImportExplicitInstantiationDef) {
10389 // The new specialization might add a dllimport attribute.
10390 HasNoEffect = false;
10391 }
10392 }
10393
10394 if (!Specialization) {
10395 // Create a new class template specialization declaration node for
10396 // this explicit specialization.
10398 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10399 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10401
10402 // A MSInheritanceAttr attached to the previous declaration must be
10403 // propagated to the new node prior to instantiation.
10404 if (PrevDecl) {
10405 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10406 auto *Clone = A->clone(getASTContext());
10407 Clone->setInherited(true);
10408 Specialization->addAttr(Clone);
10409 Consumer.AssignInheritanceModel(Specialization);
10410 }
10411 }
10412
10413 if (!HasNoEffect && !PrevDecl) {
10414 // Insert the new specialization.
10415 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10416 }
10417 }
10418
10419 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10420
10421 // Set source locations for keywords.
10422 Specialization->setExternKeywordLoc(ExternLoc);
10423 Specialization->setTemplateKeywordLoc(TemplateLoc);
10424 Specialization->setBraceRange(SourceRange());
10425
10426 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10429
10430 // Add the explicit instantiation into its lexical context. However,
10431 // since explicit instantiations are never found by name lookup, we
10432 // just put it into the declaration context directly.
10433 Specialization->setLexicalDeclContext(CurContext);
10434 CurContext->addDecl(Specialization);
10435
10436 // Syntax is now OK, so return if it has no other effect on semantics.
10437 if (HasNoEffect) {
10438 // Set the template specialization kind.
10439 Specialization->setTemplateSpecializationKind(TSK);
10440
10442 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10443 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10444 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10445 Context.getCanonicalTagType(Specialization));
10447 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10448 TemplateNameLoc, TSI, TSK);
10449 return Specialization;
10450 }
10451
10452 // C++ [temp.explicit]p3:
10453 // A definition of a class template or class member template
10454 // shall be in scope at the point of the explicit instantiation of
10455 // the class template or class member template.
10456 //
10457 // This check comes when we actually try to perform the
10458 // instantiation.
10460 = cast_or_null<ClassTemplateSpecializationDecl>(
10461 Specialization->getDefinition());
10462 if (!Def)
10464 /*Complain=*/true,
10465 CTAI.StrictPackMatch);
10466 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10467 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10468 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10469 }
10470
10471 // Instantiate the members of this class template specialization.
10472 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10473 Specialization->getDefinition());
10474 if (Def) {
10476 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10477 // TSK_ExplicitInstantiationDefinition
10478 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10480 DLLImportExplicitInstantiationDef)) {
10481 // FIXME: Need to notify the ASTMutationListener that we did this.
10483
10484 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10485 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10486 // An explicit instantiation definition can add a dll attribute to a
10487 // template with a previous instantiation declaration. MinGW doesn't
10488 // allow this.
10489 auto *A = cast<InheritableAttr>(
10491 A->setInherited(true);
10492 Def->addAttr(A);
10494 }
10495 }
10496
10497 // Fix a TSK_ImplicitInstantiation followed by a
10498 // TSK_ExplicitInstantiationDefinition
10499 bool NewlyDLLExported =
10500 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10501 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10502 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10503 // An explicit instantiation definition can add a dll attribute to a
10504 // template with a previous implicit instantiation. MinGW doesn't allow
10505 // this. We limit clang to only adding dllexport, to avoid potentially
10506 // strange codegen behavior. For example, if we extend this conditional
10507 // to dllimport, and we have a source file calling a method on an
10508 // implicitly instantiated template class instance and then declaring a
10509 // dllimport explicit instantiation definition for the same template
10510 // class, the codegen for the method call will not respect the dllimport,
10511 // while it will with cl. The Def will already have the DLL attribute,
10512 // since the Def and Specialization will be the same in the case of
10513 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10514 // attribute to the Specialization; we just need to make it take effect.
10515 assert(Def == Specialization &&
10516 "Def and Specialization should match for implicit instantiation");
10518 }
10519
10520 // In MinGW mode, export the template instantiation if the declaration
10521 // was marked dllexport.
10522 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10523 Context.getTargetInfo().getTriple().isOSCygMing() &&
10524 PrevDecl->hasAttr<DLLExportAttr>()) {
10526 }
10527
10528 // Set the template specialization kind. Make sure it is set before
10529 // instantiating the members which will trigger ASTConsumer callbacks.
10530 Specialization->setTemplateSpecializationKind(TSK);
10531 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10532 } else {
10533
10534 // Set the template specialization kind.
10535 Specialization->setTemplateSpecializationKind(TSK);
10536 }
10537
10539 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10540 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10541 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10542 Context.getCanonicalTagType(Specialization));
10544 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10545 TemplateNameLoc, TSI, TSK);
10546 return Specialization;
10547}
10548
10551 SourceLocation TemplateLoc, unsigned TagSpec,
10552 SourceLocation KWLoc, CXXScopeSpec &SS,
10553 IdentifierInfo *Name, SourceLocation NameLoc,
10554 const ParsedAttributesView &Attr) {
10555
10556 bool Owned = false;
10557 bool IsDependent = false;
10558 Decl *TagD =
10559 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10560 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10561 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10562 false, TypeResult(), /*IsTypeSpecifier*/ false,
10563 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10564 .get();
10565 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10566
10567 if (!TagD)
10568 return true;
10569
10570 TagDecl *Tag = cast<TagDecl>(TagD);
10571 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10572
10573 if (Tag->isInvalidDecl())
10574 return true;
10575
10577 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10578 if (!Pattern) {
10579 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10580 << Context.getCanonicalTagType(Record);
10581 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10582 return true;
10583 }
10584
10585 // C++0x [temp.explicit]p2:
10586 // If the explicit instantiation is for a class or member class, the
10587 // elaborated-type-specifier in the declaration shall include a
10588 // simple-template-id.
10589 //
10590 // C++98 has the same restriction, just worded differently.
10592 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10593 << Record << SS.getRange();
10594
10595 // C++0x [temp.explicit]p2:
10596 // There are two forms of explicit instantiation: an explicit instantiation
10597 // definition and an explicit instantiation declaration. An explicit
10598 // instantiation declaration begins with the extern keyword. [...]
10602
10603 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10604
10605 // Verify that it is okay to explicitly instantiate here.
10606 CXXRecordDecl *PrevDecl
10607 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10608 if (!PrevDecl && Record->getDefinition())
10609 PrevDecl = Record;
10610 if (PrevDecl) {
10612 bool HasNoEffect = false;
10613 assert(MSInfo && "No member specialization information?");
10614 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10615 PrevDecl,
10617 MSInfo->getPointOfInstantiation(),
10618 HasNoEffect))
10619 return true;
10620 if (HasNoEffect) {
10624 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10625 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10626 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10627 TL.setElaboratedKeywordLoc(KWLoc);
10628 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10629 TL.setNameLoc(NameLoc);
10631 TemplateLoc, NestedNameSpecifierLoc(),
10632 nullptr, NameLoc, TSI, TSK);
10633 return TagD;
10634 }
10635 }
10636
10637 CXXRecordDecl *RecordDef
10638 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10639 if (!RecordDef) {
10640 // C++ [temp.explicit]p3:
10641 // A definition of a member class of a class template shall be in scope
10642 // at the point of an explicit instantiation of the member class.
10643 CXXRecordDecl *Def
10644 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10645 if (!Def) {
10646 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10647 << 0 << Record->getDeclName() << Record->getDeclContext();
10648 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10649 << Pattern;
10650 return true;
10651 } else {
10652 if (InstantiateClass(NameLoc, Record, Def,
10654 TSK))
10655 return true;
10656
10657 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10658 if (!RecordDef)
10659 return true;
10660 }
10661 }
10662
10663 // Instantiate all of the members of the class.
10664 InstantiateClassMembers(NameLoc, RecordDef,
10666
10668 MarkVTableUsed(NameLoc, RecordDef, true);
10669
10672 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10673 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10674 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10675 TL.setElaboratedKeywordLoc(KWLoc);
10676 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10677 TL.setNameLoc(NameLoc);
10679 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10680 NameLoc, TSI, TSK);
10681 return TagD;
10682}
10683
10685 SourceLocation ExternLoc,
10686 SourceLocation TemplateLoc,
10687 Declarator &D) {
10688 // Explicit instantiations always require a name.
10689 // TODO: check if/when DNInfo should replace Name.
10691 DeclarationName Name = NameInfo.getName();
10692 if (!Name) {
10693 if (!D.isInvalidType())
10695 diag::err_explicit_instantiation_requires_name)
10697
10698 return true;
10699 }
10700
10701 // Get the innermost enclosing declaration scope.
10702 S = S->getDeclParent();
10703
10704 // Determine the type of the declaration.
10706 QualType R = T->getType();
10707 if (R.isNull())
10708 return true;
10709
10710 // C++ [dcl.stc]p1:
10711 // A storage-class-specifier shall not be specified in [...] an explicit
10712 // instantiation (14.7.2) directive.
10714 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10715 << Name;
10716 return true;
10717 } else if (D.getDeclSpec().getStorageClassSpec()
10719 // Complain about then remove the storage class specifier.
10720 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10722
10724 }
10725
10726 // C++0x [temp.explicit]p1:
10727 // [...] An explicit instantiation of a function template shall not use the
10728 // inline or constexpr specifiers.
10729 // Presumably, this also applies to member functions of class templates as
10730 // well.
10734 diag::err_explicit_instantiation_inline :
10735 diag::warn_explicit_instantiation_inline_0x)
10737 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10738 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10739 // not already specified.
10741 diag::err_explicit_instantiation_constexpr);
10742
10743 // A deduction guide is not on the list of entities that can be explicitly
10744 // instantiated.
10746 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10747 << /*explicit instantiation*/ 0;
10748 return true;
10749 }
10750
10751 // C++0x [temp.explicit]p2:
10752 // There are two forms of explicit instantiation: an explicit instantiation
10753 // definition and an explicit instantiation declaration. An explicit
10754 // instantiation declaration begins with the extern keyword. [...]
10758
10759 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10761 /*ObjectType=*/QualType());
10762
10763 if (!R->isFunctionType()) {
10764 // C++ [temp.explicit]p1:
10765 // A [...] static data member of a class template can be explicitly
10766 // instantiated from the member definition associated with its class
10767 // template.
10768 // C++1y [temp.explicit]p1:
10769 // A [...] variable [...] template specialization can be explicitly
10770 // instantiated from its template.
10771 if (Previous.isAmbiguous())
10772 return true;
10773
10774 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10775 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10776 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10777
10778 if (!PrevTemplate) {
10779 if (!Prev || !Prev->isStaticDataMember()) {
10780 // We expect to see a static data member here.
10781 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10782 << Name;
10783 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10784 P != PEnd; ++P)
10785 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10786 return true;
10787 }
10788
10790 // FIXME: Check for explicit specialization?
10792 diag::err_explicit_instantiation_data_member_not_instantiated)
10793 << Prev;
10794 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10795 // FIXME: Can we provide a note showing where this was declared?
10796 return true;
10797 }
10798 } else {
10799 // Explicitly instantiate a variable template.
10800
10801 // C++1y [dcl.spec.auto]p6:
10802 // ... A program that uses auto or decltype(auto) in a context not
10803 // explicitly allowed in this section is ill-formed.
10804 //
10805 // This includes auto-typed variable template instantiations.
10806 if (R->isUndeducedType()) {
10807 Diag(T->getTypeLoc().getBeginLoc(),
10808 diag::err_auto_not_allowed_var_inst);
10809 return true;
10810 }
10811
10813 // C++1y [temp.explicit]p3:
10814 // If the explicit instantiation is for a variable, the unqualified-id
10815 // in the declaration shall be a template-id.
10817 diag::err_explicit_instantiation_without_template_id)
10818 << PrevTemplate;
10819 Diag(PrevTemplate->getLocation(),
10820 diag::note_explicit_instantiation_here);
10821 return true;
10822 }
10823
10824 // Translate the parser's template argument list into our AST format.
10825 TemplateArgumentListInfo TemplateArgs =
10827
10828 DeclResult Res =
10829 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10830 TemplateArgs, /*SetWrittenArgs=*/true);
10831 if (Res.isInvalid())
10832 return true;
10833
10834 if (!Res.isUsable()) {
10835 // We somehow specified dependent template arguments in an explicit
10836 // instantiation. This should probably only happen during error
10837 // recovery.
10838 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10839 return true;
10840 }
10841
10842 // Ignore access control bits, we don't need them for redeclaration
10843 // checking.
10844 Prev = cast<VarDecl>(Res.get());
10845 ArgsAsWritten =
10847 }
10848
10849 // C++0x [temp.explicit]p2:
10850 // If the explicit instantiation is for a member function, a member class
10851 // or a static data member of a class template specialization, the name of
10852 // the class template specialization in the qualified-id for the member
10853 // name shall be a simple-template-id.
10854 //
10855 // C++98 has the same restriction, just worded differently.
10856 //
10857 // This does not apply to variable template specializations, where the
10858 // template-id is in the unqualified-id instead.
10859 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10861 diag::ext_explicit_instantiation_without_qualified_id)
10862 << Prev << D.getCXXScopeSpec().getRange();
10863
10864 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10865
10866 // Verify that it is okay to explicitly instantiate here.
10869 bool HasNoEffect = false;
10871 PrevTSK, POI, HasNoEffect))
10872 return true;
10873
10874 if (!HasNoEffect) {
10875 // Instantiate static data member or variable template.
10877 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10878 VTSD->setExternKeywordLoc(ExternLoc);
10879 VTSD->setTemplateKeywordLoc(TemplateLoc);
10880 }
10881
10882 // Merge attributes.
10884 if (PrevTemplate)
10885 ProcessAPINotes(Prev);
10886
10889 }
10890
10891 // Check the new variable specialization against the parsed input.
10892 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10893 Diag(T->getTypeLoc().getBeginLoc(),
10894 diag::err_invalid_var_template_spec_type)
10895 << 0 << PrevTemplate << R << Prev->getType();
10896 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10897 << 2 << PrevTemplate->getDeclName();
10898 return true;
10899 }
10900
10902 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10903 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10904 D.getIdentifierLoc(), T, TSK);
10905 return (Decl *)nullptr;
10906 }
10907
10908 // If the declarator is a template-id, translate the parser's template
10909 // argument list into our AST format.
10910 bool HasExplicitTemplateArgs = false;
10911 TemplateArgumentListInfo TemplateArgs;
10913 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10914 HasExplicitTemplateArgs = true;
10915 }
10916
10917 // C++ [temp.explicit]p1:
10918 // A [...] function [...] can be explicitly instantiated from its template.
10919 // A member function [...] of a class template can be explicitly
10920 // instantiated from the member definition associated with its class
10921 // template.
10922 UnresolvedSet<8> TemplateMatches;
10923 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10925 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10926 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10927 P != PEnd; ++P) {
10928 NamedDecl *Prev = *P;
10929 if (!HasExplicitTemplateArgs) {
10930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10931 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10932 /*AdjustExceptionSpec*/true);
10933 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10934 if (Method->getPrimaryTemplate()) {
10935 TemplateMatches.addDecl(Method, P.getAccess());
10936 } else {
10937 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10938 C.FoundDecl = P.getPair();
10939 C.Function = Method;
10940 C.Viable = true;
10942 if (Method->getTrailingRequiresClause() &&
10944 /*ForOverloadResolution=*/true) ||
10945 !S.IsSatisfied)) {
10946 C.Viable = false;
10948 }
10949 }
10950 }
10951 }
10952 }
10953
10954 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10955 if (!FunTmpl)
10956 continue;
10957
10958 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10959 FunctionDecl *Specialization = nullptr;
10961 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10962 Specialization, Info);
10964 // Keep track of almost-matches.
10965 FailedTemplateCandidates.addCandidate().set(
10966 P.getPair(), FunTmpl->getTemplatedDecl(),
10967 MakeDeductionFailureInfo(Context, TDK, Info));
10968 (void)TDK;
10969 continue;
10970 }
10971
10972 // Target attributes are part of the cuda function signature, so
10973 // the cuda target of the instantiated function must match that of its
10974 // template. Given that C++ template deduction does not take
10975 // target attributes into account, we reject candidates here that
10976 // have a different target.
10977 if (LangOpts.CUDA &&
10978 CUDA().IdentifyTarget(Specialization,
10979 /* IgnoreImplicitHDAttr = */ true) !=
10980 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10981 FailedTemplateCandidates.addCandidate().set(
10982 P.getPair(), FunTmpl->getTemplatedDecl(),
10985 continue;
10986 }
10987
10988 TemplateMatches.addDecl(Specialization, P.getAccess());
10989 }
10990
10991 FunctionDecl *Specialization = nullptr;
10992 if (!NonTemplateMatches.empty()) {
10993 unsigned Msg = 0;
10994 OverloadCandidateDisplayKind DisplayKind;
10996 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10997 Best)) {
10998 case OR_Success:
10999 case OR_Deleted:
11000 Specialization = cast<FunctionDecl>(Best->Function);
11001 break;
11002 case OR_Ambiguous:
11003 Msg = diag::err_explicit_instantiation_ambiguous;
11004 DisplayKind = OCD_AmbiguousCandidates;
11005 break;
11007 Msg = diag::err_explicit_instantiation_no_candidate;
11008 DisplayKind = OCD_AllCandidates;
11009 break;
11010 }
11011 if (Msg) {
11012 PartialDiagnostic Diag = PDiag(Msg) << Name;
11013 NonTemplateMatches.NoteCandidates(
11014 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11015 {});
11016 return true;
11017 }
11018 }
11019
11020 if (!Specialization) {
11021 // Find the most specialized function template specialization.
11023 TemplateMatches.begin(), TemplateMatches.end(),
11024 FailedTemplateCandidates, D.getIdentifierLoc(),
11025 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11026 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11027 PDiag(diag::note_explicit_instantiation_candidate));
11028
11029 if (Result == TemplateMatches.end())
11030 return true;
11031
11032 // Ignore access control bits, we don't need them for redeclaration checking.
11034 }
11035
11036 // C++11 [except.spec]p4
11037 // In an explicit instantiation an exception-specification may be specified,
11038 // but is not required.
11039 // If an exception-specification is specified in an explicit instantiation
11040 // directive, it shall be compatible with the exception-specifications of
11041 // other declarations of that function.
11042 if (auto *FPT = R->getAs<FunctionProtoType>())
11043 if (FPT->hasExceptionSpec()) {
11044 unsigned DiagID =
11045 diag::err_mismatched_exception_spec_explicit_instantiation;
11046 if (getLangOpts().MicrosoftExt)
11047 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11049 PDiag(DiagID) << Specialization->getType(),
11050 PDiag(diag::note_explicit_instantiation_here),
11051 Specialization->getType()->getAs<FunctionProtoType>(),
11052 Specialization->getLocation(), FPT, D.getBeginLoc());
11053 // In Microsoft mode, mismatching exception specifications just cause a
11054 // warning.
11055 if (!getLangOpts().MicrosoftExt && Result)
11056 return true;
11057 }
11058
11059 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11061 diag::err_explicit_instantiation_member_function_not_instantiated)
11063 << (Specialization->getTemplateSpecializationKind() ==
11065 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11066 return true;
11067 }
11068
11069 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11070 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11071 PrevDecl = Specialization;
11072
11073 if (PrevDecl) {
11074 bool HasNoEffect = false;
11076 PrevDecl,
11078 PrevDecl->getPointOfInstantiation(),
11079 HasNoEffect))
11080 return true;
11081
11082 if (HasNoEffect) {
11083 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11084 if (HasExplicitTemplateArgs)
11085 ArgsAsWritten =
11088 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11089 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11090 D.getIdentifierLoc(), T, TSK);
11091 return (Decl *)nullptr;
11092 }
11093 }
11094
11095 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11096 // functions
11097 // valarray<size_t>::valarray(size_t) and
11098 // valarray<size_t>::~valarray()
11099 // that it declared to have internal linkage with the internal_linkage
11100 // attribute. Ignore the explicit instantiation declaration in this case.
11101 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11103 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11104 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11105 RD->isInStdNamespace())
11106 return (Decl*) nullptr;
11107 }
11108
11111
11112 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11113 // instantiation declarations.
11115 Specialization->hasAttr<DLLImportAttr>() &&
11116 Context.getTargetInfo().getCXXABI().isMicrosoft())
11118
11119 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11120 if (Specialization->isDefined()) {
11121 // Let the ASTConsumer know that this function has been explicitly
11122 // instantiated now, and its linkage might have changed.
11123 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11124 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11125 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11126 // be explicitly instantiated.
11127 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11128 RD && RD->isLambda()) {
11129 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11130 << /*instantiation*/ 1;
11131 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11132 return (Decl *)nullptr;
11133 }
11135 }
11136
11137 // C++0x [temp.explicit]p2:
11138 // If the explicit instantiation is for a member function, a member class
11139 // or a static data member of a class template specialization, the name of
11140 // the class template specialization in the qualified-id for the member
11141 // name shall be a simple-template-id.
11142 //
11143 // C++98 has the same restriction, just worded differently.
11144 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11145 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11146 D.getCXXScopeSpec().isSet() &&
11149 diag::ext_explicit_instantiation_without_qualified_id)
11151
11153 *this,
11154 FunTmpl ? (NamedDecl *)FunTmpl
11155 : Specialization->getInstantiatedFromMemberFunction(),
11156 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11157
11158 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11159 if (HasExplicitTemplateArgs)
11160 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11162 TemplateLoc,
11164 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11165 return (Decl *)nullptr;
11166}
11167
11169 const CXXScopeSpec &SS,
11170 const IdentifierInfo *Name,
11171 SourceLocation TagLoc,
11172 SourceLocation NameLoc) {
11173 // This has to hold, because SS is expected to be defined.
11174 assert(Name && "Expected a name in a dependent tag");
11175
11177 if (!NNS)
11178 return true;
11179
11181
11182 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11183 Diag(NameLoc, diag::err_dependent_tag_decl)
11184 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11185 return true;
11186 }
11187
11188 // Create the resulting type.
11190 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11191
11192 // Create type-source location information for this type.
11193 TypeLocBuilder TLB;
11195 TL.setElaboratedKeywordLoc(TagLoc);
11197 TL.setNameLoc(NameLoc);
11199}
11200
11202 const CXXScopeSpec &SS,
11203 const IdentifierInfo &II,
11204 SourceLocation IdLoc,
11205 ImplicitTypenameContext IsImplicitTypename) {
11206 if (SS.isInvalid())
11207 return true;
11208
11209 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11210 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11211 << FixItHint::CreateRemoval(TypenameLoc);
11212
11214 TypeSourceInfo *TSI = nullptr;
11215 QualType T =
11218 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11219 /*DeducedTSTContext=*/true);
11220 if (T.isNull())
11221 return true;
11222 return CreateParsedType(T, TSI);
11223}
11224
11227 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11228 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11229 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11230 ASTTemplateArgsPtr TemplateArgsIn,
11231 SourceLocation RAngleLoc) {
11232 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11233 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11234 ? diag::compat_cxx11_typename_outside_of_template
11235 : diag::compat_pre_cxx11_typename_outside_of_template)
11236 << FixItHint::CreateRemoval(TypenameLoc);
11237
11238 // Strangely, non-type results are not ignored by this lookup, so the
11239 // program is ill-formed if it finds an injected-class-name.
11240 if (TypenameLoc.isValid()) {
11241 auto *LookupRD =
11242 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11243 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11244 Diag(TemplateIILoc,
11245 diag::ext_out_of_line_qualified_id_type_names_constructor)
11246 << TemplateII << 0 /*injected-class-name used as template name*/
11247 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11248 }
11249 }
11250
11251 // Translate the parser's template argument list in our AST format.
11252 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11253 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11254
11258 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11259 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11260 if (T.isNull())
11261 return true;
11262
11263 // Provide source-location information for the template specialization type.
11264 TypeLocBuilder Builder;
11266 = Builder.push<TemplateSpecializationTypeLoc>(T);
11267 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11268 TemplateIILoc, TemplateArgs);
11269 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11270 return CreateParsedType(T, TSI);
11271}
11272
11273/// Determine whether this failed name lookup should be treated as being
11274/// disabled by a usage of std::enable_if.
11276 SourceRange &CondRange, Expr *&Cond) {
11277 // We must be looking for a ::type...
11278 if (!II.isStr("type"))
11279 return false;
11280
11281 // ... within an explicitly-written template specialization...
11283 return false;
11284
11285 // FIXME: Look through sugar.
11286 auto EnableIfTSTLoc =
11288 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11289 return false;
11290 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11291
11292 // ... which names a complete class template declaration...
11293 const TemplateDecl *EnableIfDecl =
11294 EnableIfTST->getTemplateName().getAsTemplateDecl();
11295 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11296 return false;
11297
11298 // ... called "enable_if".
11299 const IdentifierInfo *EnableIfII =
11300 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11301 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11302 return false;
11303
11304 // Assume the first template argument is the condition.
11305 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11306
11307 // Dig out the condition.
11308 Cond = nullptr;
11309 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11311 return true;
11312
11313 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11314
11315 // Ignore Boolean literals; they add no value.
11316 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11317 Cond = nullptr;
11318
11319 return true;
11320}
11321
11324 SourceLocation KeywordLoc,
11325 NestedNameSpecifierLoc QualifierLoc,
11326 const IdentifierInfo &II,
11327 SourceLocation IILoc,
11328 TypeSourceInfo **TSI,
11329 bool DeducedTSTContext) {
11330 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11331 DeducedTSTContext);
11332 if (T.isNull())
11333 return QualType();
11334
11335 TypeLocBuilder TLB;
11336 if (isa<DependentNameType>(T)) {
11337 auto TL = TLB.push<DependentNameTypeLoc>(T);
11338 TL.setElaboratedKeywordLoc(KeywordLoc);
11339 TL.setQualifierLoc(QualifierLoc);
11340 TL.setNameLoc(IILoc);
11343 TL.setElaboratedKeywordLoc(KeywordLoc);
11344 TL.setQualifierLoc(QualifierLoc);
11345 TL.setNameLoc(IILoc);
11346 } else if (isa<TemplateTypeParmType>(T)) {
11347 // FIXME: There might be a 'typename' keyword here, but we just drop it
11348 // as it can't be represented.
11349 assert(!QualifierLoc);
11350 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11351 } else if (isa<TagType>(T)) {
11352 auto TL = TLB.push<TagTypeLoc>(T);
11353 TL.setElaboratedKeywordLoc(KeywordLoc);
11354 TL.setQualifierLoc(QualifierLoc);
11355 TL.setNameLoc(IILoc);
11356 } else if (isa<TypedefType>(T)) {
11357 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11358 } else {
11359 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11360 }
11361 *TSI = TLB.getTypeSourceInfo(Context, T);
11362 return T;
11363}
11364
11365/// Build the type that describes a C++ typename specifier,
11366/// e.g., "typename T::type".
11369 SourceLocation KeywordLoc,
11370 NestedNameSpecifierLoc QualifierLoc,
11371 const IdentifierInfo &II,
11372 SourceLocation IILoc, bool DeducedTSTContext) {
11373 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11374
11375 CXXScopeSpec SS;
11376 SS.Adopt(QualifierLoc);
11377
11378 DeclContext *Ctx = nullptr;
11379 if (QualifierLoc) {
11380 Ctx = computeDeclContext(SS);
11381 if (!Ctx) {
11382 // If the nested-name-specifier is dependent and couldn't be
11383 // resolved to a type, build a typename type.
11384 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11385 return Context.getDependentNameType(Keyword,
11386 QualifierLoc.getNestedNameSpecifier(),
11387 &II);
11388 }
11389
11390 // If the nested-name-specifier refers to the current instantiation,
11391 // the "typename" keyword itself is superfluous. In C++03, the
11392 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11393 // allows such extraneous "typename" keywords, and we retroactively
11394 // apply this DR to C++03 code with only a warning. In any case we continue.
11395
11396 if (RequireCompleteDeclContext(SS, Ctx))
11397 return QualType();
11398 }
11399
11400 DeclarationName Name(&II);
11401 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11402 if (Ctx)
11403 LookupQualifiedName(Result, Ctx, SS);
11404 else
11405 LookupName(Result, CurScope);
11406 unsigned DiagID = 0;
11407 Decl *Referenced = nullptr;
11408 switch (Result.getResultKind()) {
11410 // If we're looking up 'type' within a template named 'enable_if', produce
11411 // a more specific diagnostic.
11412 SourceRange CondRange;
11413 Expr *Cond = nullptr;
11414 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11415 // If we have a condition, narrow it down to the specific failed
11416 // condition.
11417 if (Cond) {
11418 Expr *FailedCond;
11419 std::string FailedDescription;
11420 std::tie(FailedCond, FailedDescription) =
11422
11423 Diag(FailedCond->getExprLoc(),
11424 diag::err_typename_nested_not_found_requirement)
11425 << FailedDescription
11426 << FailedCond->getSourceRange();
11427 return QualType();
11428 }
11429
11430 Diag(CondRange.getBegin(),
11431 diag::err_typename_nested_not_found_enable_if)
11432 << Ctx << CondRange;
11433 return QualType();
11434 }
11435
11436 DiagID = Ctx ? diag::err_typename_nested_not_found
11437 : diag::err_unknown_typename;
11438 break;
11439 }
11440
11442 // We found a using declaration that is a value. Most likely, the using
11443 // declaration itself is meant to have the 'typename' keyword.
11444 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11445 IILoc);
11446 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11447 << Name << Ctx << FullRange;
11448 if (UnresolvedUsingValueDecl *Using
11449 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11450 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11451 Diag(Loc, diag::note_using_value_decl_missing_typename)
11452 << FixItHint::CreateInsertion(Loc, "typename ");
11453 }
11454 }
11455 // Fall through to create a dependent typename type, from which we can
11456 // recover better.
11457 [[fallthrough]];
11458
11460 // Okay, it's a member of an unknown instantiation.
11461 return Context.getDependentNameType(Keyword,
11462 QualifierLoc.getNestedNameSpecifier(),
11463 &II);
11464
11466 // FXIME: Missing support for UsingShadowDecl on this path?
11467 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11468 // C++ [class.qual]p2:
11469 // In a lookup in which function names are not ignored and the
11470 // nested-name-specifier nominates a class C, if the name specified
11471 // after the nested-name-specifier, when looked up in C, is the
11472 // injected-class-name of C [...] then the name is instead considered
11473 // to name the constructor of class C.
11474 //
11475 // Unlike in an elaborated-type-specifier, function names are not ignored
11476 // in typename-specifier lookup. However, they are ignored in all the
11477 // contexts where we form a typename type with no keyword (that is, in
11478 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11479 //
11480 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11481 // ignore functions, but that appears to be an oversight.
11486 Type, IILoc);
11487 // FIXME: This appears to be the only case where a template type parameter
11488 // can have an elaborated keyword. We should preserve it somehow.
11491 assert(!QualifierLoc);
11493 }
11494 return Context.getTypeDeclType(
11495 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11496 }
11497
11498 // C++ [dcl.type.simple]p2:
11499 // A type-specifier of the form
11500 // typename[opt] nested-name-specifier[opt] template-name
11501 // is a placeholder for a deduced class type [...].
11502 if (getLangOpts().CPlusPlus17) {
11503 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11504 if (!DeducedTSTContext) {
11505 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11506 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11507 Diag(IILoc, diag::err_dependent_deduced_tst)
11509 << QualType(Qualifier.getAsType(), 0);
11510 else
11511 Diag(IILoc, diag::err_deduced_tst)
11514 return QualType();
11515 }
11516 TemplateName Name = Context.getQualifiedTemplateName(
11517 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11518 TemplateName(TD));
11519 return Context.getDeducedTemplateSpecializationType(
11520 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11521 Name);
11522 }
11523 }
11524
11525 DiagID = Ctx ? diag::err_typename_nested_not_type
11526 : diag::err_typename_not_type;
11527 Referenced = Result.getFoundDecl();
11528 break;
11529
11531 DiagID = Ctx ? diag::err_typename_nested_not_type
11532 : diag::err_typename_not_type;
11533 Referenced = *Result.begin();
11534 break;
11535
11537 return QualType();
11538 }
11539
11540 // If we get here, it's because name lookup did not find a
11541 // type. Emit an appropriate diagnostic and return an error.
11542 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11543 IILoc);
11544 if (Ctx)
11545 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11546 else
11547 Diag(IILoc, DiagID) << FullRange << Name;
11548 if (Referenced)
11549 Diag(Referenced->getLocation(),
11550 Ctx ? diag::note_typename_member_refers_here
11551 : diag::note_typename_refers_here)
11552 << Name;
11553 return QualType();
11554}
11555
11556namespace {
11557 // See Sema::RebuildTypeInCurrentInstantiation
11558 class CurrentInstantiationRebuilder
11559 : public TreeTransform<CurrentInstantiationRebuilder> {
11560 SourceLocation Loc;
11561 DeclarationName Entity;
11562
11563 public:
11565
11566 CurrentInstantiationRebuilder(Sema &SemaRef,
11567 SourceLocation Loc,
11568 DeclarationName Entity)
11569 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11570 Loc(Loc), Entity(Entity) { }
11571
11572 /// Determine whether the given type \p T has already been
11573 /// transformed.
11574 ///
11575 /// For the purposes of type reconstruction, a type has already been
11576 /// transformed if it is NULL or if it is not dependent.
11577 bool AlreadyTransformed(QualType T) {
11578 return T.isNull() || !T->isInstantiationDependentType();
11579 }
11580
11581 /// Returns the location of the entity whose type is being
11582 /// rebuilt.
11583 SourceLocation getBaseLocation() { return Loc; }
11584
11585 /// Returns the name of the entity whose type is being rebuilt.
11586 DeclarationName getBaseEntity() { return Entity; }
11587
11588 /// Sets the "base" location and entity when that
11589 /// information is known based on another transformation.
11590 void setBase(SourceLocation Loc, DeclarationName Entity) {
11591 this->Loc = Loc;
11592 this->Entity = Entity;
11593 }
11594
11595 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11596 // Lambdas never need to be transformed.
11597 return E;
11598 }
11599 };
11600} // end anonymous namespace
11601
11603 SourceLocation Loc,
11604 DeclarationName Name) {
11605 if (!T || !T->getType()->isInstantiationDependentType())
11606 return T;
11607
11608 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11609 return Rebuilder.TransformType(T);
11610}
11611
11613 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11614 DeclarationName());
11615 return Rebuilder.TransformExpr(E);
11616}
11617
11619 if (SS.isInvalid())
11620 return true;
11621
11623 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11624 DeclarationName());
11626 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11627 if (!Rebuilt)
11628 return true;
11629
11630 SS.Adopt(Rebuilt);
11631 return false;
11632}
11633
11635 TemplateParameterList *Params) {
11636 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11637 Decl *Param = Params->getParam(I);
11638
11639 // There is nothing to rebuild in a type parameter.
11640 if (isa<TemplateTypeParmDecl>(Param))
11641 continue;
11642
11643 // Rebuild the template parameter list of a template template parameter.
11645 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11647 TTP->getTemplateParameters()))
11648 return true;
11649
11650 continue;
11651 }
11652
11653 // Rebuild the type of a non-type template parameter.
11655 TypeSourceInfo *NewTSI
11657 NTTP->getLocation(),
11658 NTTP->getDeclName());
11659 if (!NewTSI)
11660 return true;
11661
11662 if (NewTSI->getType()->isUndeducedType()) {
11663 // C++17 [temp.dep.expr]p3:
11664 // An id-expression is type-dependent if it contains
11665 // - an identifier associated by name lookup with a non-type
11666 // template-parameter declared with a type that contains a
11667 // placeholder type (7.1.7.4),
11668 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11669 }
11670
11671 if (NewTSI != NTTP->getTypeSourceInfo()) {
11672 NTTP->setTypeSourceInfo(NewTSI);
11673 NTTP->setType(NewTSI->getType());
11674 }
11675 }
11676
11677 return false;
11678}
11679
11680std::string
11682 const TemplateArgumentList &Args) {
11683 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11684}
11685
11686std::string
11688 const TemplateArgument *Args,
11689 unsigned NumArgs) {
11690 SmallString<128> Str;
11691 llvm::raw_svector_ostream Out(Str);
11692
11693 if (!Params || Params->size() == 0 || NumArgs == 0)
11694 return std::string();
11695
11696 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11697 if (I >= NumArgs)
11698 break;
11699
11700 if (I == 0)
11701 Out << "[with ";
11702 else
11703 Out << ", ";
11704
11705 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11706 Out << Id->getName();
11707 } else {
11708 Out << '$' << I;
11709 }
11710
11711 Out << " = ";
11712 Args[I].print(getPrintingPolicy(), Out,
11714 getPrintingPolicy(), Params, I));
11715 }
11716
11717 Out << ']';
11718 return std::string(Out.str());
11719}
11720
11722 CachedTokens &Toks) {
11723 if (!FD)
11724 return;
11725
11726 auto LPT = std::make_unique<LateParsedTemplate>();
11727
11728 // Take tokens to avoid allocations
11729 LPT->Toks.swap(Toks);
11730 LPT->D = FnD;
11731 LPT->FPO = getCurFPFeatures();
11732 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11733
11734 FD->setLateTemplateParsed(true);
11735}
11736
11738 if (!FD)
11739 return;
11740 FD->setLateTemplateParsed(false);
11741}
11742
11744 DeclContext *DC = CurContext;
11745
11746 while (DC) {
11747 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11748 const FunctionDecl *FD = RD->isLocalClass();
11749 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11750 } else if (DC->isTranslationUnit() || DC->isNamespace())
11751 return false;
11752
11753 DC = DC->getParent();
11754 }
11755 return false;
11756}
11757
11758namespace {
11759/// Walk the path from which a declaration was instantiated, and check
11760/// that every explicit specialization along that path is visible. This enforces
11761/// C++ [temp.expl.spec]/6:
11762///
11763/// If a template, a member template or a member of a class template is
11764/// explicitly specialized then that specialization shall be declared before
11765/// the first use of that specialization that would cause an implicit
11766/// instantiation to take place, in every translation unit in which such a
11767/// use occurs; no diagnostic is required.
11768///
11769/// and also C++ [temp.class.spec]/1:
11770///
11771/// A partial specialization shall be declared before the first use of a
11772/// class template specialization that would make use of the partial
11773/// specialization as the result of an implicit or explicit instantiation
11774/// in every translation unit in which such a use occurs; no diagnostic is
11775/// required.
11776class ExplicitSpecializationVisibilityChecker {
11777 Sema &S;
11778 SourceLocation Loc;
11781
11782public:
11783 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11785 : S(S), Loc(Loc), Kind(Kind) {}
11786
11787 void check(NamedDecl *ND) {
11788 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11789 return checkImpl(FD);
11790 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11791 return checkImpl(RD);
11792 if (auto *VD = dyn_cast<VarDecl>(ND))
11793 return checkImpl(VD);
11794 if (auto *ED = dyn_cast<EnumDecl>(ND))
11795 return checkImpl(ED);
11796 }
11797
11798private:
11799 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11800 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11801 : Sema::MissingImportKind::ExplicitSpecialization;
11802 const bool Recover = true;
11803
11804 // If we got a custom set of modules (because only a subset of the
11805 // declarations are interesting), use them, otherwise let
11806 // diagnoseMissingImport intelligently pick some.
11807 if (Modules.empty())
11808 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11809 else
11810 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11811 }
11812
11813 bool CheckMemberSpecialization(const NamedDecl *D) {
11814 return Kind == Sema::AcceptableKind::Visible
11817 }
11818
11819 bool CheckExplicitSpecialization(const NamedDecl *D) {
11820 return Kind == Sema::AcceptableKind::Visible
11823 }
11824
11825 bool CheckDeclaration(const NamedDecl *D) {
11826 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11828 }
11829
11830 // Check a specific declaration. There are three problematic cases:
11831 //
11832 // 1) The declaration is an explicit specialization of a template
11833 // specialization.
11834 // 2) The declaration is an explicit specialization of a member of an
11835 // templated class.
11836 // 3) The declaration is an instantiation of a template, and that template
11837 // is an explicit specialization of a member of a templated class.
11838 //
11839 // We don't need to go any deeper than that, as the instantiation of the
11840 // surrounding class / etc is not triggered by whatever triggered this
11841 // instantiation, and thus should be checked elsewhere.
11842 template<typename SpecDecl>
11843 void checkImpl(SpecDecl *Spec) {
11844 bool IsHiddenExplicitSpecialization = false;
11845 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11846 // Some invalid friend declarations are written as specializations but are
11847 // instantiated implicitly.
11848 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11849 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11850 if (SpecKind == TSK_ExplicitSpecialization) {
11851 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11852 ? !CheckMemberSpecialization(Spec)
11853 : !CheckExplicitSpecialization(Spec);
11854 } else {
11855 checkInstantiated(Spec);
11856 }
11857
11858 if (IsHiddenExplicitSpecialization)
11859 diagnose(Spec->getMostRecentDecl(), false);
11860 }
11861
11862 void checkInstantiated(FunctionDecl *FD) {
11863 if (auto *TD = FD->getPrimaryTemplate())
11864 checkTemplate(TD);
11865 }
11866
11867 void checkInstantiated(CXXRecordDecl *RD) {
11868 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11869 if (!SD)
11870 return;
11871
11872 auto From = SD->getSpecializedTemplateOrPartial();
11873 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11874 checkTemplate(TD);
11875 else if (auto *TD =
11876 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11877 if (!CheckDeclaration(TD))
11878 diagnose(TD, true);
11879 checkTemplate(TD);
11880 }
11881 }
11882
11883 void checkInstantiated(VarDecl *RD) {
11884 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11885 if (!SD)
11886 return;
11887
11888 auto From = SD->getSpecializedTemplateOrPartial();
11889 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11890 checkTemplate(TD);
11891 else if (auto *TD =
11892 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11893 if (!CheckDeclaration(TD))
11894 diagnose(TD, true);
11895 checkTemplate(TD);
11896 }
11897 }
11898
11899 void checkInstantiated(EnumDecl *FD) {}
11900
11901 template<typename TemplDecl>
11902 void checkTemplate(TemplDecl *TD) {
11903 if (TD->isMemberSpecialization()) {
11904 if (!CheckMemberSpecialization(TD))
11905 diagnose(TD->getMostRecentDecl(), false);
11906 }
11907 }
11908};
11909} // end anonymous namespace
11910
11912 if (!getLangOpts().Modules)
11913 return;
11914
11915 ExplicitSpecializationVisibilityChecker(*this, Loc,
11917 .check(Spec);
11918}
11919
11921 NamedDecl *Spec) {
11922 if (!getLangOpts().CPlusPlusModules)
11923 return checkSpecializationVisibility(Loc, Spec);
11924
11925 ExplicitSpecializationVisibilityChecker(*this, Loc,
11927 .check(Spec);
11928}
11929
11932 return N->getLocation();
11933 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11935 return FD->getLocation();
11938 return N->getLocation();
11939 }
11940 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11941 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11942 continue;
11943 return CSC.PointOfInstantiation;
11944 }
11945 return N->getLocation();
11946}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, bool IsSpecified, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1001
APSInt & getInt()
Definition APValue.h:508
APSInt & getComplexIntImag()
Definition APValue.h:546
ValueKind getKind() const
Definition APValue.h:479
APFixedPoint & getFixedPoint()
Definition APValue.h:530
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1084
APValue & getVectorElt(unsigned I)
Definition APValue.h:582
unsigned getVectorLength() const
Definition APValue.h:590
bool isLValue() const
Definition APValue.h:490
bool isMemberPointer() const
Definition APValue.h:496
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
@ 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:1037
APSInt & getComplexIntReal()
Definition APValue.h:538
APFloat & getComplexFloatImag()
Definition APValue.h:562
APFloat & getComplexFloatReal()
Definition APValue.h:554
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:3956
QualType getElementType() const
Definition TypeBase.h:3798
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.
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
Attr - This represents one attribute.
Definition Attr.h:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2393
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2411
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2461
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2454
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2429
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2435
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2441
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
Pointer to a block type.
Definition TypeBase.h:3606
QualType getPointeeType() const
Definition TypeBase.h:3618
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:3228
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:2111
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:3870
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:1557
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2030
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:2060
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2056
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2037
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2071
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
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:4451
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:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isFileContext() const
Definition DeclBase.h:2193
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:2211
bool isTranslationUnit() const
Definition DeclBase.h:2198
bool isRecord() const
Definition DeclBase.h:2202
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:2174
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:1276
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1377
ValueDecl * getDecl()
Definition Expr.h:1344
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:1074
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1239
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
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:1230
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:850
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:820
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:1193
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2806
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:931
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4125
QualType getPointeeType() const
Definition TypeBase.h:4137
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2601
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2590
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3510
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4075
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4165
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4537
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4291
QualType getElementType() const
Definition TypeBase.h:4303
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateName(TemplateName Template)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4033
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4305
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5150
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:833
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:3079
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:4077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents a member of a struct/union/class.
Definition Decl.h:3182
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
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:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Represents a function declaration or definition.
Definition Decl.h:2018
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2494
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4181
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4510
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4289
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4148
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3723
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4120
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:4354
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2380
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4393
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3145
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4141
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4949
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
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:4907
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:3859
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3973
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5305
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:3681
Represents a linkage specification.
Definition DeclCXX.h:3033
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
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:4416
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5642
QualType getPointeeType() const
Definition TypeBase.h:3735
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:212
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:266
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:714
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1943
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
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:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:1423
bool isVarDeclReference() const
Definition ExprCXX.h:3302
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3318
bool isConceptReference() const
Definition ExprCXX.h:3291
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3337
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:4363
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:2188
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:8265
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3682
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3675
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4347
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4531
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5352
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
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:344
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:383
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:463
Scope * getDeclParent()
Definition Scope.h:317
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:314
@ 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:13749
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8534
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
Whether and why a template name is required in this lookup.
Definition Sema.h:11493
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11501
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12552
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12586
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:13688
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13148
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2655
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9416
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9423
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:9730
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:1473
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:4200
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:2077
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:11464
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12063
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12066
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12070
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1308
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:226
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition Sema.h:939
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:762
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:1212
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:12242
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12260
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12250
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12270
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:11514
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11521
@ None
This is not assumed to be a template name.
Definition Sema.h:11516
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11518
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:11450
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:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
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:14556
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14544
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14553
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14547
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14571
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1307
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:1306
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.
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:644
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:1446
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13787
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:15571
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1309
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:4698
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:6813
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6792
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:14064
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:11491
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:520
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:11674
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11684
@ TPC_FriendFunctionTemplate
Definition Sema.h:11682
@ TPC_ClassTemplateMember
Definition Sema.h:11680
@ TPC_FunctionTemplate
Definition Sema.h:11679
@ TPC_FriendClassTemplate
Definition Sema.h:11681
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11683
friend class InitializationSequence
Definition Sema.h:1588
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6363
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)
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
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:6500
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1300
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:3519
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11456
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:9739
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12991
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:8748
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13784
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:4664
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3739
StringRef getKindName() const
Definition Decl.h:3935
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4902
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5038
TagKind getTagKind() const
Definition Decl.h:3939
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
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:3710
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:3535
const Type * getTypeForDecl() const
Definition Decl.h:3560
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3569
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:884
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:6282
A container of type source information.
Definition TypeBase.h:8418
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:8429
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:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBooleanType() const
Definition TypeBase.h:9187
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2289
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2355
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8783
bool isPointerType() const
Definition TypeBase.h:8684
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
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:9172
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8871
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2963
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isBitIntType() const
Definition TypeBase.h:8959
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2109
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2864
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
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:5031
bool isPointerOrReferenceType() const
Definition TypeBase.h:8688
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isVectorType() const
Definition TypeBase.h:8823
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2471
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
QualType getUnderlyingType() const
Definition Decl.h:3639
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4173
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:2250
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:3390
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:437
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:6087
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3958
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3481
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
TLSKind getTLSKind() const
Definition Decl.cpp:2147
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2732
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:2867
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:2760
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:2739
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2858
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:4030
Represents a GCC generic vector type.
Definition TypeBase.h:4239
QualType getElementType() const
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,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1935
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
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:920
@ 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:604
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Extern
Definition Specifiers.h:252
@ TSCS_unspecified
Definition Specifiers.h:237
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Enum
The "enum" keyword.
Definition TypeBase.h:6009
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:562
@ Type
The name was classified as a type.
Definition Sema.h:564
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:1809
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:369
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
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:841
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
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:5970
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5988
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:1609
#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:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5456
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3385
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3402
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3367
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
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:12101
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12097
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12090
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12087
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12087
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13199
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13303
A stack object to be created when performing template instantiation.
Definition Sema.h:13390
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13537
NamedDecl * Previous
Definition Sema.h:356
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