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
777 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
779 bool Final) {
780 // The template argument itself might be an expression, in which case we just
781 // return that expression. This happens when substituting into an alias
782 // template.
783 Expr *Replacement;
784 bool refParam = true;
786 Replacement = Arg.getAsExpr();
787 refParam = Replacement->isLValue();
788 if (refParam && Replacement->getType()->isRecordType()) {
789 QualType ParamType =
791 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
792 : NTTP->getType();
793 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))
794 ParamType = PET->getPattern();
795 refParam = ParamType->isReferenceType();
796 }
797 } else {
798 ExprResult result =
799 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
800 if (result.isInvalid())
801 return ExprError();
802 Replacement = result.get();
804 }
805 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
806 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
807 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
808}
809
811 NamedDecl *Instantiation,
812 bool InstantiatedFromMember,
813 const NamedDecl *Pattern,
814 const NamedDecl *PatternDef,
816 bool Complain, bool *Unreachable) {
817 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
818 isa<VarDecl>(Instantiation));
819
820 bool IsEntityBeingDefined = false;
821 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
822 IsEntityBeingDefined = TD->isBeingDefined();
823
824 if (PatternDef && !IsEntityBeingDefined) {
825 NamedDecl *SuggestedDef = nullptr;
826 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
827 &SuggestedDef,
828 /*OnlyNeedComplete*/ false)) {
829 if (Unreachable)
830 *Unreachable = true;
831 // If we're allowed to diagnose this and recover, do so.
832 bool Recover = Complain && !isSFINAEContext();
833 if (Complain)
834 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
836 return !Recover;
837 }
838 return false;
839 }
840
841 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
842 return true;
843
844 CanQualType InstantiationTy;
845 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
846 InstantiationTy = Context.getCanonicalTagType(TD);
847 if (PatternDef) {
848 Diag(PointOfInstantiation,
849 diag::err_template_instantiate_within_definition)
850 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
851 << InstantiationTy;
852 // Not much point in noting the template declaration here, since
853 // we're lexically inside it.
854 Instantiation->setInvalidDecl();
855 } else if (InstantiatedFromMember) {
856 if (isa<FunctionDecl>(Instantiation)) {
857 Diag(PointOfInstantiation,
858 diag::err_explicit_instantiation_undefined_member)
859 << /*member function*/ 1 << Instantiation->getDeclName()
860 << Instantiation->getDeclContext();
861 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
862 } else {
863 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
864 Diag(PointOfInstantiation,
865 diag::err_implicit_instantiate_member_undefined)
866 << InstantiationTy;
867 Diag(Pattern->getLocation(), diag::note_member_declared_at);
868 }
869 } else {
870 if (isa<FunctionDecl>(Instantiation)) {
871 Diag(PointOfInstantiation,
872 diag::err_explicit_instantiation_undefined_func_template)
873 << Pattern;
874 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
875 } else if (isa<TagDecl>(Instantiation)) {
876 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
877 << (TSK != TSK_ImplicitInstantiation)
878 << InstantiationTy;
879 NoteTemplateLocation(*Pattern);
880 } else {
881 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
882 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
883 Diag(PointOfInstantiation,
884 diag::err_explicit_instantiation_undefined_var_template)
885 << Instantiation;
886 Instantiation->setInvalidDecl();
887 } else
888 Diag(PointOfInstantiation,
889 diag::err_explicit_instantiation_undefined_member)
890 << /*static data member*/ 2 << Instantiation->getDeclName()
891 << Instantiation->getDeclContext();
892 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
893 }
894 }
895
896 // In general, Instantiation isn't marked invalid to get more than one
897 // error for multiple undefined instantiations. But the code that does
898 // explicit declaration -> explicit definition conversion can't handle
899 // invalid declarations, so mark as invalid in that case.
901 Instantiation->setInvalidDecl();
902 return true;
903}
904
906 bool SupportedForCompatibility) {
907 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
908
909 // C++23 [temp.local]p6:
910 // The name of a template-parameter shall not be bound to any following.
911 // declaration whose locus is contained by the scope to which the
912 // template-parameter belongs.
913 //
914 // When MSVC compatibility is enabled, the diagnostic is always a warning
915 // by default. Otherwise, it an error unless SupportedForCompatibility is
916 // true, in which case it is a default-to-error warning.
917 unsigned DiagId =
918 getLangOpts().MSVCCompat
919 ? diag::ext_template_param_shadow
920 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
921 : diag::err_template_param_shadow);
922 const auto *ND = cast<NamedDecl>(PrevDecl);
923 Diag(Loc, DiagId) << ND->getDeclName();
925}
926
928 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
929 D = Temp->getTemplatedDecl();
930 return Temp;
931 }
932 return nullptr;
933}
934
936 SourceLocation EllipsisLoc) const {
937 assert(Kind == Template &&
938 "Only template template arguments can be pack expansions here");
939 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
940 "Template template argument pack expansion without packs");
942 Result.EllipsisLoc = EllipsisLoc;
943 return Result;
944}
945
947 const ParsedTemplateArgument &Arg) {
948
949 switch (Arg.getKind()) {
951 TypeSourceInfo *TSI;
952 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
953 if (!TSI)
954 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
956 }
957
959 Expr *E = Arg.getAsExpr();
960 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
961 }
962
965 TemplateArgument TArg;
966 if (Arg.getEllipsisLoc().isValid())
967 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
968 else
969 TArg = Template;
970 return TemplateArgumentLoc(
971 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
973 Arg.getNameLoc(), Arg.getEllipsisLoc());
974 }
975 }
976
977 llvm_unreachable("Unhandled parsed template argument");
978}
979
981 TemplateArgumentListInfo &TemplateArgs) {
982 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
983 TemplateArgs.addArgument(translateTemplateArgument(*this,
984 TemplateArgsIn[I]));
985}
986
988 SourceLocation Loc,
989 const IdentifierInfo *Name) {
990 NamedDecl *PrevDecl =
991 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
993 if (PrevDecl && PrevDecl->isTemplateParameter())
994 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
995}
996
998 TypeSourceInfo *TInfo;
999 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1000 if (T.isNull())
1001 return ParsedTemplateArgument();
1002 assert(TInfo && "template argument with no location");
1003
1004 // If we might have formed a deduced template specialization type, convert
1005 // it to a template template argument.
1006 if (getLangOpts().CPlusPlus17) {
1007 TypeLoc TL = TInfo->getTypeLoc();
1008 SourceLocation EllipsisLoc;
1009 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1010 EllipsisLoc = PET.getEllipsisLoc();
1011 TL = PET.getPatternLoc();
1012 }
1013
1014 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1015 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1016 CXXScopeSpec SS;
1017 SS.Adopt(DTST.getQualifierLoc());
1018 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1019 TemplateTy::make(Name),
1020 DTST.getTemplateNameLoc());
1021 if (EllipsisLoc.isValid())
1022 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1023 return Result;
1024 }
1025 }
1026
1027 // This is a normal type template argument. Note, if the type template
1028 // argument is an injected-class-name for a template, it has a dual nature
1029 // and can be used as either a type or a template. We handle that in
1030 // convertTypeTemplateArgumentToTemplate.
1032 ParsedType.get().getAsOpaquePtr(),
1033 TInfo->getTypeLoc().getBeginLoc());
1034}
1035
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1050 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1051 KeyLoc, ParamNameLoc, Depth, Position,
1052 ParamName, Typename, IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *CSI = getEnclosingLambdaOrBlock())
1058 CSI->LocalPacks.push_back(Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(Param);
1065 IdResolver.AddDecl(Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(
1095 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1096 }
1097
1098 return Param;
1099}
1100
1101/// Convert the parser's template argument list representation into our form.
1104 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1105 TemplateId.RAngleLoc);
1106 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1107 TemplateId.NumArgs);
1108 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1109 return TemplateArgs;
1110}
1111
1113
1114 TemplateName TN = TypeConstr->Template.get();
1115 NamedDecl *CD = nullptr;
1116 bool IsTypeConcept = false;
1117 bool RequiresArguments = false;
1118 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1119 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1120 RequiresArguments =
1121 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1122 CD = TTP;
1123 } else {
1124 CD = TN.getAsTemplateDecl();
1125 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1126 RequiresArguments = cast<ConceptDecl>(CD)
1127 ->getTemplateParameters()
1128 ->getMinRequiredArguments() > 1;
1129 }
1130
1131 // C++2a [temp.param]p4:
1132 // [...] The concept designated by a type-constraint shall be a type
1133 // concept ([temp.concept]).
1134 if (!IsTypeConcept) {
1135 Diag(TypeConstr->TemplateNameLoc,
1136 diag::err_type_constraint_non_type_concept);
1137 return true;
1138 }
1139
1140 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1141 return true;
1142
1143 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1144
1145 if (!WereArgsSpecified && RequiresArguments) {
1146 Diag(TypeConstr->TemplateNameLoc,
1147 diag::err_type_constraint_missing_arguments)
1148 << CD;
1149 return true;
1150 }
1151 return false;
1152}
1153
1155 TemplateIdAnnotation *TypeConstr,
1156 TemplateTypeParmDecl *ConstrainedParameter,
1157 SourceLocation EllipsisLoc) {
1158 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1159 false);
1160}
1161
1163 TemplateIdAnnotation *TypeConstr,
1164 TemplateTypeParmDecl *ConstrainedParameter,
1165 SourceLocation EllipsisLoc,
1166 bool AllowUnexpandedPack) {
1167
1168 if (CheckTypeConstraint(TypeConstr))
1169 return true;
1170
1171 TemplateName TN = TypeConstr->Template.get();
1174
1175 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1176 TypeConstr->TemplateNameLoc);
1177
1178 TemplateArgumentListInfo TemplateArgs;
1179 if (TypeConstr->LAngleLoc.isValid()) {
1180 TemplateArgs =
1181 makeTemplateArgumentListInfo(*this, *TypeConstr);
1182
1183 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1184 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1186 return true;
1187 }
1188 }
1189 }
1190 return AttachTypeConstraint(
1192 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1193 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1194 ConstrainedParameter, EllipsisLoc);
1195}
1196
1197template <typename ArgumentLocAppender>
1200 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1201 SourceLocation RAngleLoc, QualType ConstrainedType,
1202 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1203 SourceLocation EllipsisLoc) {
1204
1205 TemplateArgumentListInfo ConstraintArgs;
1206 ConstraintArgs.addArgument(
1208 /*NTTPType=*/QualType(), ParamNameLoc));
1209
1210 ConstraintArgs.setRAngleLoc(RAngleLoc);
1211 ConstraintArgs.setLAngleLoc(LAngleLoc);
1212 Appender(ConstraintArgs);
1213
1214 // C++2a [temp.param]p4:
1215 // [...] This constraint-expression E is called the immediately-declared
1216 // constraint of T. [...]
1217 CXXScopeSpec SS;
1218 SS.Adopt(NS);
1219 ExprResult ImmediatelyDeclaredConstraint;
1220 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1221 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1222 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1223 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1224 /*DoCheckConstraintSatisfaction=*/
1226 }
1227 // We have a template template parameter
1228 else {
1229 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1230 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1231 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1232 }
1233 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1234 return ImmediatelyDeclaredConstraint;
1235
1236 // C++2a [temp.param]p4:
1237 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1238 //
1239 // We have the following case:
1240 //
1241 // template<typename T> concept C1 = true;
1242 // template<C1... T> struct s1;
1243 //
1244 // The constraint: (C1<T> && ...)
1245 //
1246 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1247 // any unqualified lookups for 'operator&&' here.
1248 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1249 /*LParenLoc=*/SourceLocation(),
1250 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1251 EllipsisLoc, /*RHS=*/nullptr,
1252 /*RParenLoc=*/SourceLocation(),
1253 /*NumExpansions=*/std::nullopt);
1254}
1255
1257 DeclarationNameInfo NameInfo,
1258 TemplateDecl *NamedConcept,
1259 NamedDecl *FoundDecl,
1260 const TemplateArgumentListInfo *TemplateArgs,
1261 TemplateTypeParmDecl *ConstrainedParameter,
1262 SourceLocation EllipsisLoc) {
1263 // C++2a [temp.param]p4:
1264 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1265 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1266 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1268 *TemplateArgs) : nullptr;
1269
1270 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1271
1272 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1273 *this, NS, NameInfo, NamedConcept, FoundDecl,
1274 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1275 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1276 ParamAsArgument, ConstrainedParameter->getLocation(),
1277 [&](TemplateArgumentListInfo &ConstraintArgs) {
1278 if (TemplateArgs)
1279 for (const auto &ArgLoc : TemplateArgs->arguments())
1280 ConstraintArgs.addArgument(ArgLoc);
1281 },
1282 EllipsisLoc);
1283 if (ImmediatelyDeclaredConstraint.isInvalid())
1284 return true;
1285
1286 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1287 /*TemplateKWLoc=*/SourceLocation{},
1288 /*ConceptNameInfo=*/NameInfo,
1289 /*FoundDecl=*/FoundDecl,
1290 /*NamedConcept=*/NamedConcept,
1291 /*ArgsWritten=*/ArgsAsWritten);
1292 ConstrainedParameter->setTypeConstraint(
1293 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1294 return false;
1295}
1296
1298 NonTypeTemplateParmDecl *NewConstrainedParm,
1299 NonTypeTemplateParmDecl *OrigConstrainedParm,
1300 SourceLocation EllipsisLoc) {
1301 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1303 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1304 diag::err_unsupported_placeholder_constraint)
1305 << NewConstrainedParm->getTypeSourceInfo()
1306 ->getTypeLoc()
1307 .getSourceRange();
1308 return true;
1309 }
1310 // FIXME: Concepts: This should be the type of the placeholder, but this is
1311 // unclear in the wording right now.
1312 DeclRefExpr *Ref =
1313 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1314 VK_PRValue, OrigConstrainedParm->getLocation());
1315 if (!Ref)
1316 return true;
1317 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1319 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1321 OrigConstrainedParm->getLocation(),
1322 [&](TemplateArgumentListInfo &ConstraintArgs) {
1323 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1324 ConstraintArgs.addArgument(TL.getArgLoc(I));
1325 },
1326 EllipsisLoc);
1327 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1328 !ImmediatelyDeclaredConstraint.isUsable())
1329 return true;
1330
1331 NewConstrainedParm->setPlaceholderTypeConstraint(
1332 ImmediatelyDeclaredConstraint.get());
1333 return false;
1334}
1335
1337 SourceLocation Loc) {
1338 if (TSI->getType()->isUndeducedType()) {
1339 // C++17 [temp.dep.expr]p3:
1340 // An id-expression is type-dependent if it contains
1341 // - an identifier associated by name lookup with a non-type
1342 // template-parameter declared with a type that contains a
1343 // placeholder type (7.1.7.4),
1345 if (!NewTSI)
1346 return QualType();
1347 TSI = NewTSI;
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1351}
1352
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(SubLoc, diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 if (T->isBlockPointerType()) {
1463 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1464 return QualType();
1465 }
1466
1467 // C++ [temp.param]p4:
1468 //
1469 // A non-type template-parameter shall have one of the following
1470 // (optionally cv-qualified) types:
1471 //
1472 // -- integral or enumeration type,
1473 if (T->isIntegralOrEnumerationType() ||
1474 // -- pointer to object or pointer to function,
1475 T->isPointerType() ||
1476 // -- lvalue reference to object or lvalue reference to function,
1477 T->isLValueReferenceType() ||
1478 // -- pointer to member,
1479 T->isMemberPointerType() ||
1480 // -- std::nullptr_t, or
1481 T->isNullPtrType() ||
1482 // -- a type that contains a placeholder type.
1483 T->isUndeducedType()) {
1484 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1485 // are ignored when determining its type.
1486 return T.getUnqualifiedType();
1487 }
1488
1489 // C++ [temp.param]p8:
1490 //
1491 // A non-type template-parameter of type "array of T" or
1492 // "function returning T" is adjusted to be of type "pointer to
1493 // T" or "pointer to function returning T", respectively.
1494 if (T->isArrayType() || T->isFunctionType())
1495 return Context.getDecayedType(T);
1496
1497 // If T is a dependent type, we can't do the check now, so we
1498 // assume that it is well-formed. Note that stripping off the
1499 // qualifiers here is not really correct if T turns out to be
1500 // an array type, but we'll recompute the type everywhere it's
1501 // used during instantiation, so that should be OK. (Using the
1502 // qualified type is equally wrong.)
1503 if (T->isDependentType())
1504 return T.getUnqualifiedType();
1505
1506 // C++20 [temp.param]p6:
1507 // -- a structural type
1508 if (RequireStructuralType(T, Loc))
1509 return QualType();
1510
1511 if (!getLangOpts().CPlusPlus20) {
1512 // FIXME: Consider allowing structural types as an extension in C++17. (In
1513 // earlier language modes, the template argument evaluation rules are too
1514 // inflexible.)
1515 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1516 return QualType();
1517 }
1518
1519 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1520 return T.getUnqualifiedType();
1521}
1522
1524 unsigned Depth,
1525 unsigned Position,
1526 SourceLocation EqualLoc,
1527 Expr *Default) {
1529
1530 // Check that we have valid decl-specifiers specified.
1531 auto CheckValidDeclSpecifiers = [this, &D] {
1532 // C++ [temp.param]
1533 // p1
1534 // template-parameter:
1535 // ...
1536 // parameter-declaration
1537 // p2
1538 // ... A storage class shall not be specified in a template-parameter
1539 // declaration.
1540 // [dcl.typedef]p1:
1541 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1542 // of a parameter-declaration
1543 const DeclSpec &DS = D.getDeclSpec();
1544 auto EmitDiag = [this](SourceLocation Loc) {
1545 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1547 };
1549 EmitDiag(DS.getStorageClassSpecLoc());
1550
1552 EmitDiag(DS.getThreadStorageClassSpecLoc());
1553
1554 // [dcl.inline]p1:
1555 // The inline specifier can be applied only to the declaration or
1556 // definition of a variable or function.
1557
1558 if (DS.isInlineSpecified())
1559 EmitDiag(DS.getInlineSpecLoc());
1560
1561 // [dcl.constexpr]p1:
1562 // The constexpr specifier shall be applied only to the definition of a
1563 // variable or variable template or the declaration of a function or
1564 // function template.
1565
1566 if (DS.hasConstexprSpecifier())
1567 EmitDiag(DS.getConstexprSpecLoc());
1568
1569 // [dcl.fct.spec]p1:
1570 // Function-specifiers can be used only in function declarations.
1571
1572 if (DS.isVirtualSpecified())
1573 EmitDiag(DS.getVirtualSpecLoc());
1574
1575 if (DS.hasExplicitSpecifier())
1576 EmitDiag(DS.getExplicitSpecLoc());
1577
1578 if (DS.isNoreturnSpecified())
1579 EmitDiag(DS.getNoreturnSpecLoc());
1580 };
1581
1582 CheckValidDeclSpecifiers();
1583
1584 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1585 if (isa<AutoType>(T))
1587 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1588 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1589
1590 assert(S->isTemplateParamScope() &&
1591 "Non-type template parameter not in template parameter scope!");
1592 bool Invalid = false;
1593
1595 if (T.isNull()) {
1596 T = Context.IntTy; // Recover with an 'int' type.
1597 Invalid = true;
1598 }
1599
1601
1602 const IdentifierInfo *ParamName = D.getIdentifier();
1603 bool IsParameterPack = D.hasEllipsis();
1605 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1606 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1607 TInfo);
1608 Param->setAccess(AS_public);
1609
1611 if (TL.isConstrained()) {
1612 if (D.getEllipsisLoc().isInvalid() &&
1613 T->containsUnexpandedParameterPack()) {
1614 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1615 for (auto &Loc :
1616 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1619 }
1620 if (!Invalid &&
1621 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1622 Invalid = true;
1623 }
1624
1625 if (Invalid)
1626 Param->setInvalidDecl();
1627
1628 if (Param->isParameterPack())
1629 if (auto *CSI = getEnclosingLambdaOrBlock())
1630 CSI->LocalPacks.push_back(Param);
1631
1632 if (ParamName) {
1634 ParamName);
1635
1636 // Add the template parameter into the current scope.
1637 S->AddDecl(Param);
1638 IdResolver.AddDecl(Param);
1639 }
1640
1641 // C++0x [temp.param]p9:
1642 // A default template-argument may be specified for any kind of
1643 // template-parameter that is not a template parameter pack.
1644 if (Default && IsParameterPack) {
1645 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1646 Default = nullptr;
1647 }
1648
1649 // Check the well-formedness of the default template argument, if provided.
1650 if (Default) {
1651 // Check for unexpanded parameter packs.
1653 return Param;
1654
1655 Param->setDefaultArgument(
1657 TemplateArgument(Default, /*IsCanonical=*/false),
1658 QualType(), SourceLocation()));
1659 }
1660
1661 return Param;
1662}
1663
1664/// ActOnTemplateTemplateParameter - Called when a C++ template template
1665/// parameter (e.g. T in template <template <typename> class T> class array)
1666/// has been parsed. S is the current scope.
1668 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1669 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1670 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1671 unsigned Position, SourceLocation EqualLoc,
1673 assert(S->isTemplateParamScope() &&
1674 "Template template parameter not in template parameter scope!");
1675
1676 bool IsParameterPack = EllipsisLoc.isValid();
1677
1678 bool Invalid = false;
1680 Params,
1681 /*OldParams=*/nullptr,
1682 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1683 Invalid = true;
1684
1685 // Construct the parameter object.
1687 Context, Context.getTranslationUnitDecl(),
1688 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1689 Name, Kind, Typename, Params);
1690 Param->setAccess(AS_public);
1691
1692 if (Param->isParameterPack())
1693 if (auto *LSI = getEnclosingLambdaOrBlock())
1694 LSI->LocalPacks.push_back(Param);
1695
1696 // If the template template parameter has a name, then link the identifier
1697 // into the scope and lookup mechanisms.
1698 if (Name) {
1699 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1700
1701 S->AddDecl(Param);
1702 IdResolver.AddDecl(Param);
1703 }
1704
1705 if (Params->size() == 0) {
1706 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1707 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1708 Invalid = true;
1709 }
1710
1711 if (Invalid)
1712 Param->setInvalidDecl();
1713
1714 // C++0x [temp.param]p9:
1715 // A default template-argument may be specified for any kind of
1716 // template-parameter that is not a template parameter pack.
1717 if (IsParameterPack && !Default.isInvalid()) {
1718 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1720 }
1721
1722 if (!Default.isInvalid()) {
1723 // Check only that we have a template template argument. We don't want to
1724 // try to check well-formedness now, because our template template parameter
1725 // might have dependent types in its template parameters, which we wouldn't
1726 // be able to match now.
1727 //
1728 // If none of the template template parameter's template arguments mention
1729 // other template parameters, we could actually perform more checking here.
1730 // However, it isn't worth doing.
1732 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1733 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1734 << DefaultArg.getSourceRange();
1735 return Param;
1736 }
1737
1738 TemplateName Name =
1741 if (Template &&
1743 return Param;
1744 }
1745
1746 // Check for unexpanded parameter packs.
1748 DefaultArg.getArgument().getAsTemplate(),
1750 return Param;
1751
1752 Param->setDefaultArgument(Context, DefaultArg);
1753 }
1754
1755 return Param;
1756}
1757
1758namespace {
1759class ConstraintRefersToContainingTemplateChecker
1761 using inherited = ConstDynamicRecursiveASTVisitor;
1762 bool Result = false;
1763 const FunctionDecl *Friend = nullptr;
1764 unsigned TemplateDepth = 0;
1765
1766 // Check a record-decl that we've seen to see if it is a lexical parent of the
1767 // Friend, likely because it was referred to without its template arguments.
1768 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1769 CheckingRD = CheckingRD->getMostRecentDecl();
1770 if (!CheckingRD->isTemplated())
1771 return true;
1772
1773 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1774 DC && !DC->isFileContext(); DC = DC->getParent())
1775 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1776 if (CheckingRD == RD->getMostRecentDecl()) {
1777 Result = true;
1778 return false;
1779 }
1780
1781 return true;
1782 }
1783
1784 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1785 if (D->getDepth() < TemplateDepth)
1786 Result = true;
1787
1788 // Necessary because the type of the NTTP might be what refers to the parent
1789 // constriant.
1790 return TraverseType(D->getType());
1791 }
1792
1793public:
1794 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1795 unsigned TemplateDepth)
1796 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1797
1798 bool getResult() const { return Result; }
1799
1800 // This should be the only template parm type that we have to deal with.
1801 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1802 // FunctionParmPackExpr are all partially substituted, which cannot happen
1803 // with concepts at this point in translation.
1804 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1805 if (Type->getDecl()->getDepth() < TemplateDepth) {
1806 Result = true;
1807 return false;
1808 }
1809 return true;
1810 }
1811
1812 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1813 return TraverseDecl(E->getDecl());
1814 }
1815
1816 bool TraverseTypedefType(const TypedefType *TT,
1817 bool /*TraverseQualifier*/) override {
1818 return TraverseType(TT->desugar());
1819 }
1820
1821 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1822 // We don't care about TypeLocs. So traverse Types instead.
1823 return TraverseType(TL.getType(), TraverseQualifier);
1824 }
1825
1826 bool VisitTagType(const TagType *T) override {
1827 return TraverseDecl(T->getDecl());
1828 }
1829
1830 bool TraverseDecl(const Decl *D) override {
1831 assert(D);
1832 // FIXME : This is possibly an incomplete list, but it is unclear what other
1833 // Decl kinds could be used to refer to the template parameters. This is a
1834 // best guess so far based on examples currently available, but the
1835 // unreachable should catch future instances/cases.
1836 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1837 return TraverseType(TD->getUnderlyingType());
1838 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1839 return CheckNonTypeTemplateParmDecl(NTTPD);
1840 if (auto *VD = dyn_cast<ValueDecl>(D))
1841 return TraverseType(VD->getType());
1842 if (isa<TemplateDecl>(D))
1843 return true;
1844 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1845 return CheckIfContainingRecord(RD);
1846
1848 // No direct types to visit here I believe.
1849 } else
1850 llvm_unreachable("Don't know how to handle this declaration type yet");
1851 return true;
1852 }
1853};
1854} // namespace
1855
1857 const FunctionDecl *Friend, unsigned TemplateDepth,
1858 const Expr *Constraint) {
1859 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1860 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1861 Checker.TraverseStmt(Constraint);
1862 return Checker.getResult();
1863}
1864
1867 SourceLocation ExportLoc,
1868 SourceLocation TemplateLoc,
1869 SourceLocation LAngleLoc,
1870 ArrayRef<NamedDecl *> Params,
1871 SourceLocation RAngleLoc,
1872 Expr *RequiresClause) {
1873 if (ExportLoc.isValid())
1874 Diag(ExportLoc, diag::warn_template_export_unsupported);
1875
1876 for (NamedDecl *P : Params)
1878
1879 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1880 llvm::ArrayRef(Params), RAngleLoc,
1881 RequiresClause);
1882}
1883
1885 const CXXScopeSpec &SS) {
1886 if (SS.isSet())
1887 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1888}
1889
1890// Returns the template parameter list with all default template argument
1891// information.
1893 // Make sure we get the template parameter list from the most
1894 // recent declaration, since that is the only one that is guaranteed to
1895 // have all the default template argument information.
1896 Decl *D = TD->getMostRecentDecl();
1897 // C++11 N3337 [temp.param]p12:
1898 // A default template argument shall not be specified in a friend class
1899 // template declaration.
1900 //
1901 // Skip past friend *declarations* because they are not supposed to contain
1902 // default template arguments. Moreover, these declarations may introduce
1903 // template parameters living in different template depths than the
1904 // corresponding template parameters in TD, causing unmatched constraint
1905 // substitution.
1906 //
1907 // FIXME: Diagnose such cases within a class template:
1908 // template <class T>
1909 // struct S {
1910 // template <class = void> friend struct C;
1911 // };
1912 // template struct S<int>;
1914 D->getPreviousDecl())
1915 D = D->getPreviousDecl();
1916 return cast<TemplateDecl>(D)->getTemplateParameters();
1917}
1918
1920 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1921 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1922 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1923 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1924 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1925 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1926 assert(TemplateParams && TemplateParams->size() > 0 &&
1927 "No template parameters");
1928 assert(TUK != TagUseKind::Reference &&
1929 "Can only declare or define class templates");
1930 bool Invalid = false;
1931
1932 // Check that we can declare a template here.
1933 if (CheckTemplateDeclScope(S, TemplateParams))
1934 return true;
1935
1937 assert(Kind != TagTypeKind::Enum &&
1938 "can't build template of enumerated type");
1939
1940 // There is no such thing as an unnamed class template.
1941 if (!Name) {
1942 Diag(KWLoc, diag::err_template_unnamed_class);
1943 return true;
1944 }
1945
1946 // Find any previous declaration with this name. For a friend with no
1947 // scope explicitly specified, we only look for tag declarations (per
1948 // C++11 [basic.lookup.elab]p2).
1949 DeclContext *SemanticContext;
1950 LookupResult Previous(*this, Name, NameLoc,
1951 (SS.isEmpty() && TUK == TagUseKind::Friend)
1955 if (SS.isNotEmpty() && !SS.isInvalid()) {
1956 SemanticContext = computeDeclContext(SS, true);
1957 if (!SemanticContext) {
1958 // FIXME: Horrible, horrible hack! We can't currently represent this
1959 // in the AST, and historically we have just ignored such friend
1960 // class templates, so don't complain here.
1961 Diag(NameLoc, TUK == TagUseKind::Friend
1962 ? diag::warn_template_qualified_friend_ignored
1963 : diag::err_template_qualified_declarator_no_match)
1964 << SS.getScopeRep() << SS.getRange();
1965 return TUK != TagUseKind::Friend;
1966 }
1967
1968 if (RequireCompleteDeclContext(SS, SemanticContext))
1969 return true;
1970
1971 // If we're adding a template to a dependent context, we may need to
1972 // rebuilding some of the types used within the template parameter list,
1973 // now that we know what the current instantiation is.
1974 if (SemanticContext->isDependentContext()) {
1975 ContextRAII SavedContext(*this, SemanticContext);
1977 Invalid = true;
1978 }
1979
1980 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1981 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1982 /*TemplateId-*/ nullptr,
1983 /*IsMemberSpecialization*/ false);
1984
1985 LookupQualifiedName(Previous, SemanticContext);
1986 } else {
1987 SemanticContext = CurContext;
1988
1989 // C++14 [class.mem]p14:
1990 // If T is the name of a class, then each of the following shall have a
1991 // name different from T:
1992 // -- every member template of class T
1993 if (TUK != TagUseKind::Friend &&
1994 DiagnoseClassNameShadow(SemanticContext,
1995 DeclarationNameInfo(Name, NameLoc)))
1996 return true;
1997
1998 LookupName(Previous, S);
1999 }
2000
2001 if (Previous.isAmbiguous())
2002 return true;
2003
2004 // Let the template parameter scope enter the lookup chain of the current
2005 // class template. For example, given
2006 //
2007 // namespace ns {
2008 // template <class> bool Param = false;
2009 // template <class T> struct N;
2010 // }
2011 //
2012 // template <class Param> struct ns::N { void foo(Param); };
2013 //
2014 // When we reference Param inside the function parameter list, our name lookup
2015 // chain for it should be like:
2016 // FunctionScope foo
2017 // -> RecordScope N
2018 // -> TemplateParamScope (where we will find Param)
2019 // -> NamespaceScope ns
2020 //
2021 // See also CppLookupName().
2022 if (S->isTemplateParamScope())
2023 EnterTemplatedContext(S, SemanticContext);
2024
2025 NamedDecl *PrevDecl = nullptr;
2026 if (Previous.begin() != Previous.end())
2027 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2028
2029 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2030 // Maybe we will complain about the shadowed template parameter.
2031 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2032 // Just pretend that we didn't see the previous declaration.
2033 PrevDecl = nullptr;
2034 }
2035
2036 // If there is a previous declaration with the same name, check
2037 // whether this is a valid redeclaration.
2038 ClassTemplateDecl *PrevClassTemplate =
2039 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2040
2041 // We may have found the injected-class-name of a class template,
2042 // class template partial specialization, or class template specialization.
2043 // In these cases, grab the template that is being defined or specialized.
2044 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2045 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2046 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2047 PrevClassTemplate
2048 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2049 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2050 PrevClassTemplate
2052 ->getSpecializedTemplate();
2053 }
2054 }
2055
2056 if (TUK == TagUseKind::Friend) {
2057 // C++ [namespace.memdef]p3:
2058 // [...] When looking for a prior declaration of a class or a function
2059 // declared as a friend, and when the name of the friend class or
2060 // function is neither a qualified name nor a template-id, scopes outside
2061 // the innermost enclosing namespace scope are not considered.
2062 if (!SS.isSet()) {
2063 DeclContext *OutermostContext = CurContext;
2064 while (!OutermostContext->isFileContext())
2065 OutermostContext = OutermostContext->getLookupParent();
2066
2067 if (PrevDecl &&
2068 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2069 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2070 SemanticContext = PrevDecl->getDeclContext();
2071 } else {
2072 // Declarations in outer scopes don't matter. However, the outermost
2073 // context we computed is the semantic context for our new
2074 // declaration.
2075 PrevDecl = PrevClassTemplate = nullptr;
2076 SemanticContext = OutermostContext;
2077
2078 // Check that the chosen semantic context doesn't already contain a
2079 // declaration of this name as a non-tag type.
2081 DeclContext *LookupContext = SemanticContext;
2082 while (LookupContext->isTransparentContext())
2083 LookupContext = LookupContext->getLookupParent();
2084 LookupQualifiedName(Previous, LookupContext);
2085
2086 if (Previous.isAmbiguous())
2087 return true;
2088
2089 if (Previous.begin() != Previous.end())
2090 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2091 }
2092 }
2093 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2094 SemanticContext, S, SS.isValid()))
2095 PrevDecl = PrevClassTemplate = nullptr;
2096
2097 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2098 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2099 if (SS.isEmpty() &&
2100 !(PrevClassTemplate &&
2101 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2102 SemanticContext->getRedeclContext()))) {
2103 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2104 Diag(Shadow->getTargetDecl()->getLocation(),
2105 diag::note_using_decl_target);
2106 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2107 // Recover by ignoring the old declaration.
2108 PrevDecl = PrevClassTemplate = nullptr;
2109 }
2110 }
2111
2112 if (PrevClassTemplate) {
2113 // Ensure that the template parameter lists are compatible. Skip this check
2114 // for a friend in a dependent context: the template parameter list itself
2115 // could be dependent.
2116 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2118 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2119 : CurContext,
2120 CurContext, KWLoc),
2121 TemplateParams, PrevClassTemplate,
2122 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2124 return true;
2125
2126 // C++ [temp.class]p4:
2127 // In a redeclaration, partial specialization, explicit
2128 // specialization or explicit instantiation of a class template,
2129 // the class-key shall agree in kind with the original class
2130 // template declaration (7.1.5.3).
2131 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2133 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2134 Diag(KWLoc, diag::err_use_with_wrong_tag)
2135 << Name
2136 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2137 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2138 Kind = PrevRecordDecl->getTagKind();
2139 }
2140
2141 // Check for redefinition of this class template.
2142 if (TUK == TagUseKind::Definition) {
2143 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2144 // If we have a prior definition that is not visible, treat this as
2145 // simply making that previous definition visible.
2146 NamedDecl *Hidden = nullptr;
2147 bool HiddenDefVisible = false;
2148 if (SkipBody &&
2149 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2150 SkipBody->ShouldSkip = true;
2151 SkipBody->Previous = Def;
2152 if (!HiddenDefVisible && Hidden) {
2153 auto *Tmpl =
2154 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2155 assert(Tmpl && "original definition of a class template is not a "
2156 "class template?");
2159 }
2160 } else {
2161 Diag(NameLoc, diag::err_redefinition) << Name;
2162 Diag(Def->getLocation(), diag::note_previous_definition);
2163 // FIXME: Would it make sense to try to "forget" the previous
2164 // definition, as part of error recovery?
2165 return true;
2166 }
2167 }
2168 }
2169 } else if (PrevDecl) {
2170 // C++ [temp]p5:
2171 // A class template shall not have the same name as any other
2172 // template, class, function, object, enumeration, enumerator,
2173 // namespace, or type in the same scope (3.3), except as specified
2174 // in (14.5.4).
2175 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2176 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2177 return true;
2178 }
2179
2180 // Check the template parameter list of this declaration, possibly
2181 // merging in the template parameter list from the previous class
2182 // template declaration. Skip this check for a friend in a dependent
2183 // context, because the template parameter list might be dependent.
2184 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2186 TemplateParams,
2187 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2188 : nullptr,
2189 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2190 SemanticContext->isDependentContext())
2193 : TPC_Other,
2194 SkipBody))
2195 Invalid = true;
2196
2197 if (SS.isSet()) {
2198 // If the name of the template was qualified, we must be defining the
2199 // template out-of-line.
2200 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2201 Diag(NameLoc, TUK == TagUseKind::Friend
2202 ? diag::err_friend_decl_does_not_match
2203 : diag::err_member_decl_does_not_match)
2204 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2205 Invalid = true;
2206 }
2207 }
2208
2209 // If this is a templated friend in a dependent context we should not put it
2210 // on the redecl chain. In some cases, the templated friend can be the most
2211 // recent declaration tricking the template instantiator to make substitutions
2212 // there.
2213 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2214 bool ShouldAddRedecl =
2215 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2216
2218 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2219 PrevClassTemplate && ShouldAddRedecl
2220 ? PrevClassTemplate->getTemplatedDecl()
2221 : nullptr);
2222 SetNestedNameSpecifier(*this, NewClass, SS);
2223 if (NumOuterTemplateParamLists > 0)
2225 Context,
2226 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2227
2228 // Add alignment attributes if necessary; these attributes are checked when
2229 // the ASTContext lays out the structure.
2230 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2231 if (LangOpts.HLSL)
2232 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2235 }
2236
2237 ClassTemplateDecl *NewTemplate
2238 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2239 DeclarationName(Name), TemplateParams,
2240 NewClass);
2241
2242 if (ShouldAddRedecl)
2243 NewTemplate->setPreviousDecl(PrevClassTemplate);
2244
2245 NewClass->setDescribedClassTemplate(NewTemplate);
2246
2247 if (ModulePrivateLoc.isValid())
2248 NewTemplate->setModulePrivate();
2249
2250 // If we are providing an explicit specialization of a member that is a
2251 // class template, make a note of that.
2252 if (PrevClassTemplate &&
2253 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2254 PrevClassTemplate->setMemberSpecialization();
2255
2256 // Set the access specifier.
2257 if (!Invalid && TUK != TagUseKind::Friend &&
2258 NewTemplate->getDeclContext()->isRecord())
2259 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2260
2261 // Set the lexical context of these templates
2263 NewTemplate->setLexicalDeclContext(CurContext);
2264
2265 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2266 NewClass->startDefinition();
2267
2268 ProcessDeclAttributeList(S, NewClass, Attr);
2269
2270 if (PrevClassTemplate)
2271 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2272
2276
2277 if (TUK != TagUseKind::Friend) {
2278 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2279 Scope *Outer = S;
2280 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2281 Outer = Outer->getParent();
2282 PushOnScopeChains(NewTemplate, Outer);
2283 } else {
2284 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2285 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2286 NewClass->setAccess(PrevClassTemplate->getAccess());
2287 }
2288
2289 NewTemplate->setObjectOfFriendDecl();
2290
2291 // Friend templates are visible in fairly strange ways.
2292 if (!CurContext->isDependentContext()) {
2293 DeclContext *DC = SemanticContext->getRedeclContext();
2294 DC->makeDeclVisibleInContext(NewTemplate);
2295 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2296 PushOnScopeChains(NewTemplate, EnclosingScope,
2297 /* AddToContext = */ false);
2298 }
2299
2301 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2302 Friend->setAccess(AS_public);
2303 CurContext->addDecl(Friend);
2304 }
2305
2306 if (PrevClassTemplate)
2307 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2308
2309 if (Invalid) {
2310 NewTemplate->setInvalidDecl();
2311 NewClass->setInvalidDecl();
2312 }
2313
2314 ActOnDocumentableDecl(NewTemplate);
2315
2316 if (SkipBody && SkipBody->ShouldSkip)
2317 return SkipBody->Previous;
2318
2319 return NewTemplate;
2320}
2321
2322/// Diagnose the presence of a default template argument on a
2323/// template parameter, which is ill-formed in certain contexts.
2324///
2325/// \returns true if the default template argument should be dropped.
2328 SourceLocation ParamLoc,
2329 SourceRange DefArgRange) {
2330 switch (TPC) {
2331 case Sema::TPC_Other:
2333 return false;
2334
2337 // C++ [temp.param]p9:
2338 // A default template-argument shall not be specified in a
2339 // function template declaration or a function template
2340 // definition [...]
2341 // If a friend function template declaration specifies a default
2342 // template-argument, that declaration shall be a definition and shall be
2343 // the only declaration of the function template in the translation unit.
2344 // (C++98/03 doesn't have this wording; see DR226).
2345 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2346 << DefArgRange;
2347 return false;
2348
2350 // C++0x [temp.param]p9:
2351 // A default template-argument shall not be specified in the
2352 // template-parameter-lists of the definition of a member of a
2353 // class template that appears outside of the member's class.
2354 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2355 << DefArgRange;
2356 return true;
2357
2360 // C++ [temp.param]p9:
2361 // A default template-argument shall not be specified in a
2362 // friend template declaration.
2363 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2364 << DefArgRange;
2365 return true;
2366
2367 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2368 // for friend function templates if there is only a single
2369 // declaration (and it is a definition). Strange!
2370 }
2371
2372 llvm_unreachable("Invalid TemplateParamListContext!");
2373}
2374
2375/// Check for unexpanded parameter packs within the template parameters
2376/// of a template template parameter, recursively.
2379 // A template template parameter which is a parameter pack is also a pack
2380 // expansion.
2381 if (TTP->isParameterPack())
2382 return false;
2383
2385 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2386 NamedDecl *P = Params->getParam(I);
2387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2388 if (!TTP->isParameterPack())
2389 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2390 if (TC->hasExplicitTemplateArgs())
2391 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2394 return true;
2395 continue;
2396 }
2397
2398 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2399 if (!NTTP->isParameterPack() &&
2400 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2401 NTTP->getTypeSourceInfo(),
2403 return true;
2404
2405 continue;
2406 }
2407
2408 if (TemplateTemplateParmDecl *InnerTTP
2409 = dyn_cast<TemplateTemplateParmDecl>(P))
2410 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2411 return true;
2412 }
2413
2414 return false;
2415}
2416
2418 TemplateParameterList *OldParams,
2420 SkipBodyInfo *SkipBody) {
2421 bool Invalid = false;
2422
2423 // C++ [temp.param]p10:
2424 // The set of default template-arguments available for use with a
2425 // template declaration or definition is obtained by merging the
2426 // default arguments from the definition (if in scope) and all
2427 // declarations in scope in the same way default function
2428 // arguments are (8.3.6).
2429 bool SawDefaultArgument = false;
2430 SourceLocation PreviousDefaultArgLoc;
2431
2432 // Dummy initialization to avoid warnings.
2433 TemplateParameterList::iterator OldParam = NewParams->end();
2434 if (OldParams)
2435 OldParam = OldParams->begin();
2436
2437 bool RemoveDefaultArguments = false;
2438 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2439 NewParamEnd = NewParams->end();
2440 NewParam != NewParamEnd; ++NewParam) {
2441 // Whether we've seen a duplicate default argument in the same translation
2442 // unit.
2443 bool RedundantDefaultArg = false;
2444 // Whether we've found inconsis inconsitent default arguments in different
2445 // translation unit.
2446 bool InconsistentDefaultArg = false;
2447 // The name of the module which contains the inconsistent default argument.
2448 std::string PrevModuleName;
2449
2450 SourceLocation OldDefaultLoc;
2451 SourceLocation NewDefaultLoc;
2452
2453 // Variable used to diagnose missing default arguments
2454 bool MissingDefaultArg = false;
2455
2456 // Variable used to diagnose non-final parameter packs
2457 bool SawParameterPack = false;
2458
2459 if (TemplateTypeParmDecl *NewTypeParm
2460 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2461 // Check the presence of a default argument here.
2462 if (NewTypeParm->hasDefaultArgument() &&
2464 *this, TPC, NewTypeParm->getLocation(),
2465 NewTypeParm->getDefaultArgument().getSourceRange()))
2466 NewTypeParm->removeDefaultArgument();
2467
2468 // Merge default arguments for template type parameters.
2469 TemplateTypeParmDecl *OldTypeParm
2470 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2471 if (NewTypeParm->isParameterPack()) {
2472 assert(!NewTypeParm->hasDefaultArgument() &&
2473 "Parameter packs can't have a default argument!");
2474 SawParameterPack = true;
2475 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2476 NewTypeParm->hasDefaultArgument() &&
2477 (!SkipBody || !SkipBody->ShouldSkip)) {
2478 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2479 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2480 SawDefaultArgument = true;
2481
2482 if (!OldTypeParm->getOwningModule())
2483 RedundantDefaultArg = true;
2484 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2485 NewTypeParm)) {
2486 InconsistentDefaultArg = true;
2487 PrevModuleName =
2489 }
2490 PreviousDefaultArgLoc = NewDefaultLoc;
2491 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2492 // Merge the default argument from the old declaration to the
2493 // new declaration.
2494 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2495 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2496 } else if (NewTypeParm->hasDefaultArgument()) {
2497 SawDefaultArgument = true;
2498 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2499 } else if (SawDefaultArgument)
2500 MissingDefaultArg = true;
2501 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2502 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2503 // Check for unexpanded parameter packs, except in a template template
2504 // parameter pack, as in those any unexpanded packs should be expanded
2505 // along with the parameter itself.
2507 !NewNonTypeParm->isParameterPack() &&
2508 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2509 NewNonTypeParm->getTypeSourceInfo(),
2511 Invalid = true;
2512 continue;
2513 }
2514
2515 // Check the presence of a default argument here.
2516 if (NewNonTypeParm->hasDefaultArgument() &&
2518 *this, TPC, NewNonTypeParm->getLocation(),
2519 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2520 NewNonTypeParm->removeDefaultArgument();
2521 }
2522
2523 // Merge default arguments for non-type template parameters
2524 NonTypeTemplateParmDecl *OldNonTypeParm
2525 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2526 if (NewNonTypeParm->isParameterPack()) {
2527 assert(!NewNonTypeParm->hasDefaultArgument() &&
2528 "Parameter packs can't have a default argument!");
2529 if (!NewNonTypeParm->isPackExpansion())
2530 SawParameterPack = true;
2531 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2532 NewNonTypeParm->hasDefaultArgument() &&
2533 (!SkipBody || !SkipBody->ShouldSkip)) {
2534 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2535 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2536 SawDefaultArgument = true;
2537 if (!OldNonTypeParm->getOwningModule())
2538 RedundantDefaultArg = true;
2539 else if (!getASTContext().isSameDefaultTemplateArgument(
2540 OldNonTypeParm, NewNonTypeParm)) {
2541 InconsistentDefaultArg = true;
2542 PrevModuleName =
2543 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2544 }
2545 PreviousDefaultArgLoc = NewDefaultLoc;
2546 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2547 // Merge the default argument from the old declaration to the
2548 // new declaration.
2549 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2550 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2551 } else if (NewNonTypeParm->hasDefaultArgument()) {
2552 SawDefaultArgument = true;
2553 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2554 } else if (SawDefaultArgument)
2555 MissingDefaultArg = true;
2556 } else {
2557 TemplateTemplateParmDecl *NewTemplateParm
2558 = cast<TemplateTemplateParmDecl>(*NewParam);
2559
2560 // Check for unexpanded parameter packs, recursively.
2561 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2562 Invalid = true;
2563 continue;
2564 }
2565
2566 // Check the presence of a default argument here.
2567 if (NewTemplateParm->hasDefaultArgument() &&
2569 NewTemplateParm->getLocation(),
2570 NewTemplateParm->getDefaultArgument().getSourceRange()))
2571 NewTemplateParm->removeDefaultArgument();
2572
2573 // Merge default arguments for template template parameters
2574 TemplateTemplateParmDecl *OldTemplateParm
2575 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2576 if (NewTemplateParm->isParameterPack()) {
2577 assert(!NewTemplateParm->hasDefaultArgument() &&
2578 "Parameter packs can't have a default argument!");
2579 if (!NewTemplateParm->isPackExpansion())
2580 SawParameterPack = true;
2581 } else if (OldTemplateParm &&
2582 hasVisibleDefaultArgument(OldTemplateParm) &&
2583 NewTemplateParm->hasDefaultArgument() &&
2584 (!SkipBody || !SkipBody->ShouldSkip)) {
2585 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2586 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2587 SawDefaultArgument = true;
2588 if (!OldTemplateParm->getOwningModule())
2589 RedundantDefaultArg = true;
2590 else if (!getASTContext().isSameDefaultTemplateArgument(
2591 OldTemplateParm, NewTemplateParm)) {
2592 InconsistentDefaultArg = true;
2593 PrevModuleName =
2594 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2595 }
2596 PreviousDefaultArgLoc = NewDefaultLoc;
2597 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2598 // Merge the default argument from the old declaration to the
2599 // new declaration.
2600 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2601 PreviousDefaultArgLoc
2602 = OldTemplateParm->getDefaultArgument().getLocation();
2603 } else if (NewTemplateParm->hasDefaultArgument()) {
2604 SawDefaultArgument = true;
2605 PreviousDefaultArgLoc
2606 = NewTemplateParm->getDefaultArgument().getLocation();
2607 } else if (SawDefaultArgument)
2608 MissingDefaultArg = true;
2609 }
2610
2611 // C++11 [temp.param]p11:
2612 // If a template parameter of a primary class template or alias template
2613 // is a template parameter pack, it shall be the last template parameter.
2614 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2615 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2616 Diag((*NewParam)->getLocation(),
2617 diag::err_template_param_pack_must_be_last_template_parameter);
2618 Invalid = true;
2619 }
2620
2621 // [basic.def.odr]/13:
2622 // There can be more than one definition of a
2623 // ...
2624 // default template argument
2625 // ...
2626 // in a program provided that each definition appears in a different
2627 // translation unit and the definitions satisfy the [same-meaning
2628 // criteria of the ODR].
2629 //
2630 // Simply, the design of modules allows the definition of template default
2631 // argument to be repeated across translation unit. Note that the ODR is
2632 // checked elsewhere. But it is still not allowed to repeat template default
2633 // argument in the same translation unit.
2634 if (RedundantDefaultArg) {
2635 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2636 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2637 Invalid = true;
2638 } else if (InconsistentDefaultArg) {
2639 // We could only diagnose about the case that the OldParam is imported.
2640 // The case NewParam is imported should be handled in ASTReader.
2641 Diag(NewDefaultLoc,
2642 diag::err_template_param_default_arg_inconsistent_redefinition);
2643 Diag(OldDefaultLoc,
2644 diag::note_template_param_prev_default_arg_in_other_module)
2645 << PrevModuleName;
2646 Invalid = true;
2647 } else if (MissingDefaultArg &&
2648 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2649 TPC == TPC_FriendClassTemplate)) {
2650 // C++ 23[temp.param]p14:
2651 // If a template-parameter of a class template, variable template, or
2652 // alias template has a default template argument, each subsequent
2653 // template-parameter shall either have a default template argument
2654 // supplied or be a template parameter pack.
2655 Diag((*NewParam)->getLocation(),
2656 diag::err_template_param_default_arg_missing);
2657 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2658 Invalid = true;
2659 RemoveDefaultArguments = true;
2660 }
2661
2662 // If we have an old template parameter list that we're merging
2663 // in, move on to the next parameter.
2664 if (OldParams)
2665 ++OldParam;
2666 }
2667
2668 // We were missing some default arguments at the end of the list, so remove
2669 // all of the default arguments.
2670 if (RemoveDefaultArguments) {
2671 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2672 NewParamEnd = NewParams->end();
2673 NewParam != NewParamEnd; ++NewParam) {
2674 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2675 TTP->removeDefaultArgument();
2676 else if (NonTypeTemplateParmDecl *NTTP
2677 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2678 NTTP->removeDefaultArgument();
2679 else
2680 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2681 }
2682 }
2683
2684 return Invalid;
2685}
2686
2687namespace {
2688
2689/// A class which looks for a use of a certain level of template
2690/// parameter.
2691struct DependencyChecker : DynamicRecursiveASTVisitor {
2692 unsigned Depth;
2693
2694 // Whether we're looking for a use of a template parameter that makes the
2695 // overall construct type-dependent / a dependent type. This is strictly
2696 // best-effort for now; we may fail to match at all for a dependent type
2697 // in some cases if this is set.
2698 bool IgnoreNonTypeDependent;
2699
2700 bool Match;
2701 SourceLocation MatchLoc;
2702
2703 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2704 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2705 Match(false) {}
2706
2707 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2708 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2709 NamedDecl *ND = Params->getParam(0);
2710 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2711 Depth = PD->getDepth();
2712 } else if (NonTypeTemplateParmDecl *PD =
2713 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2714 Depth = PD->getDepth();
2715 } else {
2716 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2717 }
2718 }
2719
2720 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2721 if (ParmDepth >= Depth) {
2722 Match = true;
2723 MatchLoc = Loc;
2724 return true;
2725 }
2726 return false;
2727 }
2728
2729 bool TraverseStmt(Stmt *S) override {
2730 // Prune out non-type-dependent expressions if requested. This can
2731 // sometimes result in us failing to find a template parameter reference
2732 // (if a value-dependent expression creates a dependent type), but this
2733 // mode is best-effort only.
2734 if (auto *E = dyn_cast_or_null<Expr>(S))
2735 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2736 return true;
2738 }
2739
2740 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2741 if (IgnoreNonTypeDependent && !TL.isNull() &&
2742 !TL.getType()->isDependentType())
2743 return true;
2744 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2745 }
2746
2747 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2748 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2749 }
2750
2751 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2752 // For a best-effort search, keep looking until we find a location.
2753 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2754 }
2755
2756 bool TraverseTemplateName(TemplateName N) override {
2757 if (TemplateTemplateParmDecl *PD =
2758 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2759 if (Matches(PD->getDepth()))
2760 return false;
2762 }
2763
2764 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2765 if (NonTypeTemplateParmDecl *PD =
2766 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2767 if (Matches(PD->getDepth(), E->getExprLoc()))
2768 return false;
2769 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2770 }
2771
2772 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2773 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2774 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2775 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2776 return false;
2777 }
2778 for (auto &TLoc : ULE->template_arguments())
2780 }
2781 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2782 }
2783
2784 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2785 return TraverseType(T->getReplacementType());
2786 }
2787
2788 bool VisitSubstTemplateTypeParmPackType(
2789 SubstTemplateTypeParmPackType *T) override {
2790 return TraverseTemplateArgument(T->getArgumentPack());
2791 }
2792
2793 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2794 bool TraverseQualifier) override {
2795 // An InjectedClassNameType will never have a dependent template name,
2796 // so no need to traverse it.
2797 return TraverseTemplateArguments(
2798 T->getTemplateArgs(T->getDecl()->getASTContext()));
2799 }
2800};
2801} // end anonymous namespace
2802
2803/// Determines whether a given type depends on the given parameter
2804/// list.
2805static bool
2807 if (!Params->size())
2808 return false;
2809
2810 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2811 Checker.TraverseType(T);
2812 return Checker.Match;
2813}
2814
2815// Find the source range corresponding to the named type in the given
2816// nested-name-specifier, if any.
2818 QualType T,
2819 const CXXScopeSpec &SS) {
2821 for (;;) {
2824 break;
2825 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2826 return NNSLoc.castAsTypeLoc().getSourceRange();
2827 // FIXME: This will always be empty.
2828 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2829 }
2830
2831 return SourceRange();
2832}
2833
2835 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2836 TemplateIdAnnotation *TemplateId,
2837 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2838 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2839 IsMemberSpecialization = false;
2840 Invalid = false;
2841
2842 // The sequence of nested types to which we will match up the template
2843 // parameter lists. We first build this list by starting with the type named
2844 // by the nested-name-specifier and walking out until we run out of types.
2845 SmallVector<QualType, 4> NestedTypes;
2846 QualType T;
2847 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2848 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2849 if (CXXRecordDecl *Record =
2850 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2851 T = Context.getCanonicalTagType(Record);
2852 else
2853 T = QualType(Qualifier.getAsType(), 0);
2854 }
2855
2856 // If we found an explicit specialization that prevents us from needing
2857 // 'template<>' headers, this will be set to the location of that
2858 // explicit specialization.
2859 SourceLocation ExplicitSpecLoc;
2860
2861 while (!T.isNull()) {
2862 NestedTypes.push_back(T);
2863
2864 // Retrieve the parent of a record type.
2865 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2866 // If this type is an explicit specialization, we're done.
2868 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2870 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2871 ExplicitSpecLoc = Spec->getLocation();
2872 break;
2873 }
2874 } else if (Record->getTemplateSpecializationKind()
2876 ExplicitSpecLoc = Record->getLocation();
2877 break;
2878 }
2879
2880 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2881 T = Context.getTypeDeclType(Parent);
2882 else
2883 T = QualType();
2884 continue;
2885 }
2886
2887 if (const TemplateSpecializationType *TST
2888 = T->getAs<TemplateSpecializationType>()) {
2889 TemplateName Name = TST->getTemplateName();
2890 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2891 // Look one step prior in a dependent template specialization type.
2892 if (NestedNameSpecifier NNS = DTS->getQualifier();
2894 T = QualType(NNS.getAsType(), 0);
2895 else
2896 T = QualType();
2897 continue;
2898 }
2899 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2900 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2901 T = Context.getTypeDeclType(Parent);
2902 else
2903 T = QualType();
2904 continue;
2905 }
2906 }
2907
2908 // Look one step prior in a dependent name type.
2909 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2910 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2912 T = QualType(NNS.getAsType(), 0);
2913 else
2914 T = QualType();
2915 continue;
2916 }
2917
2918 // Retrieve the parent of an enumeration type.
2919 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2920 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2921 // check here.
2922 EnumDecl *Enum = EnumT->getDecl();
2923
2924 // Get to the parent type.
2925 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2926 T = Context.getCanonicalTypeDeclType(Parent);
2927 else
2928 T = QualType();
2929 continue;
2930 }
2931
2932 T = QualType();
2933 }
2934 // Reverse the nested types list, since we want to traverse from the outermost
2935 // to the innermost while checking template-parameter-lists.
2936 std::reverse(NestedTypes.begin(), NestedTypes.end());
2937
2938 // C++0x [temp.expl.spec]p17:
2939 // A member or a member template may be nested within many
2940 // enclosing class templates. In an explicit specialization for
2941 // such a member, the member declaration shall be preceded by a
2942 // template<> for each enclosing class template that is
2943 // explicitly specialized.
2944 bool SawNonEmptyTemplateParameterList = false;
2945
2946 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2947 if (SawNonEmptyTemplateParameterList) {
2948 if (!SuppressDiagnostic)
2949 Diag(DeclLoc, diag::err_specialize_member_of_template)
2950 << !Recovery << Range;
2951 Invalid = true;
2952 IsMemberSpecialization = false;
2953 return true;
2954 }
2955
2956 return false;
2957 };
2958
2959 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2960 // Check that we can have an explicit specialization here.
2961 if (CheckExplicitSpecialization(Range, true))
2962 return true;
2963
2964 // We don't have a template header, but we should.
2965 SourceLocation ExpectedTemplateLoc;
2966 if (!ParamLists.empty())
2967 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2968 else
2969 ExpectedTemplateLoc = DeclStartLoc;
2970
2971 if (!SuppressDiagnostic)
2972 Diag(DeclLoc, diag::err_template_spec_needs_header)
2973 << Range
2974 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2975 return false;
2976 };
2977
2978 unsigned ParamIdx = 0;
2979 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2980 ++TypeIdx) {
2981 T = NestedTypes[TypeIdx];
2982
2983 // Whether we expect a 'template<>' header.
2984 bool NeedEmptyTemplateHeader = false;
2985
2986 // Whether we expect a template header with parameters.
2987 bool NeedNonemptyTemplateHeader = false;
2988
2989 // For a dependent type, the set of template parameters that we
2990 // expect to see.
2991 TemplateParameterList *ExpectedTemplateParams = nullptr;
2992
2993 // C++0x [temp.expl.spec]p15:
2994 // A member or a member template may be nested within many enclosing
2995 // class templates. In an explicit specialization for such a member, the
2996 // member declaration shall be preceded by a template<> for each
2997 // enclosing class template that is explicitly specialized.
2998 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3000 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3001 ExpectedTemplateParams = Partial->getTemplateParameters();
3002 NeedNonemptyTemplateHeader = true;
3003 } else if (Record->isDependentType()) {
3004 if (Record->getDescribedClassTemplate()) {
3005 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3006 ->getTemplateParameters();
3007 NeedNonemptyTemplateHeader = true;
3008 }
3009 } else if (ClassTemplateSpecializationDecl *Spec
3010 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3011 // C++0x [temp.expl.spec]p4:
3012 // Members of an explicitly specialized class template are defined
3013 // in the same manner as members of normal classes, and not using
3014 // the template<> syntax.
3015 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3016 NeedEmptyTemplateHeader = true;
3017 else
3018 continue;
3019 } else if (Record->getTemplateSpecializationKind()) {
3020 if (Record->getTemplateSpecializationKind()
3022 TypeIdx == NumTypes - 1)
3023 IsMemberSpecialization = true;
3024
3025 continue;
3026 }
3027 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3028 TemplateName Name = TST->getTemplateName();
3029 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3030 ExpectedTemplateParams = Template->getTemplateParameters();
3031 NeedNonemptyTemplateHeader = true;
3032 } else if (Name.getAsDeducedTemplateName()) {
3033 // FIXME: We actually could/should check the template arguments here
3034 // against the corresponding template parameter list.
3035 NeedNonemptyTemplateHeader = false;
3036 }
3037 }
3038
3039 // C++ [temp.expl.spec]p16:
3040 // In an explicit specialization declaration for a member of a class
3041 // template or a member template that appears in namespace scope, the
3042 // member template and some of its enclosing class templates may remain
3043 // unspecialized, except that the declaration shall not explicitly
3044 // specialize a class member template if its enclosing class templates
3045 // are not explicitly specialized as well.
3046 if (ParamIdx < ParamLists.size()) {
3047 if (ParamLists[ParamIdx]->size() == 0) {
3048 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3049 false))
3050 return nullptr;
3051 } else
3052 SawNonEmptyTemplateParameterList = true;
3053 }
3054
3055 if (NeedEmptyTemplateHeader) {
3056 // If we're on the last of the types, and we need a 'template<>' header
3057 // here, then it's a member specialization.
3058 if (TypeIdx == NumTypes - 1)
3059 IsMemberSpecialization = true;
3060
3061 if (ParamIdx < ParamLists.size()) {
3062 if (ParamLists[ParamIdx]->size() > 0) {
3063 // The header has template parameters when it shouldn't. Complain.
3064 if (!SuppressDiagnostic)
3065 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3066 diag::err_template_param_list_matches_nontemplate)
3067 << T
3068 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3069 ParamLists[ParamIdx]->getRAngleLoc())
3071 Invalid = true;
3072 return nullptr;
3073 }
3074
3075 // Consume this template header.
3076 ++ParamIdx;
3077 continue;
3078 }
3079
3080 if (!IsFriend)
3081 if (DiagnoseMissingExplicitSpecialization(
3083 return nullptr;
3084
3085 continue;
3086 }
3087
3088 if (NeedNonemptyTemplateHeader) {
3089 // In friend declarations we can have template-ids which don't
3090 // depend on the corresponding template parameter lists. But
3091 // assume that empty parameter lists are supposed to match this
3092 // template-id.
3093 if (IsFriend && T->isDependentType()) {
3094 if (ParamIdx < ParamLists.size() &&
3095 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3096 ExpectedTemplateParams = nullptr;
3097 else
3098 continue;
3099 }
3100
3101 if (ParamIdx < ParamLists.size()) {
3102 // Check the template parameter list, if we can.
3103 if (ExpectedTemplateParams &&
3105 ExpectedTemplateParams,
3106 !SuppressDiagnostic, TPL_TemplateMatch))
3107 Invalid = true;
3108
3109 if (!Invalid &&
3110 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3112 Invalid = true;
3113
3114 ++ParamIdx;
3115 continue;
3116 }
3117
3118 if (!SuppressDiagnostic)
3119 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3120 << T
3122 Invalid = true;
3123 continue;
3124 }
3125 }
3126
3127 // If there were at least as many template-ids as there were template
3128 // parameter lists, then there are no template parameter lists remaining for
3129 // the declaration itself.
3130 if (ParamIdx >= ParamLists.size()) {
3131 if (TemplateId && !IsFriend) {
3132 // We don't have a template header for the declaration itself, but we
3133 // should.
3134 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3135 TemplateId->RAngleLoc));
3136
3137 // Fabricate an empty template parameter list for the invented header.
3139 SourceLocation(), {},
3140 SourceLocation(), nullptr);
3141 }
3142
3143 return nullptr;
3144 }
3145
3146 // If there were too many template parameter lists, complain about that now.
3147 if (ParamIdx < ParamLists.size() - 1) {
3148 bool HasAnyExplicitSpecHeader = false;
3149 bool AllExplicitSpecHeaders = true;
3150 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3151 if (ParamLists[I]->size() == 0)
3152 HasAnyExplicitSpecHeader = true;
3153 else
3154 AllExplicitSpecHeaders = false;
3155 }
3156
3157 if (!SuppressDiagnostic)
3158 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3159 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3160 : diag::err_template_spec_extra_headers)
3161 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3162 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3163
3164 // If there was a specialization somewhere, such that 'template<>' is
3165 // not required, and there were any 'template<>' headers, note where the
3166 // specialization occurred.
3167 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3168 !SuppressDiagnostic)
3169 Diag(ExplicitSpecLoc,
3170 diag::note_explicit_template_spec_does_not_need_header)
3171 << NestedTypes.back();
3172
3173 // We have a template parameter list with no corresponding scope, which
3174 // means that the resulting template declaration can't be instantiated
3175 // properly (we'll end up with dependent nodes when we shouldn't).
3176 if (!AllExplicitSpecHeaders)
3177 Invalid = true;
3178 }
3179
3180 // C++ [temp.expl.spec]p16:
3181 // In an explicit specialization declaration for a member of a class
3182 // template or a member template that ap- pears in namespace scope, the
3183 // member template and some of its enclosing class templates may remain
3184 // unspecialized, except that the declaration shall not explicitly
3185 // specialize a class member template if its en- closing class templates
3186 // are not explicitly specialized as well.
3187 if (ParamLists.back()->size() == 0 &&
3188 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3189 false))
3190 return nullptr;
3191
3192 // Return the last template parameter list, which corresponds to the
3193 // entity being declared.
3194 return ParamLists.back();
3195}
3196
3198 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3199 Diag(Template->getLocation(), diag::note_template_declared_here)
3201 ? 0
3203 ? 1
3205 ? 2
3207 << Template->getDeclName();
3208 return;
3209 }
3210
3212 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3213 IEnd = OST->end();
3214 I != IEnd; ++I)
3215 Diag((*I)->getLocation(), diag::note_template_declared_here)
3216 << 0 << (*I)->getDeclName();
3217
3218 return;
3219 }
3220}
3221
3223 TemplateName BaseTemplate,
3224 SourceLocation TemplateLoc,
3226 auto lookUpCommonType = [&](TemplateArgument T1,
3227 TemplateArgument T2) -> QualType {
3228 // Don't bother looking for other specializations if both types are
3229 // builtins - users aren't allowed to specialize for them
3230 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3231 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3232 {T1, T2});
3233
3237 Args.addArgument(TemplateArgumentLoc(
3238 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3239
3240 EnterExpressionEvaluationContext UnevaluatedContext(
3242 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3244
3245 QualType BaseTemplateInst = S.CheckTemplateIdType(
3246 Keyword, BaseTemplate, TemplateLoc, Args,
3247 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3248
3249 if (SFINAE.hasErrorOccurred())
3250 return QualType();
3251
3252 return BaseTemplateInst;
3253 };
3254
3255 // Note A: For the common_type trait applied to a template parameter pack T of
3256 // types, the member type shall be either defined or not present as follows:
3257 switch (Ts.size()) {
3258
3259 // If sizeof...(T) is zero, there shall be no member type.
3260 case 0:
3261 return QualType();
3262
3263 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3264 // pack T. The member typedef-name type shall denote the same type, if any, as
3265 // common_type_t<T0, T0>; otherwise there shall be no member type.
3266 case 1:
3267 return lookUpCommonType(Ts[0], Ts[0]);
3268
3269 // If sizeof...(T) is two, let the first and second types constituting T be
3270 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3271 // as decay_t<T1> and decay_t<T2>, respectively.
3272 case 2: {
3273 QualType T1 = Ts[0].getAsType();
3274 QualType T2 = Ts[1].getAsType();
3275 QualType D1 = S.BuiltinDecay(T1, {});
3276 QualType D2 = S.BuiltinDecay(T2, {});
3277
3278 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3279 // the same type, if any, as common_type_t<D1, D2>.
3280 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3281 return lookUpCommonType(D1, D2);
3282
3283 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3284 // denotes a valid type, let C denote that type.
3285 {
3286 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3287 EnterExpressionEvaluationContext UnevaluatedContext(
3289 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3291
3292 // false
3294 VK_PRValue);
3295 ExprResult Cond = &CondExpr;
3296
3297 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3298 if (ConstRefQual) {
3299 D1.addConst();
3300 D2.addConst();
3301 }
3302
3303 // declval<D1>()
3304 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3305 ExprResult LHS = &LHSExpr;
3306
3307 // declval<D2>()
3308 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3309 ExprResult RHS = &RHSExpr;
3310
3313
3314 // decltype(false ? declval<D1>() : declval<D2>())
3315 QualType Result =
3316 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3317
3318 if (Result.isNull() || SFINAE.hasErrorOccurred())
3319 return QualType();
3320
3321 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3322 return S.BuiltinDecay(Result, TemplateLoc);
3323 };
3324
3325 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3326 return Res;
3327
3328 // Let:
3329 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3330 // COND-RES(X, Y) be
3331 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3332
3333 // C++20 only
3334 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3335 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3336 if (!S.Context.getLangOpts().CPlusPlus20)
3337 return QualType();
3338 return CheckConditionalOperands(true);
3339 }
3340 }
3341
3342 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3343 // denote the first, second, and (pack of) remaining types constituting T. Let
3344 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3345 // a type C, the member typedef-name type shall denote the same type, if any,
3346 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3347 default: {
3348 QualType Result = Ts.front().getAsType();
3349 for (auto T : llvm::drop_begin(Ts)) {
3350 Result = lookUpCommonType(Result, T.getAsType());
3351 if (Result.isNull())
3352 return QualType();
3353 }
3354 return Result;
3355 }
3356 }
3357}
3358
3359static bool isInVkNamespace(const RecordType *RT) {
3360 DeclContext *DC = RT->getDecl()->getDeclContext();
3361 if (!DC)
3362 return false;
3363
3364 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3365 if (!ND)
3366 return false;
3367
3368 return ND->getQualifiedNameAsString() == "hlsl::vk";
3369}
3370
3371static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3372 QualType OperandArg,
3373 SourceLocation Loc) {
3374 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3375 bool Literal = false;
3376 SourceLocation LiteralLoc;
3377 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3378 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3379 assert(SpecDecl);
3380
3381 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3382 QualType ConstantType = LiteralArgs[0].getAsType();
3383 RT = ConstantType->getAsCanonical<RecordType>();
3384 Literal = true;
3385 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3386 }
3387
3388 if (RT && isInVkNamespace(RT) &&
3389 RT->getDecl()->getName() == "integral_constant") {
3390 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3391 assert(SpecDecl);
3392
3393 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3394
3395 QualType ConstantType = ConstantArgs[0].getAsType();
3396 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3397
3398 if (Literal)
3399 return SpirvOperand::createLiteral(Value);
3400 return SpirvOperand::createConstant(ConstantType, Value);
3401 } else if (Literal) {
3402 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3403 return SpirvOperand();
3404 }
3405 }
3406 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3407 diag::err_call_incomplete_argument))
3408 return SpirvOperand();
3409 return SpirvOperand::createType(OperandArg);
3410}
3411
3414 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3415 TemplateArgumentListInfo &TemplateArgs) {
3416 ASTContext &Context = SemaRef.getASTContext();
3417
3418 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3419 "Builtin template arguments do not match its parameters");
3420
3421 switch (BTD->getBuiltinTemplateKind()) {
3422 case BTK__make_integer_seq: {
3423 // Specializations of __make_integer_seq<S, T, N> are treated like
3424 // S<T, 0, ..., N-1>.
3425
3426 QualType OrigType = Converted[1].getAsType();
3427 // C++14 [inteseq.intseq]p1:
3428 // T shall be an integer type.
3429 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3430 SemaRef.Diag(TemplateArgs[1].getLocation(),
3431 diag::err_integer_sequence_integral_element_type);
3432 return QualType();
3433 }
3434
3435 TemplateArgument NumArgsArg = Converted[2];
3436 if (NumArgsArg.isDependent())
3437 return QualType();
3438
3439 TemplateArgumentListInfo SyntheticTemplateArgs;
3440 // The type argument, wrapped in substitution sugar, gets reused as the
3441 // first template argument in the synthetic template argument list.
3442 SyntheticTemplateArgs.addArgument(
3445 OrigType, TemplateArgs[1].getLocation())));
3446
3447 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3448 // Expand N into 0 ... N-1.
3449 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3450 I < NumArgs; ++I) {
3451 TemplateArgument TA(Context, I, OrigType);
3452 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3453 TA, OrigType, TemplateArgs[2].getLocation()));
3454 }
3455 } else {
3456 // C++14 [inteseq.make]p1:
3457 // If N is negative the program is ill-formed.
3458 SemaRef.Diag(TemplateArgs[2].getLocation(),
3459 diag::err_integer_sequence_negative_length);
3460 return QualType();
3461 }
3462
3463 // The first template argument will be reused as the template decl that
3464 // our synthetic template arguments will be applied to.
3465 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3466 TemplateLoc, SyntheticTemplateArgs,
3467 /*Scope=*/nullptr,
3468 /*ForNestedNameSpecifier=*/false);
3469 }
3470
3471 case BTK__type_pack_element: {
3472 // Specializations of
3473 // __type_pack_element<Index, T_1, ..., T_N>
3474 // are treated like T_Index.
3475 assert(Converted.size() == 2 &&
3476 "__type_pack_element should be given an index and a parameter pack");
3477
3478 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3479 if (IndexArg.isDependent() || Ts.isDependent())
3480 return QualType();
3481
3482 llvm::APSInt Index = IndexArg.getAsIntegral();
3483 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3484 "type std::size_t, and hence be non-negative");
3485 // If the Index is out of bounds, the program is ill-formed.
3486 if (Index >= Ts.pack_size()) {
3487 SemaRef.Diag(TemplateArgs[0].getLocation(),
3488 diag::err_type_pack_element_out_of_bounds);
3489 return QualType();
3490 }
3491
3492 // We simply return the type at index `Index`.
3493 int64_t N = Index.getExtValue();
3494 return Ts.getPackAsArray()[N].getAsType();
3495 }
3496
3497 case BTK__builtin_common_type: {
3498 assert(Converted.size() == 4);
3499 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3500 return QualType();
3501
3502 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3503 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3504 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3505 TemplateLoc, Ts);
3506 !CT.isNull()) {
3510 CT, TemplateArgs[1].getLocation())));
3511 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3512 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3513 TAs, /*Scope=*/nullptr,
3514 /*ForNestedNameSpecifier=*/false);
3515 }
3516 QualType HasNoTypeMember = Converted[2].getAsType();
3517 return HasNoTypeMember;
3518 }
3519
3520 case BTK__hlsl_spirv_type: {
3521 assert(Converted.size() == 4);
3522
3523 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3524 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3525 }
3526
3527 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3528 return QualType();
3529
3530 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3531 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3532 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3533
3534 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3535
3537
3538 for (auto &OperandTA : OperandArgs) {
3539 QualType OperandArg = OperandTA.getAsType();
3540 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3541 TemplateArgs[3].getLocation());
3542 if (!Operand.isValid())
3543 return QualType();
3544 Operands.push_back(Operand);
3545 }
3546
3547 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3548 }
3549 case BTK__builtin_dedup_pack: {
3550 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3551 "a parameter pack");
3552 TemplateArgument Ts = Converted[0];
3553 // Delay the computation until we can compute the final result. We choose
3554 // not to remove the duplicates upfront before substitution to keep the code
3555 // simple.
3556 if (Ts.isDependent())
3557 return QualType();
3558 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3560 llvm::SmallDenseSet<QualType> Seen;
3561 // Synthesize a new template argument list, removing duplicates.
3562 for (auto T : Ts.getPackAsArray()) {
3563 assert(T.getKind() == clang::TemplateArgument::Type);
3564 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3565 continue;
3566 OutArgs.push_back(T);
3567 }
3568 return Context.getSubstBuiltinTemplatePack(
3569 TemplateArgument::CreatePackCopy(Context, OutArgs));
3570 }
3571 }
3572 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3573}
3574
3575/// Determine whether this alias template is "enable_if_t".
3576/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3578 return AliasTemplate->getName() == "enable_if_t" ||
3579 AliasTemplate->getName() == "__enable_if_t";
3580}
3581
3582/// Collect all of the separable terms in the given condition, which
3583/// might be a conjunction.
3584///
3585/// FIXME: The right answer is to convert the logical expression into
3586/// disjunctive normal form, so we can find the first failed term
3587/// within each possible clause.
3588static void collectConjunctionTerms(Expr *Clause,
3589 SmallVectorImpl<Expr *> &Terms) {
3590 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3591 if (BinOp->getOpcode() == BO_LAnd) {
3592 collectConjunctionTerms(BinOp->getLHS(), Terms);
3593 collectConjunctionTerms(BinOp->getRHS(), Terms);
3594 return;
3595 }
3596 }
3597
3598 Terms.push_back(Clause);
3599}
3600
3601// The ranges-v3 library uses an odd pattern of a top-level "||" with
3602// a left-hand side that is value-dependent but never true. Identify
3603// the idiom and ignore that term.
3605 // Top-level '||'.
3606 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3607 if (!BinOp) return Cond;
3608
3609 if (BinOp->getOpcode() != BO_LOr) return Cond;
3610
3611 // With an inner '==' that has a literal on the right-hand side.
3612 Expr *LHS = BinOp->getLHS();
3613 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3614 if (!InnerBinOp) return Cond;
3615
3616 if (InnerBinOp->getOpcode() != BO_EQ ||
3617 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3618 return Cond;
3619
3620 // If the inner binary operation came from a macro expansion named
3621 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3622 // of the '||', which is the real, user-provided condition.
3623 SourceLocation Loc = InnerBinOp->getExprLoc();
3624 if (!Loc.isMacroID()) return Cond;
3625
3626 StringRef MacroName = PP.getImmediateMacroName(Loc);
3627 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3628 return BinOp->getRHS();
3629
3630 return Cond;
3631}
3632
3633namespace {
3634
3635// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3636// within failing boolean expression, such as substituting template parameters
3637// for actual types.
3638class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3639public:
3640 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3641 : Policy(P) {}
3642
3643 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3644 const auto *DR = dyn_cast<DeclRefExpr>(E);
3645 if (DR && DR->getQualifier()) {
3646 // If this is a qualified name, expand the template arguments in nested
3647 // qualifiers.
3648 DR->getQualifier().print(OS, Policy, true);
3649 // Then print the decl itself.
3650 const ValueDecl *VD = DR->getDecl();
3651 OS << VD->getName();
3652 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3653 // This is a template variable, print the expanded template arguments.
3654 printTemplateArgumentList(
3655 OS, IV->getTemplateArgs().asArray(), Policy,
3656 IV->getSpecializedTemplate()->getTemplateParameters());
3657 }
3658 return true;
3659 }
3660 return false;
3661 }
3662
3663private:
3664 const PrintingPolicy Policy;
3665};
3666
3667} // end anonymous namespace
3668
3669std::pair<Expr *, std::string>
3672
3673 // Separate out all of the terms in a conjunction.
3676
3677 // Determine which term failed.
3678 Expr *FailedCond = nullptr;
3679 for (Expr *Term : Terms) {
3680 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3681
3682 // Literals are uninteresting.
3683 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3684 isa<IntegerLiteral>(TermAsWritten))
3685 continue;
3686
3687 // The initialization of the parameter from the argument is
3688 // a constant-evaluated context.
3691
3692 bool Succeeded;
3693 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3694 !Succeeded) {
3695 FailedCond = TermAsWritten;
3696 break;
3697 }
3698 }
3699 if (!FailedCond)
3700 FailedCond = Cond->IgnoreParenImpCasts();
3701
3702 std::string Description;
3703 {
3704 llvm::raw_string_ostream Out(Description);
3706 Policy.PrintAsCanonical = true;
3707 FailedBooleanConditionPrinterHelper Helper(Policy);
3708 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3709 }
3710 return { FailedCond, Description };
3711}
3712
3713static TemplateName
3715 const AssumedTemplateStorage *ATN,
3716 SourceLocation NameLoc) {
3717 // We assumed this undeclared identifier to be an (ADL-only) function
3718 // template name, but it was used in a context where a type was required.
3719 // Try to typo-correct it now.
3720 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3721 struct CandidateCallback : CorrectionCandidateCallback {
3722 bool ValidateCandidate(const TypoCorrection &TC) override {
3723 return TC.getCorrectionDecl() &&
3725 }
3726 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3727 return std::make_unique<CandidateCallback>(*this);
3728 }
3729 } FilterCCC;
3730
3731 TypoCorrection Corrected =
3732 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3733 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3734 if (Corrected && Corrected.getFoundDecl()) {
3735 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3736 << ATN->getDeclName());
3738 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3740 }
3741
3742 return TemplateName();
3743}
3744
3746 TemplateName Name,
3747 SourceLocation TemplateLoc,
3748 TemplateArgumentListInfo &TemplateArgs,
3749 Scope *Scope, bool ForNestedNameSpecifier) {
3750 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3751
3752 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3753 if (!Template) {
3754 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3755 Template = S->getParameterPack();
3756 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3757 if (DTN->getName().getIdentifier())
3758 // When building a template-id where the template-name is dependent,
3759 // assume the template is a type template. Either our assumption is
3760 // correct, or the code is ill-formed and will be diagnosed when the
3761 // dependent name is substituted.
3762 return Context.getTemplateSpecializationType(Keyword, Name,
3763 TemplateArgs.arguments(),
3764 /*CanonicalArgs=*/{});
3765 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3767 *this, Scope, ATN, TemplateLoc);
3768 CorrectedName.isNull()) {
3769 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3770 return QualType();
3771 } else {
3772 Name = CorrectedName;
3773 Template = Name.getAsTemplateDecl();
3774 }
3775 }
3776 }
3777 if (!Template ||
3779 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3780 if (ForNestedNameSpecifier)
3781 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3782 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3783 else
3784 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3786 return QualType();
3787 }
3788
3789 // Check that the template argument list is well-formed for this
3790 // template.
3792 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3793 DefaultArgs, /*PartialTemplateArgs=*/false,
3794 CTAI,
3795 /*UpdateArgsWithConversions=*/true))
3796 return QualType();
3797
3798 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3799 // and there are no diagnsotics currently implemented for TemplateDecls,
3800 // so avoid doing it for now.
3801 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3802
3803 QualType CanonType;
3804
3806 // We might have a substituted template template parameter pack. If so,
3807 // build a template specialization type for it.
3809 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3810
3811 // C++0x [dcl.type.elab]p2:
3812 // If the identifier resolves to a typedef-name or the simple-template-id
3813 // resolves to an alias template specialization, the
3814 // elaborated-type-specifier is ill-formed.
3817 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3820 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3821 }
3822
3823 // Find the canonical type for this type alias template specialization.
3824 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3825
3826 // Diagnose uses of the pattern of this template.
3827 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3828 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3829
3830 if (Pattern->isInvalidDecl())
3831 return QualType();
3832
3833 // Only substitute for the innermost template argument list.
3834 MultiLevelTemplateArgumentList TemplateArgLists;
3836 /*Final=*/true);
3837 TemplateArgLists.addOuterRetainedLevels(
3838 AliasTemplate->getTemplateParameters()->getDepth());
3839
3841
3842 // FIXME: The TemplateArgs passed here are not used for the context note,
3843 // nor they should, because this note will be pointing to the specialization
3844 // anyway. These arguments are needed for a hack for instantiating lambdas
3845 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3846 // arguments will be used for collating the template arguments needed to
3847 // instantiate the lambda.
3848 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3849 /*Entity=*/AliasTemplate,
3850 /*TemplateArgs=*/CTAI.SugaredConverted);
3851 if (Inst.isInvalid())
3852 return QualType();
3853
3854 std::optional<ContextRAII> SavedContext;
3855 if (!AliasTemplate->getDeclContext()->isFileContext())
3856 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3857
3858 CanonType =
3859 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3860 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3861 if (CanonType.isNull()) {
3862 // If this was enable_if and we failed to find the nested type
3863 // within enable_if in a SFINAE context, dig out the specific
3864 // enable_if condition that failed and present that instead.
3866 if (SFINAETrap *Trap = getSFINAEContext();
3867 TemplateDeductionInfo *DeductionInfo =
3868 Trap ? Trap->getDeductionInfo() : nullptr) {
3869 if (DeductionInfo->hasSFINAEDiagnostic() &&
3870 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3871 diag::err_typename_nested_not_found_enable_if &&
3872 TemplateArgs[0].getArgument().getKind() ==
3874 Expr *FailedCond;
3875 std::string FailedDescription;
3876 std::tie(FailedCond, FailedDescription) =
3877 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3878
3879 // Remove the old SFINAE diagnostic.
3880 PartialDiagnosticAt OldDiag =
3882 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3883
3884 // Add a new SFINAE diagnostic specifying which condition
3885 // failed.
3886 DeductionInfo->addSFINAEDiagnostic(
3887 OldDiag.first,
3888 PDiag(diag::err_typename_nested_not_found_requirement)
3889 << FailedDescription << FailedCond->getSourceRange());
3890 }
3891 }
3892 }
3893
3894 return QualType();
3895 }
3896 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3897 CanonType = checkBuiltinTemplateIdType(
3898 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3899 } else if (Name.isDependent() ||
3900 TemplateSpecializationType::anyDependentTemplateArguments(
3901 TemplateArgs, CTAI.CanonicalConverted)) {
3902 // This class template specialization is a dependent
3903 // type. Therefore, its canonical type is another class template
3904 // specialization type that contains all of the converted
3905 // arguments in canonical form. This ensures that, e.g., A<T> and
3906 // A<T, T> have identical types when A is declared as:
3907 //
3908 // template<typename T, typename U = T> struct A;
3909 CanonType = Context.getCanonicalTemplateSpecializationType(
3911 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3912 CTAI.CanonicalConverted);
3913 assert(CanonType->isCanonicalUnqualified());
3914
3915 // This might work out to be a current instantiation, in which
3916 // case the canonical type needs to be the InjectedClassNameType.
3917 //
3918 // TODO: in theory this could be a simple hashtable lookup; most
3919 // changes to CurContext don't change the set of current
3920 // instantiations.
3922 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3923 // If we get out to a namespace, we're done.
3924 if (Ctx->isFileContext()) break;
3925
3926 // If this isn't a record, keep looking.
3927 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3928 if (!Record) continue;
3929
3930 // Look for one of the two cases with InjectedClassNameTypes
3931 // and check whether it's the same template.
3933 !Record->getDescribedClassTemplate())
3934 continue;
3935
3936 // Fetch the injected class name type and check whether its
3937 // injected type is equal to the type we just built.
3938 CanQualType ICNT = Context.getCanonicalTagType(Record);
3939 CanQualType Injected =
3940 Record->getCanonicalTemplateSpecializationType(Context);
3941
3942 if (CanonType != Injected)
3943 continue;
3944
3945 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3946 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3947
3948 // If so, the canonical type of this TST is the injected
3949 // class name type of the record we just found.
3950 CanonType = ICNT;
3951 break;
3952 }
3953 }
3954 } else if (ClassTemplateDecl *ClassTemplate =
3955 dyn_cast<ClassTemplateDecl>(Template)) {
3956 // Find the class template specialization declaration that
3957 // corresponds to these arguments.
3958 void *InsertPos = nullptr;
3960 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3961 if (!Decl) {
3962 // This is the first time we have referenced this class template
3963 // specialization. Create the canonical declaration and add it to
3964 // the set of specializations.
3966 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3967 ClassTemplate->getDeclContext(),
3968 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3969 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3970 CTAI.StrictPackMatch, nullptr);
3971 ClassTemplate->AddSpecialization(Decl, InsertPos);
3972 if (ClassTemplate->isOutOfLine())
3973 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3974 }
3975
3976 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3977 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3978 NonSFINAEContext _(*this);
3979 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3980 if (!Inst.isInvalid()) {
3982 CTAI.CanonicalConverted,
3983 /*Final=*/false);
3984 InstantiateAttrsForDecl(TemplateArgLists,
3985 ClassTemplate->getTemplatedDecl(), Decl);
3986 }
3987 }
3988
3989 // Diagnose uses of this specialization.
3990 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3991 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
3992
3993 CanonType = Context.getCanonicalTagType(Decl);
3994 assert(isa<RecordType>(CanonType) &&
3995 "type of non-dependent specialization is not a RecordType");
3996 } else {
3997 llvm_unreachable("Unhandled template kind");
3998 }
3999
4000 // Build the fully-sugared type for this class template
4001 // specialization, which refers back to the class template
4002 // specialization we created or found.
4003 return Context.getTemplateSpecializationType(
4004 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4005 CanonType);
4006}
4007
4009 TemplateNameKind &TNK,
4010 SourceLocation NameLoc,
4011 IdentifierInfo *&II) {
4012 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4013
4014 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4015 assert(ATN && "not an assumed template name");
4016 II = ATN->getDeclName().getAsIdentifierInfo();
4017
4018 if (TemplateName Name =
4019 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4020 !Name.isNull()) {
4021 // Resolved to a type template name.
4022 ParsedName = TemplateTy::make(Name);
4023 TNK = TNK_Type_template;
4024 }
4025}
4026
4028 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4029 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4030 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4031 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4032 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4033 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4034 ImplicitTypenameContext AllowImplicitTypename) {
4035 if (SS.isInvalid())
4036 return true;
4037
4038 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4039 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4040
4041 // C++ [temp.res]p3:
4042 // A qualified-id that refers to a type and in which the
4043 // nested-name-specifier depends on a template-parameter (14.6.2)
4044 // shall be prefixed by the keyword typename to indicate that the
4045 // qualified-id denotes a type, forming an
4046 // elaborated-type-specifier (7.1.5.3).
4047 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4048 // C++2a relaxes some of those restrictions in [temp.res]p5.
4049 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4050 SS.getScopeRep(), TemplateII);
4052 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4053 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4054 << NNS;
4055 if (!getLangOpts().CPlusPlus20)
4056 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4057 } else
4058 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4059
4060 // FIXME: This is not quite correct recovery as we don't transform SS
4061 // into the corresponding dependent form (and we don't diagnose missing
4062 // 'template' keywords within SS as a result).
4063 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4064 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4065 TemplateArgsIn, RAngleLoc);
4066 }
4067
4068 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4069 // it's not actually allowed to be used as a type in most cases. Because
4070 // we annotate it before we know whether it's valid, we have to check for
4071 // this case here.
4072 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4073 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4074 Diag(TemplateIILoc,
4075 TemplateKWLoc.isInvalid()
4076 ? diag::err_out_of_line_qualified_id_type_names_constructor
4077 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4078 << TemplateII << 0 /*injected-class-name used as template name*/
4079 << 1 /*if any keyword was present, it was 'template'*/;
4080 }
4081 }
4082
4083 // Translate the parser's template argument list in our AST format.
4084 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4085 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4086
4088 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4089 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4090 if (SpecTy.isNull())
4091 return true;
4092
4093 // Build type-source information.
4094 TypeLocBuilder TLB;
4095 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4096 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4097 TemplateIILoc, TemplateArgs);
4098 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4099}
4100
4102 TypeSpecifierType TagSpec,
4103 SourceLocation TagLoc,
4104 CXXScopeSpec &SS,
4105 SourceLocation TemplateKWLoc,
4106 TemplateTy TemplateD,
4107 SourceLocation TemplateLoc,
4108 SourceLocation LAngleLoc,
4109 ASTTemplateArgsPtr TemplateArgsIn,
4110 SourceLocation RAngleLoc) {
4111 if (SS.isInvalid())
4112 return TypeResult(true);
4113
4114 // Translate the parser's template argument list in our AST format.
4115 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4116 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4117
4118 // Determine the tag kind
4122
4124 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4125 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4126 if (Result.isNull())
4127 return TypeResult(true);
4128
4129 // Check the tag kind
4130 if (const RecordType *RT = Result->getAs<RecordType>()) {
4131 RecordDecl *D = RT->getDecl();
4132
4133 IdentifierInfo *Id = D->getIdentifier();
4134 assert(Id && "templated class must have an identifier");
4135
4137 TagLoc, Id)) {
4138 Diag(TagLoc, diag::err_use_with_wrong_tag)
4139 << Result
4141 Diag(D->getLocation(), diag::note_previous_use);
4142 }
4143 }
4144
4145 // Provide source-location information for the template specialization.
4146 TypeLocBuilder TLB;
4148 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4149 TemplateArgs);
4151}
4152
4153static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4154 NamedDecl *PrevDecl,
4155 SourceLocation Loc,
4157
4159
4161 unsigned Depth,
4162 unsigned Index) {
4163 switch (Arg.getKind()) {
4171 return false;
4172
4174 QualType Type = Arg.getAsType();
4175 const TemplateTypeParmType *TPT =
4176 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4177 return TPT && !Type.hasQualifiers() &&
4178 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4179 }
4180
4182 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4183 if (!DRE || !DRE->getDecl())
4184 return false;
4185 const NonTypeTemplateParmDecl *NTTP =
4186 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4187 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4188 }
4189
4191 const TemplateTemplateParmDecl *TTP =
4192 dyn_cast_or_null<TemplateTemplateParmDecl>(
4194 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4195 }
4196 llvm_unreachable("unexpected kind of template argument");
4197}
4198
4200 TemplateParameterList *SpecParams,
4202 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4203 return false;
4204
4205 unsigned Depth = Params->getDepth();
4206
4207 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4208 TemplateArgument Arg = Args[I];
4209
4210 // If the parameter is a pack expansion, the argument must be a pack
4211 // whose only element is a pack expansion.
4212 if (Params->getParam(I)->isParameterPack()) {
4213 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4214 !Arg.pack_begin()->isPackExpansion())
4215 return false;
4216 Arg = Arg.pack_begin()->getPackExpansionPattern();
4217 }
4218
4219 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4220 return false;
4221
4222 // For NTTPs further specialization is allowed via deduced types, so
4223 // we need to make sure to only reject here if primary template and
4224 // specialization use the same type for the NTTP.
4225 if (auto *SpecNTTP =
4226 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4227 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4228 if (!NTTP || NTTP->getType().getCanonicalType() !=
4229 SpecNTTP->getType().getCanonicalType())
4230 return false;
4231 }
4232 }
4233
4234 return true;
4235}
4236
4237template<typename PartialSpecDecl>
4238static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4239 if (Partial->getDeclContext()->isDependentContext())
4240 return;
4241
4242 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4243 // for non-substitution-failure issues?
4244 TemplateDeductionInfo Info(Partial->getLocation());
4245 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4246 return;
4247
4248 auto *Template = Partial->getSpecializedTemplate();
4249 S.Diag(Partial->getLocation(),
4250 diag::ext_partial_spec_not_more_specialized_than_primary)
4252
4253 if (Info.hasSFINAEDiagnostic()) {
4257 SmallString<128> SFINAEArgString;
4258 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4259 S.Diag(Diag.first,
4260 diag::note_partial_spec_not_more_specialized_than_primary)
4261 << SFINAEArgString;
4262 }
4263
4265 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4266 Template->getAssociatedConstraints(TemplateAC);
4267 Partial->getAssociatedConstraints(PartialAC);
4269 TemplateAC);
4270}
4271
4272static void
4274 const llvm::SmallBitVector &DeducibleParams) {
4275 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4276 if (!DeducibleParams[I]) {
4277 NamedDecl *Param = TemplateParams->getParam(I);
4278 if (Param->getDeclName())
4279 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4280 << Param->getDeclName();
4281 else
4282 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4283 << "(anonymous)";
4284 }
4285 }
4286}
4287
4288
4289template<typename PartialSpecDecl>
4291 PartialSpecDecl *Partial) {
4292 // C++1z [temp.class.spec]p8: (DR1495)
4293 // - The specialization shall be more specialized than the primary
4294 // template (14.5.5.2).
4296
4297 // C++ [temp.class.spec]p8: (DR1315)
4298 // - Each template-parameter shall appear at least once in the
4299 // template-id outside a non-deduced context.
4300 // C++1z [temp.class.spec.match]p3 (P0127R2)
4301 // If the template arguments of a partial specialization cannot be
4302 // deduced because of the structure of its template-parameter-list
4303 // and the template-id, the program is ill-formed.
4304 auto *TemplateParams = Partial->getTemplateParameters();
4305 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4306 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4307 TemplateParams->getDepth(), DeducibleParams);
4308
4309 if (!DeducibleParams.all()) {
4310 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4311 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4313 << (NumNonDeducible > 1)
4314 << SourceRange(Partial->getLocation(),
4315 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4316 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4317 }
4318}
4319
4324
4329
4331 // C++1z [temp.param]p11:
4332 // A template parameter of a deduction guide template that does not have a
4333 // default-argument shall be deducible from the parameter-type-list of the
4334 // deduction guide template.
4335 auto *TemplateParams = TD->getTemplateParameters();
4336 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4337 MarkDeducedTemplateParameters(TD, DeducibleParams);
4338 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4339 // A parameter pack is deducible (to an empty pack).
4340 auto *Param = TemplateParams->getParam(I);
4341 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4342 DeducibleParams[I] = true;
4343 }
4344
4345 if (!DeducibleParams.all()) {
4346 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4347 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4348 << (NumNonDeducible > 1);
4349 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4350 }
4351}
4352
4355 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4357 // D must be variable template id.
4359 "Variable template specialization is declared with a template id.");
4360
4361 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4362 TemplateArgumentListInfo TemplateArgs =
4363 makeTemplateArgumentListInfo(*this, *TemplateId);
4364 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4365 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4366 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4367
4368 TemplateName Name = TemplateId->Template.get();
4369
4370 // The template-id must name a variable template.
4372 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4373 if (!VarTemplate) {
4374 NamedDecl *FnTemplate;
4375 if (auto *OTS = Name.getAsOverloadedTemplate())
4376 FnTemplate = *OTS->begin();
4377 else
4378 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4379 if (FnTemplate)
4380 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4381 << FnTemplate->getDeclName();
4382 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4384 }
4385
4386 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4387 auto Message = DSA->getMessage();
4388 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4389 << VarTemplate << !Message.empty() << Message;
4390 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4391 }
4392
4393 // Check for unexpanded parameter packs in any of the template arguments.
4394 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4395 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4399 return true;
4400
4401 // Check that the template argument list is well-formed for this
4402 // template.
4404 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4405 /*DefaultArgs=*/{},
4406 /*PartialTemplateArgs=*/false, CTAI,
4407 /*UpdateArgsWithConversions=*/true))
4408 return true;
4409
4410 // Find the variable template (partial) specialization declaration that
4411 // corresponds to these arguments.
4414 TemplateArgs.size(),
4415 CTAI.CanonicalConverted))
4416 return true;
4417
4418 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4419 // we also do them during instantiation.
4420 if (!Name.isDependent() &&
4421 !TemplateSpecializationType::anyDependentTemplateArguments(
4422 TemplateArgs, CTAI.CanonicalConverted)) {
4423 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4424 << VarTemplate->getDeclName();
4426 }
4427
4428 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4429 TemplateParams, CTAI.CanonicalConverted) &&
4430 (!Context.getLangOpts().CPlusPlus20 ||
4431 !TemplateParams->hasAssociatedConstraints())) {
4432 // C++ [temp.class.spec]p9b3:
4433 //
4434 // -- The argument list of the specialization shall not be identical
4435 // to the implicit argument list of the primary template.
4436 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4437 << /*variable template*/ 1
4438 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4439 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4440 // FIXME: Recover from this by treating the declaration as a
4441 // redeclaration of the primary template.
4442 return true;
4443 }
4444 }
4445
4446 void *InsertPos = nullptr;
4447 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4448
4450 PrevDecl = VarTemplate->findPartialSpecialization(
4451 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4452 else
4453 PrevDecl =
4454 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4455
4457
4458 // Check whether we can declare a variable template specialization in
4459 // the current scope.
4460 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4461 TemplateNameLoc,
4463 return true;
4464
4465 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4466 // Since the only prior variable template specialization with these
4467 // arguments was referenced but not declared, reuse that
4468 // declaration node as our own, updating its source location and
4469 // the list of outer template parameters to reflect our new declaration.
4470 Specialization = PrevDecl;
4471 Specialization->setLocation(TemplateNameLoc);
4472 PrevDecl = nullptr;
4473 } else if (IsPartialSpecialization) {
4474 // Create a new class template partial specialization declaration node.
4476 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4479 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4480 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4481 SC, CTAI.CanonicalConverted);
4482 Partial->setTemplateArgsAsWritten(TemplateArgs);
4483
4484 if (!PrevPartial)
4485 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4486 Specialization = Partial;
4487
4488 // If we are providing an explicit specialization of a member variable
4489 // template specialization, make a note of that.
4490 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4491 PrevPartial->setMemberSpecialization();
4492
4494 } else {
4495 // Create a new class template specialization declaration node for
4496 // this explicit specialization or friend declaration.
4498 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4499 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4500 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4501
4502 if (!PrevDecl)
4503 VarTemplate->AddSpecialization(Specialization, InsertPos);
4504 }
4505
4506 // C++ [temp.expl.spec]p6:
4507 // If a template, a member template or the member of a class template is
4508 // explicitly specialized then that specialization shall be declared
4509 // before the first use of that specialization that would cause an implicit
4510 // instantiation to take place, in every translation unit in which such a
4511 // use occurs; no diagnostic is required.
4512 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4513 bool Okay = false;
4514 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4515 // Is there any previous explicit specialization declaration?
4517 Okay = true;
4518 break;
4519 }
4520 }
4521
4522 if (!Okay) {
4523 SourceRange Range(TemplateNameLoc, RAngleLoc);
4524 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4525 << Name << Range;
4526
4527 Diag(PrevDecl->getPointOfInstantiation(),
4528 diag::note_instantiation_required_here)
4529 << (PrevDecl->getTemplateSpecializationKind() !=
4531 return true;
4532 }
4533 }
4534
4535 Specialization->setLexicalDeclContext(CurContext);
4536
4537 // Add the specialization into its lexical context, so that it can
4538 // be seen when iterating through the list of declarations in that
4539 // context. However, specializations are not found by name lookup.
4540 CurContext->addDecl(Specialization);
4541
4542 // Note that this is an explicit specialization.
4543 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4544
4545 Previous.clear();
4546 if (PrevDecl)
4547 Previous.addDecl(PrevDecl);
4548 else if (Specialization->isStaticDataMember() &&
4549 Specialization->isOutOfLine())
4550 Specialization->setAccess(VarTemplate->getAccess());
4551
4552 return Specialization;
4553}
4554
4555namespace {
4556/// A partial specialization whose template arguments have matched
4557/// a given template-id.
4558struct PartialSpecMatchResult {
4561};
4562
4563// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4564// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4565static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4566 if (Var->getName() != "format_kind" ||
4567 !Var->getDeclContext()->isStdNamespace())
4568 return false;
4569
4570 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4571 // release in which users can access std::format_kind.
4572 // We can use 20250520 as the final date, see the following commits.
4573 // GCC releases/gcc-15 branch:
4574 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4575 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4576 // GCC master branch:
4577 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4578 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4579 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4580}
4581} // end anonymous namespace
4582
4585 SourceLocation TemplateNameLoc,
4586 const TemplateArgumentListInfo &TemplateArgs,
4587 bool SetWrittenArgs) {
4588 assert(Template && "A variable template id without template?");
4589
4590 // Check that the template argument list is well-formed for this template.
4593 Template, TemplateNameLoc,
4594 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4595 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4596 /*UpdateArgsWithConversions=*/true))
4597 return true;
4598
4599 // Produce a placeholder value if the specialization is dependent.
4600 if (Template->getDeclContext()->isDependentContext() ||
4601 TemplateSpecializationType::anyDependentTemplateArguments(
4602 TemplateArgs, CTAI.CanonicalConverted)) {
4603 if (ParsingInitForAutoVars.empty())
4604 return DeclResult();
4605
4606 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4607 const TemplateArgument &Arg2) {
4608 return Context.isSameTemplateArgument(Arg1, Arg2);
4609 };
4610
4611 if (VarDecl *Var = Template->getTemplatedDecl();
4612 ParsingInitForAutoVars.count(Var) &&
4613 // See comments on this function definition
4614 !IsLibstdcxxStdFormatKind(PP, Var) &&
4615 llvm::equal(
4616 CTAI.CanonicalConverted,
4617 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4618 IsSameTemplateArg)) {
4619 Diag(TemplateNameLoc,
4620 diag::err_auto_variable_cannot_appear_in_own_initializer)
4621 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4622 return true;
4623 }
4624
4626 Template->getPartialSpecializations(PartialSpecs);
4627 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4628 if (ParsingInitForAutoVars.count(Partial) &&
4629 llvm::equal(CTAI.CanonicalConverted,
4630 Partial->getTemplateArgs().asArray(),
4631 IsSameTemplateArg)) {
4632 Diag(TemplateNameLoc,
4633 diag::err_auto_variable_cannot_appear_in_own_initializer)
4634 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4635 << Partial->getType();
4636 return true;
4637 }
4638
4639 return DeclResult();
4640 }
4641
4642 // Find the variable template specialization declaration that
4643 // corresponds to these arguments.
4644 void *InsertPos = nullptr;
4646 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4647 checkSpecializationReachability(TemplateNameLoc, Spec);
4648 if (Spec->getType()->isUndeducedType()) {
4649 if (ParsingInitForAutoVars.count(Spec))
4650 Diag(TemplateNameLoc,
4651 diag::err_auto_variable_cannot_appear_in_own_initializer)
4652 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4653 << Spec->getType();
4654 else
4655 // We are substituting the initializer of this variable template
4656 // specialization.
4657 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4658 << Spec << Spec->getType();
4659
4660 return true;
4661 }
4662 // If we already have a variable template specialization, return it.
4663 return Spec;
4664 }
4665
4666 // This is the first time we have referenced this variable template
4667 // specialization. Create the canonical declaration and add it to
4668 // the set of specializations, based on the closest partial specialization
4669 // that it represents. That is,
4670 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4671 const TemplateArgumentList *PartialSpecArgs = nullptr;
4672 bool AmbiguousPartialSpec = false;
4673 typedef PartialSpecMatchResult MatchResult;
4675 SourceLocation PointOfInstantiation = TemplateNameLoc;
4676 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4677 /*ForTakingAddress=*/false);
4678
4679 // 1. Attempt to find the closest partial specialization that this
4680 // specializes, if any.
4681 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4682 // Perhaps better after unification of DeduceTemplateArguments() and
4683 // getMoreSpecializedPartialSpecialization().
4685 Template->getPartialSpecializations(PartialSpecs);
4686
4687 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4688 // C++ [temp.spec.partial.member]p2:
4689 // If the primary member template is explicitly specialized for a given
4690 // (implicit) specialization of the enclosing class template, the partial
4691 // specializations of the member template are ignored for this
4692 // specialization of the enclosing class template. If a partial
4693 // specialization of the member template is explicitly specialized for a
4694 // given (implicit) specialization of the enclosing class template, the
4695 // primary member template and its other partial specializations are still
4696 // considered for this specialization of the enclosing class template.
4697 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4698 !Partial->getMostRecentDecl()->isMemberSpecialization())
4699 continue;
4700
4701 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4702
4704 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4706 // Store the failed-deduction information for use in diagnostics, later.
4707 // TODO: Actually use the failed-deduction info?
4708 FailedCandidates.addCandidate().set(
4711 (void)Result;
4712 } else {
4713 Matched.push_back(PartialSpecMatchResult());
4714 Matched.back().Partial = Partial;
4715 Matched.back().Args = Info.takeSugared();
4716 }
4717 }
4718
4719 if (Matched.size() >= 1) {
4720 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4721 if (Matched.size() == 1) {
4722 // -- If exactly one matching specialization is found, the
4723 // instantiation is generated from that specialization.
4724 // We don't need to do anything for this.
4725 } else {
4726 // -- If more than one matching specialization is found, the
4727 // partial order rules (14.5.4.2) are used to determine
4728 // whether one of the specializations is more specialized
4729 // than the others. If none of the specializations is more
4730 // specialized than all of the other matching
4731 // specializations, then the use of the variable template is
4732 // ambiguous and the program is ill-formed.
4733 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4734 PEnd = Matched.end();
4735 P != PEnd; ++P) {
4736 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4737 PointOfInstantiation) ==
4738 P->Partial)
4739 Best = P;
4740 }
4741
4742 // Determine if the best partial specialization is more specialized than
4743 // the others.
4744 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4745 PEnd = Matched.end();
4746 P != PEnd; ++P) {
4748 P->Partial, Best->Partial,
4749 PointOfInstantiation) != Best->Partial) {
4750 AmbiguousPartialSpec = true;
4751 break;
4752 }
4753 }
4754 }
4755
4756 // Instantiate using the best variable template partial specialization.
4757 InstantiationPattern = Best->Partial;
4758 PartialSpecArgs = Best->Args;
4759 } else {
4760 // -- If no match is found, the instantiation is generated
4761 // from the primary template.
4762 // InstantiationPattern = Template->getTemplatedDecl();
4763 }
4764
4765 // 2. Create the canonical declaration.
4766 // Note that we do not instantiate a definition until we see an odr-use
4767 // in DoMarkVarDeclReferenced().
4768 // FIXME: LateAttrs et al.?
4769 if (AmbiguousPartialSpec) {
4770 // Partial ordering did not produce a clear winner. Complain.
4771 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4772 << Template;
4773 // Print the matching partial specializations.
4774 for (MatchResult P : Matched)
4775 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4776 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4777 *P.Args);
4778 return true;
4779 }
4780
4782 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4783 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4784 if (!Decl)
4785 return true;
4786 if (SetWrittenArgs)
4787 Decl->setTemplateArgsAsWritten(TemplateArgs);
4788
4790 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4791 Decl->setInstantiationOf(D, PartialSpecArgs);
4792
4793 checkSpecializationReachability(TemplateNameLoc, Decl);
4794
4795 assert(Decl && "No variable template specialization?");
4796 return Decl;
4797}
4798
4800 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4801 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4802 const TemplateArgumentListInfo *TemplateArgs) {
4803
4804 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4805 *TemplateArgs, /*SetWrittenArgs=*/false);
4806 if (Decl.isInvalid())
4807 return ExprError();
4808
4809 if (!Decl.get())
4810 return ExprResult();
4811
4812 VarDecl *Var = cast<VarDecl>(Decl.get());
4815 NameInfo.getLoc());
4816
4817 // Build an ordinary singleton decl ref.
4818 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4819}
4820
4822 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4824 const TemplateArgumentListInfo *TemplateArgs) {
4825 assert(Template && "A variable template id without template?");
4826
4827 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4828 Template->templateParameterKind() !=
4830 return ExprResult();
4831
4832 // Check that the template argument list is well-formed for this template.
4835 Template, TemplateLoc,
4836 // FIXME: TemplateArgs will not be modified because
4837 // UpdateArgsWithConversions is false, however, we should
4838 // CheckTemplateArgumentList to be const-correct.
4839 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4840 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4841 /*UpdateArgsWithConversions=*/false))
4842 return true;
4843
4845 R.addDecl(Template);
4846
4847 // FIXME: We model references to variable template and concept parameters
4848 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4849 // data, can generally be used in the same places and work the same way.
4850 // However, it might be cleaner to use a dedicated AST node in the long run.
4853 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4854 /*KnownDependent=*/false,
4855 /*KnownInstantiationDependent=*/false);
4856}
4857
4859 SourceLocation Loc) {
4860 Diag(Loc, diag::err_template_missing_args)
4861 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4862 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4863 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4864 }
4865}
4866
4868 bool TemplateKeyword,
4869 TemplateDecl *TD,
4870 SourceLocation Loc) {
4871 TemplateName Name = Context.getQualifiedTemplateName(
4872 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4874}
4875
4877 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4878 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4879 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4880 bool DoCheckConstraintSatisfaction) {
4881 assert(NamedConcept && "A concept template id without a template?");
4882
4883 if (NamedConcept->isInvalidDecl())
4884 return ExprError();
4885
4888 NamedConcept, ConceptNameInfo.getLoc(),
4889 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4890 /*DefaultArgs=*/{},
4891 /*PartialTemplateArgs=*/false, CTAI,
4892 /*UpdateArgsWithConversions=*/false))
4893 return ExprError();
4894
4895 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4896
4897 // There's a bug with CTAI.CanonicalConverted.
4898 // If the template argument contains a DependentDecltypeType that includes a
4899 // TypeAliasType, and the same written type had occurred previously in the
4900 // source, then the DependentDecltypeType would be canonicalized to that
4901 // previous type which would mess up the substitution.
4902 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4904 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4905 CTAI.SugaredConverted);
4906 ConstraintSatisfaction Satisfaction;
4907 bool AreArgsDependent =
4908 TemplateSpecializationType::anyDependentTemplateArguments(
4909 *TemplateArgs, CTAI.SugaredConverted);
4910 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4911 /*Final=*/false);
4913 Context,
4915 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4917
4918 bool Error = false;
4919 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4920 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4921 DoCheckConstraintSatisfaction) {
4922
4924
4927
4929 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4930 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4931 TemplateArgs->getRAngleLoc()),
4932 Satisfaction, CL);
4933 Satisfaction.ContainsErrors = Error;
4934 }
4935
4936 if (Error)
4937 return ExprError();
4938
4940 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4941}
4942
4944 SourceLocation TemplateKWLoc,
4945 LookupResult &R,
4946 bool RequiresADL,
4947 const TemplateArgumentListInfo *TemplateArgs) {
4948 // FIXME: Can we do any checking at this point? I guess we could check the
4949 // template arguments that we have against the template name, if the template
4950 // name refers to a single template. That's not a terribly common case,
4951 // though.
4952 // foo<int> could identify a single function unambiguously
4953 // This approach does NOT work, since f<int>(1);
4954 // gets resolved prior to resorting to overload resolution
4955 // i.e., template<class T> void f(double);
4956 // vs template<class T, class U> void f(U);
4957
4958 // These should be filtered out by our callers.
4959 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4960
4961 // Non-function templates require a template argument list.
4962 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4963 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4965 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4966 return ExprError();
4967 }
4968 }
4969 bool KnownDependent = false;
4970 // In C++1y, check variable template ids.
4971 if (R.getAsSingle<VarTemplateDecl>()) {
4973 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4974 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4975 if (Res.isInvalid() || Res.isUsable())
4976 return Res;
4977 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4978 KnownDependent = true;
4979 }
4980
4981 // We don't want lookup warnings at this point.
4982 R.suppressDiagnostics();
4983
4984 if (R.getAsSingle<ConceptDecl>()) {
4985 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4986 R.getRepresentativeDecl(),
4987 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4988 }
4989
4990 // Check variable template ids (C++17) and concept template parameters
4991 // (C++26).
4993 if (R.getAsSingle<TemplateTemplateParmDecl>())
4995 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
4996 TemplateKWLoc, TemplateArgs);
4997
4998 // Function templates
5000 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5001 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5002 R.begin(), R.end(), KnownDependent,
5003 /*KnownInstantiationDependent=*/false);
5004 // Model the templates with UnresolvedTemplateTy. The expression should then
5005 // either be transformed in an instantiation or be diagnosed in
5006 // CheckPlaceholderExpr.
5007 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5008 !R.getFoundDecl()->getAsFunction())
5009 ULE->setType(Context.UnresolvedTemplateTy);
5010
5011 return ULE;
5012}
5013
5015 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5016 const DeclarationNameInfo &NameInfo,
5017 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5018 assert(TemplateArgs || TemplateKWLoc.isValid());
5019
5020 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5021 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5022 /*EnteringContext=*/false, TemplateKWLoc))
5023 return ExprError();
5024
5025 if (R.isAmbiguous())
5026 return ExprError();
5027
5028 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5029 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5030
5031 if (R.empty()) {
5033 Diag(NameInfo.getLoc(), diag::err_no_member)
5034 << NameInfo.getName() << DC << SS.getRange();
5035 return ExprError();
5036 }
5037
5038 // If necessary, build an implicit class member access.
5039 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5040 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5041 /*S=*/nullptr);
5042
5043 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5044}
5045
5047 CXXScopeSpec &SS,
5048 SourceLocation TemplateKWLoc,
5049 const UnqualifiedId &Name,
5050 ParsedType ObjectType,
5051 bool EnteringContext,
5053 bool AllowInjectedClassName) {
5054 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5055 Diag(TemplateKWLoc,
5057 diag::warn_cxx98_compat_template_outside_of_template :
5058 diag::ext_template_outside_of_template)
5059 << FixItHint::CreateRemoval(TemplateKWLoc);
5060
5061 if (SS.isInvalid())
5062 return TNK_Non_template;
5063
5064 // Figure out where isTemplateName is going to look.
5065 DeclContext *LookupCtx = nullptr;
5066 if (SS.isNotEmpty())
5067 LookupCtx = computeDeclContext(SS, EnteringContext);
5068 else if (ObjectType)
5069 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5070
5071 // C++0x [temp.names]p5:
5072 // If a name prefixed by the keyword template is not the name of
5073 // a template, the program is ill-formed. [Note: the keyword
5074 // template may not be applied to non-template members of class
5075 // templates. -end note ] [ Note: as is the case with the
5076 // typename prefix, the template prefix is allowed in cases
5077 // where it is not strictly necessary; i.e., when the
5078 // nested-name-specifier or the expression on the left of the ->
5079 // or . is not dependent on a template-parameter, or the use
5080 // does not appear in the scope of a template. -end note]
5081 //
5082 // Note: C++03 was more strict here, because it banned the use of
5083 // the "template" keyword prior to a template-name that was not a
5084 // dependent name. C++ DR468 relaxed this requirement (the
5085 // "template" keyword is now permitted). We follow the C++0x
5086 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5087 bool MemberOfUnknownSpecialization;
5088 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5089 ObjectType, EnteringContext, Result,
5090 MemberOfUnknownSpecialization);
5091 if (TNK != TNK_Non_template) {
5092 // We resolved this to a (non-dependent) template name. Return it.
5093 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5094 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5096 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5097 // C++14 [class.qual]p2:
5098 // In a lookup in which function names are not ignored and the
5099 // nested-name-specifier nominates a class C, if the name specified
5100 // [...] is the injected-class-name of C, [...] the name is instead
5101 // considered to name the constructor
5102 //
5103 // We don't get here if naming the constructor would be valid, so we
5104 // just reject immediately and recover by treating the
5105 // injected-class-name as naming the template.
5106 Diag(Name.getBeginLoc(),
5107 diag::ext_out_of_line_qualified_id_type_names_constructor)
5108 << Name.Identifier
5109 << 0 /*injected-class-name used as template name*/
5110 << TemplateKWLoc.isValid();
5111 }
5112 return TNK;
5113 }
5114
5115 if (!MemberOfUnknownSpecialization) {
5116 // Didn't find a template name, and the lookup wasn't dependent.
5117 // Do the lookup again to determine if this is a "nothing found" case or
5118 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5119 // need to do this.
5121 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5123 // Tell LookupTemplateName that we require a template so that it diagnoses
5124 // cases where it finds a non-template.
5125 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5126 ? RequiredTemplateKind(TemplateKWLoc)
5128 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5129 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5130 !R.isAmbiguous()) {
5131 if (LookupCtx)
5132 Diag(Name.getBeginLoc(), diag::err_no_member)
5133 << DNI.getName() << LookupCtx << SS.getRange();
5134 else
5135 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5136 << DNI.getName() << SS.getRange();
5137 }
5138 return TNK_Non_template;
5139 }
5140
5141 NestedNameSpecifier Qualifier = SS.getScopeRep();
5142
5143 switch (Name.getKind()) {
5145 Result = TemplateTy::make(Context.getDependentTemplateName(
5146 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5148
5150 Result = TemplateTy::make(Context.getDependentTemplateName(
5151 {Qualifier, Name.OperatorFunctionId.Operator,
5152 TemplateKWLoc.isValid()}));
5153 return TNK_Function_template;
5154
5156 // This is a kind of template name, but can never occur in a dependent
5157 // scope (literal operators can only be declared at namespace scope).
5158 break;
5159
5160 default:
5161 break;
5162 }
5163
5164 // This name cannot possibly name a dependent template. Diagnose this now
5165 // rather than building a dependent template name that can never be valid.
5166 Diag(Name.getBeginLoc(),
5167 diag::err_template_kw_refers_to_dependent_non_template)
5169 << TemplateKWLoc.isValid() << TemplateKWLoc;
5170 return TNK_Non_template;
5171}
5172
5175 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5176 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5177 const TemplateArgument &Arg = AL.getArgument();
5179 TypeSourceInfo *TSI = nullptr;
5180
5181 // Check template type parameter.
5182 switch(Arg.getKind()) {
5184 // C++ [temp.arg.type]p1:
5185 // A template-argument for a template-parameter which is a
5186 // type shall be a type-id.
5187 ArgType = Arg.getAsType();
5188 TSI = AL.getTypeSourceInfo();
5189 break;
5192 // We have a template type parameter but the template argument
5193 // is a template without any arguments.
5194 SourceRange SR = AL.getSourceRange();
5197 return true;
5198 }
5200 // We have a template type parameter but the template argument is an
5201 // expression; see if maybe it is missing the "typename" keyword.
5202 CXXScopeSpec SS;
5203 DeclarationNameInfo NameInfo;
5204
5205 if (DependentScopeDeclRefExpr *ArgExpr =
5206 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5207 SS.Adopt(ArgExpr->getQualifierLoc());
5208 NameInfo = ArgExpr->getNameInfo();
5209 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5210 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5211 if (ArgExpr->isImplicitAccess()) {
5212 SS.Adopt(ArgExpr->getQualifierLoc());
5213 NameInfo = ArgExpr->getMemberNameInfo();
5214 }
5215 }
5216
5217 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5218 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5219 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5220
5221 if (Result.getAsSingle<TypeDecl>() ||
5222 Result.wasNotFoundInCurrentInstantiation()) {
5223 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5224 // Suggest that the user add 'typename' before the NNS.
5226 Diag(Loc, getLangOpts().MSVCCompat
5227 ? diag::ext_ms_template_type_arg_missing_typename
5228 : diag::err_template_arg_must_be_type_suggest)
5229 << FixItHint::CreateInsertion(Loc, "typename ");
5231
5232 // Recover by synthesizing a type using the location information that we
5233 // already have.
5234 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5235 SS.getScopeRep(), II);
5236 TypeLocBuilder TLB;
5238 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5240 TL.setNameLoc(NameInfo.getLoc());
5241 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5242
5243 // Overwrite our input TemplateArgumentLoc so that we can recover
5244 // properly.
5247
5248 break;
5249 }
5250 }
5251 // fallthrough
5252 [[fallthrough]];
5253 }
5254 default: {
5255 // We allow instantiating a template with template argument packs when
5256 // building deduction guides or mapping constraint template parameters.
5257 if (Arg.getKind() == TemplateArgument::Pack &&
5258 (CodeSynthesisContexts.back().Kind ==
5261 SugaredConverted.push_back(Arg);
5262 CanonicalConverted.push_back(Arg);
5263 return false;
5264 }
5265 // We have a template type parameter but the template argument
5266 // is not a type.
5267 SourceRange SR = AL.getSourceRange();
5268 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5270
5271 return true;
5272 }
5273 }
5274
5275 if (CheckTemplateArgument(TSI))
5276 return true;
5277
5278 // Objective-C ARC:
5279 // If an explicitly-specified template argument type is a lifetime type
5280 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5281 if (getLangOpts().ObjCAutoRefCount &&
5282 ArgType->isObjCLifetimeType() &&
5283 !ArgType.getObjCLifetime()) {
5284 Qualifiers Qs;
5286 ArgType = Context.getQualifiedType(ArgType, Qs);
5287 }
5288
5289 SugaredConverted.push_back(TemplateArgument(ArgType));
5290 CanonicalConverted.push_back(
5291 TemplateArgument(Context.getCanonicalType(ArgType)));
5292 return false;
5293}
5294
5295/// Substitute template arguments into the default template argument for
5296/// the given template type parameter.
5297///
5298/// \param SemaRef the semantic analysis object for which we are performing
5299/// the substitution.
5300///
5301/// \param Template the template that we are synthesizing template arguments
5302/// for.
5303///
5304/// \param TemplateLoc the location of the template name that started the
5305/// template-id we are checking.
5306///
5307/// \param RAngleLoc the location of the right angle bracket ('>') that
5308/// terminates the template-id.
5309///
5310/// \param Param the template template parameter whose default we are
5311/// substituting into.
5312///
5313/// \param Converted the list of template arguments provided for template
5314/// parameters that precede \p Param in the template parameter list.
5315///
5316/// \param Output the resulting substituted template argument.
5317///
5318/// \returns true if an error occurred.
5320 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5321 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5322 ArrayRef<TemplateArgument> SugaredConverted,
5323 ArrayRef<TemplateArgument> CanonicalConverted,
5324 TemplateArgumentLoc &Output) {
5325 Output = Param->getDefaultArgument();
5326
5327 // If the argument type is dependent, instantiate it now based
5328 // on the previously-computed template arguments.
5329 if (Output.getArgument().isInstantiationDependent()) {
5330 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5331 SugaredConverted,
5332 SourceRange(TemplateLoc, RAngleLoc));
5333 if (Inst.isInvalid())
5334 return true;
5335
5336 // Only substitute for the innermost template argument list.
5337 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5338 /*Final=*/true);
5339 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5340 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5341
5342 bool ForLambdaCallOperator = false;
5343 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5344 ForLambdaCallOperator = Rec->isLambda();
5345 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5346 !ForLambdaCallOperator);
5347
5348 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5349 Param->getDefaultArgumentLoc(),
5350 Param->getDeclName()))
5351 return true;
5352 }
5353
5354 return false;
5355}
5356
5357/// Substitute template arguments into the default template argument for
5358/// the given non-type template parameter.
5359///
5360/// \param SemaRef the semantic analysis object for which we are performing
5361/// the substitution.
5362///
5363/// \param Template the template that we are synthesizing template arguments
5364/// for.
5365///
5366/// \param TemplateLoc the location of the template name that started the
5367/// template-id we are checking.
5368///
5369/// \param RAngleLoc the location of the right angle bracket ('>') that
5370/// terminates the template-id.
5371///
5372/// \param Param the non-type template parameter whose default we are
5373/// substituting into.
5374///
5375/// \param Converted the list of template arguments provided for template
5376/// parameters that precede \p Param in the template parameter list.
5377///
5378/// \returns the substituted template argument, or NULL if an error occurred.
5380 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5381 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5382 ArrayRef<TemplateArgument> SugaredConverted,
5383 ArrayRef<TemplateArgument> CanonicalConverted,
5384 TemplateArgumentLoc &Output) {
5385 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5386 SugaredConverted,
5387 SourceRange(TemplateLoc, RAngleLoc));
5388 if (Inst.isInvalid())
5389 return true;
5390
5391 // Only substitute for the innermost template argument list.
5392 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5393 /*Final=*/true);
5394 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5395 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5396
5397 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5398 EnterExpressionEvaluationContext ConstantEvaluated(
5400 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5401 TemplateArgLists, Output);
5402}
5403
5404/// Substitute template arguments into the default template argument for
5405/// the given template template parameter.
5406///
5407/// \param SemaRef the semantic analysis object for which we are performing
5408/// the substitution.
5409///
5410/// \param Template the template that we are synthesizing template arguments
5411/// for.
5412///
5413/// \param TemplateLoc the location of the template name that started the
5414/// template-id we are checking.
5415///
5416/// \param RAngleLoc the location of the right angle bracket ('>') that
5417/// terminates the template-id.
5418///
5419/// \param Param the template template parameter whose default we are
5420/// substituting into.
5421///
5422/// \param Converted the list of template arguments provided for template
5423/// parameters that precede \p Param in the template parameter list.
5424///
5425/// \param QualifierLoc Will be set to the nested-name-specifier (with
5426/// source-location information) that precedes the template name.
5427///
5428/// \returns the substituted template argument, or NULL if an error occurred.
5430 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5431 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5433 ArrayRef<TemplateArgument> SugaredConverted,
5434 ArrayRef<TemplateArgument> CanonicalConverted,
5435 NestedNameSpecifierLoc &QualifierLoc) {
5437 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5438 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5439 if (Inst.isInvalid())
5440 return TemplateName();
5441
5442 // Only substitute for the innermost template argument list.
5443 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5444 /*Final=*/true);
5445 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5446 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5447
5448 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5449
5450 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5451 QualifierLoc = A.getTemplateQualifierLoc();
5452 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5454 A.getTemplateNameLoc(), TemplateArgLists);
5455}
5456
5458 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5459 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5460 ArrayRef<TemplateArgument> SugaredConverted,
5461 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5462 HasDefaultArg = false;
5463
5464 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5465 if (!hasReachableDefaultArgument(TypeParm))
5466 return TemplateArgumentLoc();
5467
5468 HasDefaultArg = true;
5469 TemplateArgumentLoc Output;
5470 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5471 RAngleLoc, TypeParm, SugaredConverted,
5472 CanonicalConverted, Output))
5473 return TemplateArgumentLoc();
5474 return Output;
5475 }
5476
5477 if (NonTypeTemplateParmDecl *NonTypeParm
5478 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5479 if (!hasReachableDefaultArgument(NonTypeParm))
5480 return TemplateArgumentLoc();
5481
5482 HasDefaultArg = true;
5483 TemplateArgumentLoc Output;
5484 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5485 RAngleLoc, NonTypeParm, SugaredConverted,
5486 CanonicalConverted, Output))
5487 return TemplateArgumentLoc();
5488 return Output;
5489 }
5490
5491 TemplateTemplateParmDecl *TempTempParm
5493 if (!hasReachableDefaultArgument(TempTempParm))
5494 return TemplateArgumentLoc();
5495
5496 HasDefaultArg = true;
5497 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5498 NestedNameSpecifierLoc QualifierLoc;
5500 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5501 SugaredConverted, CanonicalConverted, QualifierLoc);
5502 if (TName.isNull())
5503 return TemplateArgumentLoc();
5504
5505 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5506 QualifierLoc, A.getTemplateNameLoc());
5507}
5508
5509/// Convert a template-argument that we parsed as a type into a template, if
5510/// possible. C++ permits injected-class-names to perform dual service as
5511/// template template arguments and as template type arguments.
5514 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5515 if (!TagLoc)
5516 return TemplateArgumentLoc();
5517
5518 // If this type was written as an injected-class-name, it can be used as a
5519 // template template argument.
5520 // If this type was written as an injected-class-name, it may have been
5521 // converted to a RecordType during instantiation. If the RecordType is
5522 // *not* wrapped in a TemplateSpecializationType and denotes a class
5523 // template specialization, it must have come from an injected-class-name.
5524
5525 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5526 if (Name.isNull())
5527 return TemplateArgumentLoc();
5528
5529 return TemplateArgumentLoc(Context, Name,
5530 /*TemplateKWLoc=*/SourceLocation(),
5531 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5532}
5533
5536 SourceLocation TemplateLoc,
5537 SourceLocation RAngleLoc,
5538 unsigned ArgumentPackIndex,
5541 // Check template type parameters.
5542 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5543 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5544 CTAI.CanonicalConverted);
5545
5546 const TemplateArgument &Arg = ArgLoc.getArgument();
5547 // Check non-type template parameters.
5548 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5549 // Do substitution on the type of the non-type template parameter
5550 // with the template arguments we've seen thus far. But if the
5551 // template has a dependent context then we cannot substitute yet.
5552 QualType NTTPType = NTTP->getType();
5553 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5554 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5555
5556 if (NTTPType->isInstantiationDependentType()) {
5557 // Do substitution on the type of the non-type template parameter.
5558 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5559 CTAI.SugaredConverted,
5560 SourceRange(TemplateLoc, RAngleLoc));
5561 if (Inst.isInvalid())
5562 return true;
5563
5565 /*Final=*/true);
5566 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5567 // If the parameter is a pack expansion, expand this slice of the pack.
5568 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5569 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5570 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5571 NTTP->getDeclName());
5572 } else {
5573 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5574 NTTP->getDeclName());
5575 }
5576
5577 // If that worked, check the non-type template parameter type
5578 // for validity.
5579 if (!NTTPType.isNull())
5580 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5581 NTTP->getLocation());
5582 if (NTTPType.isNull())
5583 return true;
5584 }
5585
5586 auto checkExpr = [&](Expr *E) -> Expr * {
5587 TemplateArgument SugaredResult, CanonicalResult;
5589 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5590 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5591 // If the current template argument causes an error, give up now.
5592 if (Res.isInvalid())
5593 return nullptr;
5594 CTAI.SugaredConverted.push_back(SugaredResult);
5595 CTAI.CanonicalConverted.push_back(CanonicalResult);
5596 return Res.get();
5597 };
5598
5599 switch (Arg.getKind()) {
5601 llvm_unreachable("Should never see a NULL template argument here");
5602
5604 Expr *E = Arg.getAsExpr();
5605 Expr *R = checkExpr(E);
5606 if (!R)
5607 return true;
5608 // If the resulting expression is new, then use it in place of the
5609 // old expression in the template argument.
5610 if (R != E) {
5611 TemplateArgument TA(R, /*IsCanonical=*/false);
5612 ArgLoc = TemplateArgumentLoc(TA, R);
5613 }
5614 break;
5615 }
5616
5617 // As for the converted NTTP kinds, they still might need another
5618 // conversion, as the new corresponding parameter might be different.
5619 // Ideally, we would always perform substitution starting with sugared types
5620 // and never need these, as we would still have expressions. Since these are
5621 // needed so rarely, it's probably a better tradeoff to just convert them
5622 // back to expressions.
5627 // FIXME: StructuralValue is untested here.
5628 ExprResult R =
5630 assert(R.isUsable());
5631 if (!checkExpr(R.get()))
5632 return true;
5633 break;
5634 }
5635
5638 // We were given a template template argument. It may not be ill-formed;
5639 // see below.
5642 // We have a template argument such as \c T::template X, which we
5643 // parsed as a template template argument. However, since we now
5644 // know that we need a non-type template argument, convert this
5645 // template name into an expression.
5646
5647 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5648 ArgLoc.getTemplateNameLoc());
5649
5650 CXXScopeSpec SS;
5651 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5652 // FIXME: the template-template arg was a DependentTemplateName,
5653 // so it was provided with a template keyword. However, its source
5654 // location is not stored in the template argument structure.
5655 SourceLocation TemplateKWLoc;
5657 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5658 nullptr);
5659
5660 // If we parsed the template argument as a pack expansion, create a
5661 // pack expansion expression.
5664 if (E.isInvalid())
5665 return true;
5666 }
5667
5668 TemplateArgument SugaredResult, CanonicalResult;
5670 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5671 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5672 if (E.isInvalid())
5673 return true;
5674
5675 CTAI.SugaredConverted.push_back(SugaredResult);
5676 CTAI.CanonicalConverted.push_back(CanonicalResult);
5677 break;
5678 }
5679
5680 // We have a template argument that actually does refer to a class
5681 // template, alias template, or template template parameter, and
5682 // therefore cannot be a non-type template argument.
5683 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5684 << ArgLoc.getSourceRange();
5686
5687 return true;
5688
5690 // We have a non-type template parameter but the template
5691 // argument is a type.
5692
5693 // C++ [temp.arg]p2:
5694 // In a template-argument, an ambiguity between a type-id and
5695 // an expression is resolved to a type-id, regardless of the
5696 // form of the corresponding template-parameter.
5697 //
5698 // We warn specifically about this case, since it can be rather
5699 // confusing for users.
5700 QualType T = Arg.getAsType();
5701 SourceRange SR = ArgLoc.getSourceRange();
5702 if (T->isFunctionType())
5703 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5704 else
5705 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5707 return true;
5708 }
5709
5711 llvm_unreachable("Caller must expand template argument packs");
5712 }
5713
5714 return false;
5715 }
5716
5717
5718 // Check template template parameters.
5720
5721 TemplateParameterList *Params = TempParm->getTemplateParameters();
5722 if (TempParm->isExpandedParameterPack())
5723 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5724
5725 // Substitute into the template parameter list of the template
5726 // template parameter, since previously-supplied template arguments
5727 // may appear within the template template parameter.
5728 //
5729 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5730 {
5731 // Set up a template instantiation context.
5733 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5734 CTAI.SugaredConverted,
5735 SourceRange(TemplateLoc, RAngleLoc));
5736 if (Inst.isInvalid())
5737 return true;
5738
5739 Params = SubstTemplateParams(
5740 Params, CurContext,
5742 /*Final=*/true),
5743 /*EvaluateConstraints=*/false);
5744 if (!Params)
5745 return true;
5746 }
5747
5748 // C++1z [temp.local]p1: (DR1004)
5749 // When [the injected-class-name] is used [...] as a template-argument for
5750 // a template template-parameter [...] it refers to the class template
5751 // itself.
5752 if (Arg.getKind() == TemplateArgument::Type) {
5754 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5755 if (!ConvertedArg.getArgument().isNull())
5756 ArgLoc = ConvertedArg;
5757 }
5758
5759 switch (Arg.getKind()) {
5761 llvm_unreachable("Should never see a NULL template argument here");
5762
5765 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5766 CTAI.PartialOrdering,
5767 &CTAI.StrictPackMatch))
5768 return true;
5769
5770 CTAI.SugaredConverted.push_back(Arg);
5771 CTAI.CanonicalConverted.push_back(
5772 Context.getCanonicalTemplateArgument(Arg));
5773 break;
5774
5777 auto Kind = 0;
5778 switch (TempParm->templateParameterKind()) {
5780 Kind = 1;
5781 break;
5783 Kind = 2;
5784 break;
5785 default:
5786 break;
5787 }
5788
5789 // We have a template template parameter but the template
5790 // argument does not refer to a template.
5791 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5792 << Kind << getLangOpts().CPlusPlus11;
5793 return true;
5794 }
5795
5800 llvm_unreachable("non-type argument with template template parameter");
5801
5803 llvm_unreachable("Caller must expand template argument packs");
5804 }
5805
5806 return false;
5807}
5808
5809/// Diagnose a missing template argument.
5810template<typename TemplateParmDecl>
5812 TemplateDecl *TD,
5813 const TemplateParmDecl *D,
5815 // Dig out the most recent declaration of the template parameter; there may be
5816 // declarations of the template that are more recent than TD.
5818 ->getTemplateParameters()
5819 ->getParam(D->getIndex()));
5820
5821 // If there's a default argument that's not reachable, diagnose that we're
5822 // missing a module import.
5824 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5826 D->getDefaultArgumentLoc(), Modules,
5828 /*Recover*/true);
5829 return true;
5830 }
5831
5832 // FIXME: If there's a more recent default argument that *is* visible,
5833 // diagnose that it was declared too late.
5834
5836
5837 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5838 << /*not enough args*/0
5840 << TD;
5841 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5842 return true;
5843}
5844
5845/// Check that the given template argument list is well-formed
5846/// for specializing the given template.
5848 TemplateDecl *Template, SourceLocation TemplateLoc,
5849 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5850 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5851 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5853 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5854 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5856}
5857
5858/// Check that the given template argument list is well-formed
5859/// for specializing the given template.
5862 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5863 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5864 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5866
5868 *ConstraintsNotSatisfied = false;
5869
5870 // Make a copy of the template arguments for processing. Only make the
5871 // changes at the end when successful in matching the arguments to the
5872 // template.
5873 TemplateArgumentListInfo NewArgs = TemplateArgs;
5874
5875 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5876
5877 // C++23 [temp.arg.general]p1:
5878 // [...] The type and form of each template-argument specified in
5879 // a template-id shall match the type and form specified for the
5880 // corresponding parameter declared by the template in its
5881 // template-parameter-list.
5882 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5883 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5884 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5885 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5886 LocalInstantiationScope InstScope(*this, true);
5887 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5888 ParamEnd = Params->end(),
5889 Param = ParamBegin;
5890 Param != ParamEnd;
5891 /* increment in loop */) {
5892 if (size_t ParamIdx = Param - ParamBegin;
5893 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5894 // All written arguments should have been consumed by this point.
5895 assert(ArgIdx == NumArgs && "bad default argument deduction");
5896 if (ParamIdx == DefaultArgs.StartPos) {
5897 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5898 // Default arguments from a DeducedTemplateName are already converted.
5899 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5900 CTAI.SugaredConverted.push_back(DefArg);
5901 CTAI.CanonicalConverted.push_back(
5902 Context.getCanonicalTemplateArgument(DefArg));
5903 ++Param;
5904 }
5905 continue;
5906 }
5907 }
5908
5909 // If we have an expanded parameter pack, make sure we don't have too
5910 // many arguments.
5911 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5912 if (*Expansions == SugaredArgumentPack.size()) {
5913 // We're done with this parameter pack. Pack up its arguments and add
5914 // them to the list.
5915 CTAI.SugaredConverted.push_back(
5916 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5917 SugaredArgumentPack.clear();
5918
5919 CTAI.CanonicalConverted.push_back(
5920 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5921 CanonicalArgumentPack.clear();
5922
5923 // This argument is assigned to the next parameter.
5924 ++Param;
5925 continue;
5926 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5927 // Not enough arguments for this parameter pack.
5928 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5929 << /*not enough args*/0
5931 << Template;
5933 return true;
5934 }
5935 }
5936
5937 // Check for builtins producing template packs in this context, we do not
5938 // support them yet.
5939 if (const NonTypeTemplateParmDecl *NTTP =
5940 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5941 NTTP && NTTP->isPackExpansion()) {
5942 auto TL = NTTP->getTypeSourceInfo()
5943 ->getTypeLoc()
5946 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5947 for (const auto &UPP : Unexpanded) {
5948 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5949 if (!TST)
5950 continue;
5951 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5952 // Expanding a built-in pack in this context is not yet supported.
5953 Diag(TL.getEllipsisLoc(),
5954 diag::err_unsupported_builtin_template_pack_expansion)
5955 << TST->getTemplateName();
5956 return true;
5957 }
5958 }
5959
5960 if (ArgIdx < NumArgs) {
5961 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5962 bool NonPackParameter =
5963 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5964 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5965
5966 if (ArgIsExpansion && CTAI.MatchingTTP) {
5967 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5968 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5969 ++Param) {
5970 TemplateArgument &Arg = Args[Param - First];
5971 Arg = ArgLoc.getArgument();
5972 if (!(*Param)->isTemplateParameterPack() ||
5973 getExpandedPackSize(*Param))
5974 Arg = Arg.getPackExpansionPattern();
5975 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5976 SaveAndRestore _1(CTAI.PartialOrdering, false);
5977 SaveAndRestore _2(CTAI.MatchingTTP, true);
5978 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5979 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5981 return true;
5982 Arg = NewArgLoc.getArgument();
5983 CTAI.CanonicalConverted.back().setIsDefaulted(
5984 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5985 CTAI.CanonicalConverted,
5986 Params->getDepth()));
5987 }
5988 ArgLoc = TemplateArgumentLoc(
5991 } else {
5992 SaveAndRestore _1(CTAI.PartialOrdering, false);
5993 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5994 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5996 return true;
5997 CTAI.CanonicalConverted.back().setIsDefaulted(
5998 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5999 *Param, CTAI.CanonicalConverted,
6000 Params->getDepth()));
6001 if (ArgIsExpansion && NonPackParameter) {
6002 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6003 // alias template, builtin template, or concept, and it's not part of
6004 // a parameter pack. This can't be canonicalized, so reject it now.
6006 Template)) {
6007 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6009 : 0;
6010 Diag(ArgLoc.getLocation(),
6011 diag::err_template_expansion_into_fixed_list)
6012 << DiagSelect << ArgLoc.getSourceRange();
6014 return true;
6015 }
6016 }
6017 }
6018
6019 // We're now done with this argument.
6020 ++ArgIdx;
6021
6022 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6023 // Directly convert the remaining arguments, because we don't know what
6024 // parameters they'll match up with.
6025
6026 if (!SugaredArgumentPack.empty()) {
6027 // If we were part way through filling in an expanded parameter pack,
6028 // fall back to just producing individual arguments.
6029 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6030 SugaredArgumentPack.begin(),
6031 SugaredArgumentPack.end());
6032 SugaredArgumentPack.clear();
6033
6034 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6035 CanonicalArgumentPack.begin(),
6036 CanonicalArgumentPack.end());
6037 CanonicalArgumentPack.clear();
6038 }
6039
6040 while (ArgIdx < NumArgs) {
6041 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6042 CTAI.SugaredConverted.push_back(Arg);
6043 CTAI.CanonicalConverted.push_back(
6044 Context.getCanonicalTemplateArgument(Arg));
6045 ++ArgIdx;
6046 }
6047
6048 return false;
6049 }
6050
6051 if ((*Param)->isTemplateParameterPack()) {
6052 // The template parameter was a template parameter pack, so take the
6053 // deduced argument and place it on the argument pack. Note that we
6054 // stay on the same template parameter so that we can deduce more
6055 // arguments.
6056 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6057 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6058 } else {
6059 // Move to the next template parameter.
6060 ++Param;
6061 }
6062 continue;
6063 }
6064
6065 // If we're checking a partial template argument list, we're done.
6066 if (PartialTemplateArgs) {
6067 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6068 CTAI.SugaredConverted.push_back(
6069 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6070 CTAI.CanonicalConverted.push_back(
6071 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6072 }
6073 return false;
6074 }
6075
6076 // If we have a template parameter pack with no more corresponding
6077 // arguments, just break out now and we'll fill in the argument pack below.
6078 if ((*Param)->isTemplateParameterPack()) {
6079 assert(!getExpandedPackSize(*Param) &&
6080 "Should have dealt with this already");
6081
6082 // A non-expanded parameter pack before the end of the parameter list
6083 // only occurs for an ill-formed template parameter list, unless we've
6084 // got a partial argument list for a function template, so just bail out.
6085 if (Param + 1 != ParamEnd) {
6086 assert(
6087 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6088 "Concept templates must have parameter packs at the end.");
6089 return true;
6090 }
6091
6092 CTAI.SugaredConverted.push_back(
6093 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6094 SugaredArgumentPack.clear();
6095
6096 CTAI.CanonicalConverted.push_back(
6097 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6098 CanonicalArgumentPack.clear();
6099
6100 ++Param;
6101 continue;
6102 }
6103
6104 // Check whether we have a default argument.
6105 bool HasDefaultArg;
6106
6107 // Retrieve the default template argument from the template
6108 // parameter. For each kind of template parameter, we substitute the
6109 // template arguments provided thus far and any "outer" template arguments
6110 // (when the template parameter was part of a nested template) into
6111 // the default argument.
6113 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6114 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6115
6116 if (Arg.getArgument().isNull()) {
6117 if (!HasDefaultArg) {
6118 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6119 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6120 NewArgs);
6121 if (NonTypeTemplateParmDecl *NTTP =
6122 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6123 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6124 NewArgs);
6125 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6127 NewArgs);
6128 }
6129 return true;
6130 }
6131
6132 // Introduce an instantiation record that describes where we are using
6133 // the default template argument. We're not actually instantiating a
6134 // template here, we just create this object to put a note into the
6135 // context stack.
6136 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6137 CTAI.SugaredConverted,
6138 SourceRange(TemplateLoc, RAngleLoc));
6139 if (Inst.isInvalid())
6140 return true;
6141
6142 SaveAndRestore _1(CTAI.PartialOrdering, false);
6143 SaveAndRestore _2(CTAI.MatchingTTP, false);
6144 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6145 // Check the default template argument.
6146 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6147 CTAI, CTAK_Specified))
6148 return true;
6149
6150 CTAI.SugaredConverted.back().setIsDefaulted(true);
6151 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6152
6153 // Core issue 150 (assumed resolution): if this is a template template
6154 // parameter, keep track of the default template arguments from the
6155 // template definition.
6156 if (isTemplateTemplateParameter)
6157 NewArgs.addArgument(Arg);
6158
6159 // Move to the next template parameter and argument.
6160 ++Param;
6161 ++ArgIdx;
6162 }
6163
6164 // If we're performing a partial argument substitution, allow any trailing
6165 // pack expansions; they might be empty. This can happen even if
6166 // PartialTemplateArgs is false (the list of arguments is complete but
6167 // still dependent).
6168 if (CTAI.MatchingTTP ||
6170 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6171 while (ArgIdx < NumArgs &&
6172 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6173 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6174 CTAI.SugaredConverted.push_back(Arg);
6175 CTAI.CanonicalConverted.push_back(
6176 Context.getCanonicalTemplateArgument(Arg));
6177 }
6178 }
6179
6180 // If we have any leftover arguments, then there were too many arguments.
6181 // Complain and fail.
6182 if (ArgIdx < NumArgs) {
6183 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6184 << /*too many args*/1
6186 << Template
6187 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6189 return true;
6190 }
6191
6192 // No problems found with the new argument list, propagate changes back
6193 // to caller.
6194 if (UpdateArgsWithConversions)
6195 TemplateArgs = std::move(NewArgs);
6196
6197 if (!PartialTemplateArgs) {
6198 // Setup the context/ThisScope for the case where we are needing to
6199 // re-instantiate constraints outside of normal instantiation.
6200 DeclContext *NewContext = Template->getDeclContext();
6201
6202 // If this template is in a template, make sure we extract the templated
6203 // decl.
6204 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6205 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6206 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6207
6208 Qualifiers ThisQuals;
6209 if (const auto *Method =
6210 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6211 ThisQuals = Method->getMethodQualifiers();
6212
6213 ContextRAII Context(*this, NewContext);
6214 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6215
6217 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6218 /*RelativeToPrimary=*/true,
6219 /*Pattern=*/nullptr,
6220 /*ForConceptInstantiation=*/true);
6221 if (!isa<ConceptDecl>(Template) &&
6223 Template, MLTAL,
6224 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6227 return true;
6228 }
6229 }
6230
6231 return false;
6232}
6233
6234namespace {
6235 class UnnamedLocalNoLinkageFinder
6236 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6237 {
6238 Sema &S;
6239 SourceRange SR;
6240
6242
6243 public:
6244 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6245
6246 bool Visit(QualType T) {
6247 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6248 }
6249
6250#define TYPE(Class, Parent) \
6251 bool Visit##Class##Type(const Class##Type *);
6252#define ABSTRACT_TYPE(Class, Parent) \
6253 bool Visit##Class##Type(const Class##Type *) { return false; }
6254#define NON_CANONICAL_TYPE(Class, Parent) \
6255 bool Visit##Class##Type(const Class##Type *) { return false; }
6256#include "clang/AST/TypeNodes.inc"
6257
6258 bool VisitTagDecl(const TagDecl *Tag);
6259 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6260 };
6261} // end anonymous namespace
6262
6263bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6264 return false;
6265}
6266
6267bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6268 return Visit(T->getElementType());
6269}
6270
6271bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6272 return Visit(T->getPointeeType());
6273}
6274
6275bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6276 const BlockPointerType* T) {
6277 return Visit(T->getPointeeType());
6278}
6279
6280bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6281 const LValueReferenceType* T) {
6282 return Visit(T->getPointeeType());
6283}
6284
6285bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6286 const RValueReferenceType* T) {
6287 return Visit(T->getPointeeType());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6291 const MemberPointerType *T) {
6292 if (Visit(T->getPointeeType()))
6293 return true;
6294 if (auto *RD = T->getMostRecentCXXRecordDecl())
6295 return VisitTagDecl(RD);
6296 return VisitNestedNameSpecifier(T->getQualifier());
6297}
6298
6299bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6300 const ConstantArrayType* T) {
6301 return Visit(T->getElementType());
6302}
6303
6304bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6305 const IncompleteArrayType* T) {
6306 return Visit(T->getElementType());
6307}
6308
6309bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6310 const VariableArrayType* T) {
6311 return Visit(T->getElementType());
6312}
6313
6314bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6315 const DependentSizedArrayType* T) {
6316 return Visit(T->getElementType());
6317}
6318
6319bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6320 const DependentSizedExtVectorType* T) {
6321 return Visit(T->getElementType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6325 const DependentSizedMatrixType *T) {
6326 return Visit(T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6330 const DependentAddressSpaceType *T) {
6331 return Visit(T->getPointeeType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6339 const DependentVectorType *T) {
6340 return Visit(T->getElementType());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6344 return Visit(T->getElementType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6348 const ConstantMatrixType *T) {
6349 return Visit(T->getElementType());
6350}
6351
6352bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6353 const FunctionProtoType* T) {
6354 for (const auto &A : T->param_types()) {
6355 if (Visit(A))
6356 return true;
6357 }
6358
6359 return Visit(T->getReturnType());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6363 const FunctionNoProtoType* T) {
6364 return Visit(T->getReturnType());
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6368 const UnresolvedUsingType*) {
6369 return false;
6370}
6371
6372bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6373 return false;
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6377 return Visit(T->getUnmodifiedType());
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6381 return false;
6382}
6383
6384bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6385 const PackIndexingType *) {
6386 return false;
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6390 const UnaryTransformType*) {
6391 return false;
6392}
6393
6394bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6395 return Visit(T->getDeducedType());
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6399 const DeducedTemplateSpecializationType *T) {
6400 return Visit(T->getDeducedType());
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6404 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6408 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6412 const TemplateTypeParmType*) {
6413 return false;
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6417 const SubstTemplateTypeParmPackType *) {
6418 return false;
6419}
6420
6421bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6422 const SubstBuiltinTemplatePackType *) {
6423 return false;
6424}
6425
6426bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6427 const TemplateSpecializationType*) {
6428 return false;
6429}
6430
6431bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6432 const InjectedClassNameType* T) {
6433 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6434}
6435
6436bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6437 const DependentNameType* T) {
6438 return VisitNestedNameSpecifier(T->getQualifier());
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6442 const PackExpansionType* T) {
6443 return Visit(T->getPattern());
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6447 return false;
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6451 const ObjCInterfaceType *) {
6452 return false;
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6456 const ObjCObjectPointerType *) {
6457 return false;
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6461 return Visit(T->getValueType());
6462}
6463
6464bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6465 const OverflowBehaviorType *T) {
6466 return Visit(T->getUnderlyingType());
6467}
6468
6469bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6470 return false;
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6474 return false;
6475}
6476
6477bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6478 const ArrayParameterType *T) {
6479 return VisitConstantArrayType(T);
6480}
6481
6482bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6483 const DependentBitIntType *T) {
6484 return false;
6485}
6486
6487bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6488 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6489 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6490 ? diag::warn_cxx98_compat_template_arg_local_type
6491 : diag::ext_template_arg_local_type)
6492 << S.Context.getCanonicalTagType(Tag) << SR;
6493 return true;
6494 }
6495
6496 if (!Tag->hasNameForLinkage()) {
6497 S.Diag(SR.getBegin(),
6498 S.getLangOpts().CPlusPlus11 ?
6499 diag::warn_cxx98_compat_template_arg_unnamed_type :
6500 diag::ext_template_arg_unnamed_type) << SR;
6501 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6502 return true;
6503 }
6504
6505 return false;
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6509 NestedNameSpecifier NNS) {
6510 switch (NNS.getKind()) {
6515 return false;
6517 return Visit(QualType(NNS.getAsType(), 0));
6518 }
6519 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6520}
6521
6522bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6523 const HLSLAttributedResourceType *T) {
6524 if (T->hasContainedType() && Visit(T->getContainedType()))
6525 return true;
6526 return Visit(T->getWrappedType());
6527}
6528
6529bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6530 const HLSLInlineSpirvType *T) {
6531 for (auto &Operand : T->getOperands())
6532 if (Operand.isConstant() && Operand.isLiteral())
6533 if (Visit(Operand.getResultType()))
6534 return true;
6535 return false;
6536}
6537
6539 assert(ArgInfo && "invalid TypeSourceInfo");
6540 QualType Arg = ArgInfo->getType();
6541 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6542 QualType CanonArg = Context.getCanonicalType(Arg);
6543
6544 if (CanonArg->isVariablyModifiedType()) {
6545 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6546 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6547 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6548 }
6549
6550 // C++03 [temp.arg.type]p2:
6551 // A local type, a type with no linkage, an unnamed type or a type
6552 // compounded from any of these types shall not be used as a
6553 // template-argument for a template type-parameter.
6554 //
6555 // C++11 allows these, and even in C++03 we allow them as an extension with
6556 // a warning.
6557 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6558 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6559 (void)Finder.Visit(CanonArg);
6560 }
6561
6562 return false;
6563}
6564
6570
6571/// Determine whether the given template argument is a null pointer
6572/// value of the appropriate type.
6575 QualType ParamType, Expr *Arg,
6576 Decl *Entity = nullptr) {
6577 if (Arg->isValueDependent() || Arg->isTypeDependent())
6578 return NPV_NotNullPointer;
6579
6580 // dllimport'd entities aren't constant but are available inside of template
6581 // arguments.
6582 if (Entity && Entity->hasAttr<DLLImportAttr>())
6583 return NPV_NotNullPointer;
6584
6585 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6586 llvm_unreachable(
6587 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6588
6589 if (!S.getLangOpts().CPlusPlus11)
6590 return NPV_NotNullPointer;
6591
6592 // Determine whether we have a constant expression.
6594 if (ArgRV.isInvalid())
6595 return NPV_Error;
6596 Arg = ArgRV.get();
6597
6598 Expr::EvalResult EvalResult;
6600 EvalResult.Diag = &Notes;
6601 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6602 EvalResult.HasSideEffects) {
6603 SourceLocation DiagLoc = Arg->getExprLoc();
6604
6605 // If our only note is the usual "invalid subexpression" note, just point
6606 // the caret at its location rather than producing an essentially
6607 // redundant note.
6608 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6609 diag::note_invalid_subexpr_in_const_expr) {
6610 DiagLoc = Notes[0].first;
6611 Notes.clear();
6612 }
6613
6614 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6615 << Arg->getType() << Arg->getSourceRange();
6616 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6617 S.Diag(Notes[I].first, Notes[I].second);
6618
6620 return NPV_Error;
6621 }
6622
6623 // C++11 [temp.arg.nontype]p1:
6624 // - an address constant expression of type std::nullptr_t
6625 if (Arg->getType()->isNullPtrType())
6626 return NPV_NullPointer;
6627
6628 // - a constant expression that evaluates to a null pointer value (4.10); or
6629 // - a constant expression that evaluates to a null member pointer value
6630 // (4.11); or
6631 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6632 (EvalResult.Val.isMemberPointer() &&
6633 !EvalResult.Val.getMemberPointerDecl())) {
6634 // If our expression has an appropriate type, we've succeeded.
6635 bool ObjCLifetimeConversion;
6636 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6637 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6638 ObjCLifetimeConversion))
6639 return NPV_NullPointer;
6640
6641 // The types didn't match, but we know we got a null pointer; complain,
6642 // then recover as if the types were correct.
6643 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6644 << Arg->getType() << ParamType << Arg->getSourceRange();
6646 return NPV_NullPointer;
6647 }
6648
6649 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6650 // We found a pointer that isn't null, but doesn't refer to an object.
6651 // We could just return NPV_NotNullPointer, but we can print a better
6652 // message with the information we have here.
6653 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6654 << EvalResult.Val.getAsString(S.Context, ParamType);
6656 return NPV_Error;
6657 }
6658
6659 // If we don't have a null pointer value, but we do have a NULL pointer
6660 // constant, suggest a cast to the appropriate type.
6662 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6663 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6664 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6666 ")");
6668 return NPV_NullPointer;
6669 }
6670
6671 // FIXME: If we ever want to support general, address-constant expressions
6672 // as non-type template arguments, we should return the ExprResult here to
6673 // be interpreted by the caller.
6674 return NPV_NotNullPointer;
6675}
6676
6677/// Checks whether the given template argument is compatible with its
6678/// template parameter.
6679static bool
6681 QualType ParamType, Expr *ArgIn,
6682 Expr *Arg, QualType ArgType) {
6683 bool ObjCLifetimeConversion;
6684 if (ParamType->isPointerType() &&
6685 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6686 S.IsQualificationConversion(ArgType, ParamType, false,
6687 ObjCLifetimeConversion)) {
6688 // For pointer-to-object types, qualification conversions are
6689 // permitted.
6690 } else {
6691 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6692 if (!ParamRef->getPointeeType()->isFunctionType()) {
6693 // C++ [temp.arg.nontype]p5b3:
6694 // For a non-type template-parameter of type reference to
6695 // object, no conversions apply. The type referred to by the
6696 // reference may be more cv-qualified than the (otherwise
6697 // identical) type of the template- argument. The
6698 // template-parameter is bound directly to the
6699 // template-argument, which shall be an lvalue.
6700
6701 // FIXME: Other qualifiers?
6702 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6703 unsigned ArgQuals = ArgType.getCVRQualifiers();
6704
6705 if ((ParamQuals | ArgQuals) != ParamQuals) {
6706 S.Diag(Arg->getBeginLoc(),
6707 diag::err_template_arg_ref_bind_ignores_quals)
6708 << ParamType << Arg->getType() << Arg->getSourceRange();
6710 return true;
6711 }
6712 }
6713 }
6714
6715 // At this point, the template argument refers to an object or
6716 // function with external linkage. We now need to check whether the
6717 // argument and parameter types are compatible.
6718 if (!S.Context.hasSameUnqualifiedType(ArgType,
6719 ParamType.getNonReferenceType())) {
6720 // We can't perform this conversion or binding.
6721 if (ParamType->isReferenceType())
6722 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6723 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6724 else
6725 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6726 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6728 return true;
6729 }
6730 }
6731
6732 return false;
6733}
6734
6735/// Checks whether the given template argument is the address
6736/// of an object or function according to C++ [temp.arg.nontype]p1.
6738 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6739 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6740 bool Invalid = false;
6741 Expr *Arg = ArgIn;
6742 QualType ArgType = Arg->getType();
6743
6744 bool AddressTaken = false;
6745 SourceLocation AddrOpLoc;
6746 if (S.getLangOpts().MicrosoftExt) {
6747 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6748 // dereference and address-of operators.
6749 Arg = Arg->IgnoreParenCasts();
6750
6751 bool ExtWarnMSTemplateArg = false;
6752 UnaryOperatorKind FirstOpKind;
6753 SourceLocation FirstOpLoc;
6754 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6755 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6756 if (UnOpKind == UO_Deref)
6757 ExtWarnMSTemplateArg = true;
6758 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6759 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6760 if (!AddrOpLoc.isValid()) {
6761 FirstOpKind = UnOpKind;
6762 FirstOpLoc = UnOp->getOperatorLoc();
6763 }
6764 } else
6765 break;
6766 }
6767 if (FirstOpLoc.isValid()) {
6768 if (ExtWarnMSTemplateArg)
6769 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6770 << ArgIn->getSourceRange();
6771
6772 if (FirstOpKind == UO_AddrOf)
6773 AddressTaken = true;
6774 else if (Arg->getType()->isPointerType()) {
6775 // We cannot let pointers get dereferenced here, that is obviously not a
6776 // constant expression.
6777 assert(FirstOpKind == UO_Deref);
6778 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6779 << Arg->getSourceRange();
6780 }
6781 }
6782 } else {
6783 // See through any implicit casts we added to fix the type.
6784 Arg = Arg->IgnoreImpCasts();
6785
6786 // C++ [temp.arg.nontype]p1:
6787 //
6788 // A template-argument for a non-type, non-template
6789 // template-parameter shall be one of: [...]
6790 //
6791 // -- the address of an object or function with external
6792 // linkage, including function templates and function
6793 // template-ids but excluding non-static class members,
6794 // expressed as & id-expression where the & is optional if
6795 // the name refers to a function or array, or if the
6796 // corresponding template-parameter is a reference; or
6797
6798 // In C++98/03 mode, give an extension warning on any extra parentheses.
6799 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6800 bool ExtraParens = false;
6801 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6802 if (!Invalid && !ExtraParens) {
6803 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6804 << Arg->getSourceRange();
6805 ExtraParens = true;
6806 }
6807
6808 Arg = Parens->getSubExpr();
6809 }
6810
6811 while (SubstNonTypeTemplateParmExpr *subst =
6812 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6813 Arg = subst->getReplacement()->IgnoreImpCasts();
6814
6815 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6816 if (UnOp->getOpcode() == UO_AddrOf) {
6817 Arg = UnOp->getSubExpr();
6818 AddressTaken = true;
6819 AddrOpLoc = UnOp->getOperatorLoc();
6820 }
6821 }
6822
6823 while (SubstNonTypeTemplateParmExpr *subst =
6824 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6825 Arg = subst->getReplacement()->IgnoreImpCasts();
6826 }
6827
6828 ValueDecl *Entity = nullptr;
6829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6830 Entity = DRE->getDecl();
6831 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6832 Entity = CUE->getGuidDecl();
6833
6834 // If our parameter has pointer type, check for a null template value.
6835 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6836 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6837 Entity)) {
6838 case NPV_NullPointer:
6839 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6840 SugaredConverted = TemplateArgument(ParamType,
6841 /*isNullPtr=*/true);
6842 CanonicalConverted =
6844 /*isNullPtr=*/true);
6845 return false;
6846
6847 case NPV_Error:
6848 return true;
6849
6850 case NPV_NotNullPointer:
6851 break;
6852 }
6853 }
6854
6855 // Stop checking the precise nature of the argument if it is value dependent,
6856 // it should be checked when instantiated.
6857 if (Arg->isValueDependent()) {
6858 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6859 CanonicalConverted =
6860 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6861 return false;
6862 }
6863
6864 if (!Entity) {
6865 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6866 << Arg->getSourceRange();
6868 return true;
6869 }
6870
6871 // Cannot refer to non-static data members
6872 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6873 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6874 << Entity << Arg->getSourceRange();
6876 return true;
6877 }
6878
6879 // Cannot refer to non-static member functions
6880 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6881 if (!Method->isStatic()) {
6882 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6883 << Method << Arg->getSourceRange();
6885 return true;
6886 }
6887 }
6888
6889 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6890 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6891 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6892
6893 // A non-type template argument must refer to an object or function.
6894 if (!Func && !Var && !Guid) {
6895 // We found something, but we don't know specifically what it is.
6896 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6897 << Arg->getSourceRange();
6898 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6899 return true;
6900 }
6901
6902 // Address / reference template args must have external linkage in C++98.
6903 if (Entity->getFormalLinkage() == Linkage::Internal) {
6904 S.Diag(Arg->getBeginLoc(),
6905 S.getLangOpts().CPlusPlus11
6906 ? diag::warn_cxx98_compat_template_arg_object_internal
6907 : diag::ext_template_arg_object_internal)
6908 << !Func << Entity << Arg->getSourceRange();
6909 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6910 << !Func;
6911 } else if (!Entity->hasLinkage()) {
6912 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6913 << !Func << Entity << Arg->getSourceRange();
6914 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6915 << !Func;
6916 return true;
6917 }
6918
6919 if (Var) {
6920 // A value of reference type is not an object.
6921 if (Var->getType()->isReferenceType()) {
6922 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6923 << Var->getType() << Arg->getSourceRange();
6925 return true;
6926 }
6927
6928 // A template argument must have static storage duration.
6929 if (Var->getTLSKind()) {
6930 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6931 << Arg->getSourceRange();
6932 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6933 return true;
6934 }
6935 }
6936
6937 if (AddressTaken && ParamType->isReferenceType()) {
6938 // If we originally had an address-of operator, but the
6939 // parameter has reference type, complain and (if things look
6940 // like they will work) drop the address-of operator.
6941 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6942 ParamType.getNonReferenceType())) {
6943 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6944 << ParamType;
6946 return true;
6947 }
6948
6949 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6950 << ParamType
6951 << FixItHint::CreateRemoval(AddrOpLoc);
6953
6954 ArgType = Entity->getType();
6955 }
6956
6957 // If the template parameter has pointer type, either we must have taken the
6958 // address or the argument must decay to a pointer.
6959 if (!AddressTaken && ParamType->isPointerType()) {
6960 if (Func) {
6961 // Function-to-pointer decay.
6962 ArgType = S.Context.getPointerType(Func->getType());
6963 } else if (Entity->getType()->isArrayType()) {
6964 // Array-to-pointer decay.
6965 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6966 } else {
6967 // If the template parameter has pointer type but the address of
6968 // this object was not taken, complain and (possibly) recover by
6969 // taking the address of the entity.
6970 ArgType = S.Context.getPointerType(Entity->getType());
6971 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6972 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6973 << ParamType;
6975 return true;
6976 }
6977
6978 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6979 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6980
6982 }
6983 }
6984
6985 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6986 Arg, ArgType))
6987 return true;
6988
6989 // Create the template argument.
6990 SugaredConverted = TemplateArgument(Entity, ParamType);
6991 CanonicalConverted =
6993 S.Context.getCanonicalType(ParamType));
6994 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6995 return false;
6996}
6997
6998/// Checks whether the given template argument is a pointer to
6999/// member constant according to C++ [temp.arg.nontype]p1.
7001 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7002 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7003 bool Invalid = false;
7004
7005 Expr *Arg = ResultArg;
7006 bool ObjCLifetimeConversion;
7007
7008 // C++ [temp.arg.nontype]p1:
7009 //
7010 // A template-argument for a non-type, non-template
7011 // template-parameter shall be one of: [...]
7012 //
7013 // -- a pointer to member expressed as described in 5.3.1.
7014 DeclRefExpr *DRE = nullptr;
7015
7016 // In C++98/03 mode, give an extension warning on any extra parentheses.
7017 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7018 bool ExtraParens = false;
7019 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7020 if (!Invalid && !ExtraParens) {
7021 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7022 << Arg->getSourceRange();
7023 ExtraParens = true;
7024 }
7025
7026 Arg = Parens->getSubExpr();
7027 }
7028
7029 while (SubstNonTypeTemplateParmExpr *subst =
7030 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7031 Arg = subst->getReplacement()->IgnoreImpCasts();
7032
7033 // A pointer-to-member constant written &Class::member.
7034 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7035 if (UnOp->getOpcode() == UO_AddrOf) {
7036 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7037 if (DRE && !DRE->getQualifier())
7038 DRE = nullptr;
7039 }
7040 }
7041 // A constant of pointer-to-member type.
7042 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7043 ValueDecl *VD = DRE->getDecl();
7044 if (VD->getType()->isMemberPointerType()) {
7046 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7047 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7048 CanonicalConverted =
7049 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7050 } else {
7051 SugaredConverted = TemplateArgument(VD, ParamType);
7052 CanonicalConverted =
7054 S.Context.getCanonicalType(ParamType));
7055 }
7056 return Invalid;
7057 }
7058 }
7059
7060 DRE = nullptr;
7061 }
7062
7063 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7064
7065 // Check for a null pointer value.
7066 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7067 Entity)) {
7068 case NPV_Error:
7069 return true;
7070 case NPV_NullPointer:
7071 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7072 SugaredConverted = TemplateArgument(ParamType,
7073 /*isNullPtr*/ true);
7074 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7075 /*isNullPtr*/ true);
7076 return false;
7077 case NPV_NotNullPointer:
7078 break;
7079 }
7080
7081 if (S.IsQualificationConversion(ResultArg->getType(),
7082 ParamType.getNonReferenceType(), false,
7083 ObjCLifetimeConversion)) {
7084 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7085 ResultArg->getValueKind())
7086 .get();
7087 } else if (!S.Context.hasSameUnqualifiedType(
7088 ResultArg->getType(), ParamType.getNonReferenceType())) {
7089 // We can't perform this conversion.
7090 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7091 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7093 return true;
7094 }
7095
7096 if (!DRE)
7097 return S.Diag(Arg->getBeginLoc(),
7098 diag::err_template_arg_not_pointer_to_member_form)
7099 << Arg->getSourceRange();
7100
7101 if (isa<FieldDecl>(DRE->getDecl()) ||
7103 isa<CXXMethodDecl>(DRE->getDecl())) {
7104 assert((isa<FieldDecl>(DRE->getDecl()) ||
7107 ->isImplicitObjectMemberFunction()) &&
7108 "Only non-static member pointers can make it here");
7109
7110 // Okay: this is the address of a non-static member, and therefore
7111 // a member pointer constant.
7112 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7113 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7114 CanonicalConverted =
7115 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7116 } else {
7117 ValueDecl *D = DRE->getDecl();
7118 SugaredConverted = TemplateArgument(D, ParamType);
7119 CanonicalConverted =
7121 S.Context.getCanonicalType(ParamType));
7122 }
7123 return Invalid;
7124 }
7125
7126 // We found something else, but we don't know specifically what it is.
7127 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7128 << Arg->getSourceRange();
7129 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7130 return true;
7131}
7132
7133/// Check a template argument against its corresponding
7134/// non-type template parameter.
7135///
7136/// This routine implements the semantics of C++ [temp.arg.nontype].
7137/// If an error occurred, it returns ExprError(); otherwise, it
7138/// returns the converted template argument. \p ParamType is the
7139/// type of the non-type template parameter after it has been instantiated.
7141 Expr *Arg,
7142 TemplateArgument &SugaredConverted,
7143 TemplateArgument &CanonicalConverted,
7144 bool StrictCheck,
7146 SourceLocation StartLoc = Arg->getBeginLoc();
7147 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7148 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7149 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7150 DeductionArg = NewDeductionArg;
7151 if (ArgPE) {
7152 // Recreate a pack expansion if we unwrapped one.
7153 Arg = new (Context) PackExpansionExpr(
7154 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7155 } else {
7156 Arg = DeductionArg;
7157 }
7158 };
7159
7160 // If the parameter type somehow involves auto, deduce the type now.
7161 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7162 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7163 if (IsDeduced) {
7164 // When checking a deduced template argument, deduce from its type even if
7165 // the type is dependent, in order to check the types of non-type template
7166 // arguments line up properly in partial ordering.
7167 TypeSourceInfo *TSI =
7168 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7170 InitializedEntity Entity =
7173 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7174 Expr *Inits[1] = {DeductionArg};
7175 ParamType =
7177 if (ParamType.isNull())
7178 return ExprError();
7179 } else {
7180 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7181 Param->getTemplateDepth() + 1);
7182 ParamType = QualType();
7184 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7185 /*DependentDeduction=*/true,
7186 // We do not check constraints right now because the
7187 // immediately-declared constraint of the auto type is
7188 // also an associated constraint, and will be checked
7189 // along with the other associated constraints after
7190 // checking the template argument list.
7191 /*IgnoreConstraints=*/true);
7193 ParamType = TSI->getType();
7194 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7196 return ExprError();
7197 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7198 Diag(Arg->getExprLoc(),
7199 diag::err_non_type_template_parm_type_deduction_failure)
7200 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7201 << Arg->getSourceRange();
7203 return ExprError();
7204 }
7205 ParamType = SubstAutoTypeDependent(ParamType);
7206 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7207 }
7208 }
7209 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7210 // an error. The error message normally references the parameter
7211 // declaration, but here we'll pass the argument location because that's
7212 // where the parameter type is deduced.
7213 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7214 if (ParamType.isNull()) {
7216 return ExprError();
7217 }
7218 }
7219
7220 // We should have already dropped all cv-qualifiers by now.
7221 assert(!ParamType.hasQualifiers() &&
7222 "non-type template parameter type cannot be qualified");
7223
7224 // If either the parameter has a dependent type or the argument is
7225 // type-dependent, there's nothing we can check now.
7226 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7227 // Force the argument to the type of the parameter to maintain invariants.
7228 if (!IsDeduced) {
7230 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7231 ParamType->isLValueReferenceType() ? VK_LValue
7232 : ParamType->isRValueReferenceType() ? VK_XValue
7233 : VK_PRValue);
7234 if (E.isInvalid())
7235 return ExprError();
7236 setDeductionArg(E.get());
7237 }
7238 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7239 CanonicalConverted = TemplateArgument(
7240 Context.getCanonicalTemplateArgument(SugaredConverted));
7241 return Arg;
7242 }
7243
7244 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7245 if (CTAK == CTAK_Deduced && !StrictCheck &&
7246 (ParamType->isReferenceType()
7247 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7248 DeductionArg->getType())
7249 : !Context.hasSameUnqualifiedType(ParamType,
7250 DeductionArg->getType()))) {
7251 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7252 // we should actually be checking the type of the template argument in P,
7253 // not the type of the template argument deduced from A, against the
7254 // template parameter type.
7255 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7256 << Arg->getType() << ParamType.getUnqualifiedType();
7258 return ExprError();
7259 }
7260
7261 // If the argument is a pack expansion, we don't know how many times it would
7262 // expand. If we continue checking the argument, this will make the template
7263 // definition ill-formed if it would be ill-formed for any number of
7264 // expansions during instantiation time. When partial ordering or matching
7265 // template template parameters, this is exactly what we want. Otherwise, the
7266 // normal template rules apply: we accept the template if it would be valid
7267 // for any number of expansions (i.e. none).
7268 if (ArgPE && !StrictCheck) {
7269 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7270 CanonicalConverted = TemplateArgument(
7271 Context.getCanonicalTemplateArgument(SugaredConverted));
7272 return Arg;
7273 }
7274
7275 // Avoid making a copy when initializing a template parameter of class type
7276 // from a template parameter object of the same type. This is going beyond
7277 // the standard, but is required for soundness: in
7278 // template<A a> struct X { X *p; X<a> *q; };
7279 // ... we need p and q to have the same type.
7280 //
7281 // Similarly, don't inject a call to a copy constructor when initializing
7282 // from a template parameter of the same type.
7283 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7284 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7285 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7286 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7287 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7288
7289 SugaredConverted = TemplateArgument(TPO, ParamType);
7290 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7291 ParamType.getCanonicalType());
7292 return Arg;
7293 }
7295 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7296 CanonicalConverted =
7297 Context.getCanonicalTemplateArgument(SugaredConverted);
7298 return Arg;
7299 }
7300 }
7301
7302 // The initialization of the parameter from the argument is
7303 // a constant-evaluated context.
7306
7307 bool IsConvertedConstantExpression = true;
7308 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7310 StartLoc, /*DirectInit=*/false, DeductionArg);
7311 Expr *Inits[1] = {DeductionArg};
7312 InitializedEntity Entity =
7314 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7315 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7316 if (Result.isInvalid() || !Result.get())
7317 return ExprError();
7319 if (Result.isInvalid() || !Result.get())
7320 return ExprError();
7321 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7322 /*DiscardedValue=*/false,
7323 /*IsConstexpr=*/true,
7324 /*IsTemplateArgument=*/true)
7325 .get());
7326 IsConvertedConstantExpression = false;
7327 }
7328
7329 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7330 // C++17 [temp.arg.nontype]p1:
7331 // A template-argument for a non-type template parameter shall be
7332 // a converted constant expression of the type of the template-parameter.
7333 APValue Value;
7334 ExprResult ArgResult;
7335 if (IsConvertedConstantExpression) {
7337 DeductionArg, ParamType,
7338 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7339 assert(!ArgResult.isUnset());
7340 if (ArgResult.isInvalid()) {
7342 return ExprError();
7343 }
7344 } else {
7345 ArgResult = DeductionArg;
7346 }
7347
7348 // For a value-dependent argument, CheckConvertedConstantExpression is
7349 // permitted (and expected) to be unable to determine a value.
7350 if (ArgResult.get()->isValueDependent()) {
7351 setDeductionArg(ArgResult.get());
7352 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7353 CanonicalConverted =
7354 Context.getCanonicalTemplateArgument(SugaredConverted);
7355 return Arg;
7356 }
7357
7358 APValue PreNarrowingValue;
7360 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7361 false, PreNarrowingValue);
7362 if (ArgResult.isInvalid())
7363 return ExprError();
7364 setDeductionArg(ArgResult.get());
7365
7366 if (Value.isLValue()) {
7367 APValue::LValueBase Base = Value.getLValueBase();
7368 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7369 // For a non-type template-parameter of pointer or reference type,
7370 // the value of the constant expression shall not refer to
7371 assert(ParamType->isPointerOrReferenceType() ||
7372 ParamType->isNullPtrType());
7373 // -- a temporary object
7374 // -- a string literal
7375 // -- the result of a typeid expression, or
7376 // -- a predefined __func__ variable
7377 if (Base &&
7378 (!VD ||
7380 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7381 << Arg->getSourceRange();
7382 return ExprError();
7383 }
7384
7385 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7386 VD->getType()->isArrayType() &&
7387 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7388 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7389 if (ArgPE) {
7390 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7391 CanonicalConverted =
7392 Context.getCanonicalTemplateArgument(SugaredConverted);
7393 } else {
7394 SugaredConverted = TemplateArgument(VD, ParamType);
7395 CanonicalConverted =
7397 ParamType.getCanonicalType());
7398 }
7399 return Arg;
7400 }
7401
7402 // -- a subobject [until C++20]
7403 if (!getLangOpts().CPlusPlus20) {
7404 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7405 Value.isLValueOnePastTheEnd()) {
7406 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7407 << Value.getAsString(Context, ParamType);
7408 return ExprError();
7409 }
7410 assert((VD || !ParamType->isReferenceType()) &&
7411 "null reference should not be a constant expression");
7412 assert((!VD || !ParamType->isNullPtrType()) &&
7413 "non-null value of type nullptr_t?");
7414 }
7415 }
7416
7417 if (Value.isAddrLabelDiff())
7418 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7419
7420 if (ArgPE) {
7421 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7422 CanonicalConverted =
7423 Context.getCanonicalTemplateArgument(SugaredConverted);
7424 } else {
7425 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7426 CanonicalConverted =
7428 }
7429 return Arg;
7430 }
7431
7432 // These should have all been handled above using the C++17 rules.
7433 assert(!ArgPE && !StrictCheck);
7434
7435 // C++ [temp.arg.nontype]p5:
7436 // The following conversions are performed on each expression used
7437 // as a non-type template-argument. If a non-type
7438 // template-argument cannot be converted to the type of the
7439 // corresponding template-parameter then the program is
7440 // ill-formed.
7441 if (ParamType->isIntegralOrEnumerationType()) {
7442 // C++11:
7443 // -- for a non-type template-parameter of integral or
7444 // enumeration type, conversions permitted in a converted
7445 // constant expression are applied.
7446 //
7447 // C++98:
7448 // -- for a non-type template-parameter of integral or
7449 // enumeration type, integral promotions (4.5) and integral
7450 // conversions (4.7) are applied.
7451
7452 if (getLangOpts().CPlusPlus11) {
7453 // C++ [temp.arg.nontype]p1:
7454 // A template-argument for a non-type, non-template template-parameter
7455 // shall be one of:
7456 //
7457 // -- for a non-type template-parameter of integral or enumeration
7458 // type, a converted constant expression of the type of the
7459 // template-parameter; or
7460 llvm::APSInt Value;
7462 Arg, ParamType, Value, CCEKind::TemplateArg);
7463 if (ArgResult.isInvalid())
7464 return ExprError();
7465 Arg = ArgResult.get();
7466
7467 // We can't check arbitrary value-dependent arguments.
7468 if (Arg->isValueDependent()) {
7469 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7470 CanonicalConverted =
7471 Context.getCanonicalTemplateArgument(SugaredConverted);
7472 return Arg;
7473 }
7474
7475 // Widen the argument value to sizeof(parameter type). This is almost
7476 // always a no-op, except when the parameter type is bool. In
7477 // that case, this may extend the argument from 1 bit to 8 bits.
7478 QualType IntegerType = ParamType;
7479 if (const auto *ED = IntegerType->getAsEnumDecl())
7480 IntegerType = ED->getIntegerType();
7481 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7482 ? Context.getIntWidth(IntegerType)
7483 : Context.getTypeSize(IntegerType));
7484
7485 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7486 CanonicalConverted =
7487 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7488 return Arg;
7489 }
7490
7491 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7492 if (ArgResult.isInvalid())
7493 return ExprError();
7494 Arg = ArgResult.get();
7495
7496 QualType ArgType = Arg->getType();
7497
7498 // C++ [temp.arg.nontype]p1:
7499 // A template-argument for a non-type, non-template
7500 // template-parameter shall be one of:
7501 //
7502 // -- an integral constant-expression of integral or enumeration
7503 // type; or
7504 // -- the name of a non-type template-parameter; or
7505 llvm::APSInt Value;
7506 if (!ArgType->isIntegralOrEnumerationType()) {
7507 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7508 << ArgType << Arg->getSourceRange();
7510 return ExprError();
7511 }
7512 if (!Arg->isValueDependent()) {
7513 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7514 QualType T;
7515
7516 public:
7517 TmplArgICEDiagnoser(QualType T) : T(T) { }
7518
7519 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7520 SourceLocation Loc) override {
7521 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7522 }
7523 } Diagnoser(ArgType);
7524
7525 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7526 if (!Arg)
7527 return ExprError();
7528 }
7529
7530 // From here on out, all we care about is the unqualified form
7531 // of the argument type.
7532 ArgType = ArgType.getUnqualifiedType();
7533
7534 // Try to convert the argument to the parameter's type.
7535 if (Context.hasSameType(ParamType, ArgType)) {
7536 // Okay: no conversion necessary
7537 } else if (ParamType->isBooleanType()) {
7538 // This is an integral-to-boolean conversion.
7539 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7540 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7541 !ParamType->isEnumeralType()) {
7542 // This is an integral promotion or conversion.
7543 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7544 } else {
7545 // We can't perform this conversion.
7546 Diag(StartLoc, diag::err_template_arg_not_convertible)
7547 << Arg->getType() << ParamType << Arg->getSourceRange();
7549 return ExprError();
7550 }
7551
7552 // Add the value of this argument to the list of converted
7553 // arguments. We use the bitwidth and signedness of the template
7554 // parameter.
7555 if (Arg->isValueDependent()) {
7556 // The argument is value-dependent. Create a new
7557 // TemplateArgument with the converted expression.
7558 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7559 CanonicalConverted =
7560 Context.getCanonicalTemplateArgument(SugaredConverted);
7561 return Arg;
7562 }
7563
7564 QualType IntegerType = ParamType;
7565 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7566 IntegerType = ED->getIntegerType();
7567 }
7568
7569 if (ParamType->isBooleanType()) {
7570 // Value must be zero or one.
7571 Value = Value != 0;
7572 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7573 if (Value.getBitWidth() != AllowedBits)
7574 Value = Value.extOrTrunc(AllowedBits);
7575 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7576 } else {
7577 llvm::APSInt OldValue = Value;
7578
7579 // Coerce the template argument's value to the value it will have
7580 // based on the template parameter's type.
7581 unsigned AllowedBits = IntegerType->isBitIntType()
7582 ? Context.getIntWidth(IntegerType)
7583 : Context.getTypeSize(IntegerType);
7584 if (Value.getBitWidth() != AllowedBits)
7585 Value = Value.extOrTrunc(AllowedBits);
7586 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7587
7588 // Complain if an unsigned parameter received a negative value.
7589 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7590 (OldValue.isSigned() && OldValue.isNegative())) {
7591 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7592 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7593 << Arg->getSourceRange();
7595 }
7596
7597 // Complain if we overflowed the template parameter's type.
7598 unsigned RequiredBits;
7599 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7600 RequiredBits = OldValue.getActiveBits();
7601 else if (OldValue.isUnsigned())
7602 RequiredBits = OldValue.getActiveBits() + 1;
7603 else
7604 RequiredBits = OldValue.getSignificantBits();
7605 if (RequiredBits > AllowedBits) {
7606 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7607 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7608 << Arg->getSourceRange();
7610 }
7611 }
7612
7613 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7614 SugaredConverted = TemplateArgument(Context, Value, T);
7615 CanonicalConverted =
7616 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7617 return Arg;
7618 }
7619
7620 QualType ArgType = Arg->getType();
7621 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7622
7623 // Handle pointer-to-function, reference-to-function, and
7624 // pointer-to-member-function all in (roughly) the same way.
7625 if (// -- For a non-type template-parameter of type pointer to
7626 // function, only the function-to-pointer conversion (4.3) is
7627 // applied. If the template-argument represents a set of
7628 // overloaded functions (or a pointer to such), the matching
7629 // function is selected from the set (13.4).
7630 (ParamType->isPointerType() &&
7631 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7632 // -- For a non-type template-parameter of type reference to
7633 // function, no conversions apply. If the template-argument
7634 // represents a set of overloaded functions, the matching
7635 // function is selected from the set (13.4).
7636 (ParamType->isReferenceType() &&
7637 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7638 // -- For a non-type template-parameter of type pointer to
7639 // member function, no conversions apply. If the
7640 // template-argument represents a set of overloaded member
7641 // functions, the matching member function is selected from
7642 // the set (13.4).
7643 (ParamType->isMemberPointerType() &&
7644 ParamType->castAs<MemberPointerType>()->getPointeeType()
7645 ->isFunctionType())) {
7646
7647 if (Arg->getType() == Context.OverloadTy) {
7648 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7649 true,
7650 FoundResult)) {
7651 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7652 return ExprError();
7653
7654 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7655 if (Res.isInvalid())
7656 return ExprError();
7657 Arg = Res.get();
7658 ArgType = Arg->getType();
7659 } else
7660 return ExprError();
7661 }
7662
7663 if (!ParamType->isMemberPointerType()) {
7665 *this, Param, ParamType, Arg, SugaredConverted,
7666 CanonicalConverted))
7667 return ExprError();
7668 return Arg;
7669 }
7670
7672 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7673 return ExprError();
7674 return Arg;
7675 }
7676
7677 if (ParamType->isPointerType()) {
7678 // -- for a non-type template-parameter of type pointer to
7679 // object, qualification conversions (4.4) and the
7680 // array-to-pointer conversion (4.2) are applied.
7681 // C++0x also allows a value of std::nullptr_t.
7682 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7683 "Only object pointers allowed here");
7684
7686 *this, Param, ParamType, Arg, SugaredConverted, 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, SugaredConverted, CanonicalConverted))
7719 return ExprError();
7720 return Arg;
7721 }
7722
7723 // Deal with parameters of type std::nullptr_t.
7724 if (ParamType->isNullPtrType()) {
7725 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7726 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7727 CanonicalConverted =
7728 Context.getCanonicalTemplateArgument(SugaredConverted);
7729 return Arg;
7730 }
7731
7732 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7733 case NPV_NotNullPointer:
7734 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7735 << Arg->getType() << ParamType;
7737 return ExprError();
7738
7739 case NPV_Error:
7740 return ExprError();
7741
7742 case NPV_NullPointer:
7743 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7744 SugaredConverted = TemplateArgument(ParamType,
7745 /*isNullPtr=*/true);
7746 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7747 /*isNullPtr=*/true);
7748 return Arg;
7749 }
7750 }
7751
7752 // -- For a non-type template-parameter of type pointer to data
7753 // member, qualification conversions (4.4) are applied.
7754 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7755
7757 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7758 return ExprError();
7759 return Arg;
7760}
7761
7765
7768 const TemplateArgumentLoc &Arg) {
7769 // C++0x [temp.arg.template]p1:
7770 // A template-argument for a template template-parameter shall be
7771 // the name of a class template or an alias template, expressed as an
7772 // id-expression. When the template-argument names a class template, only
7773 // primary class templates are considered when matching the
7774 // template template argument with the corresponding parameter;
7775 // partial specializations are not considered even if their
7776 // parameter lists match that of the template template parameter.
7777 //
7778
7780 unsigned DiagFoundKind = 0;
7781
7782 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7783 switch (TTP->templateParameterKind()) {
7785 DiagFoundKind = 3;
7786 break;
7788 DiagFoundKind = 2;
7789 break;
7790 default:
7791 DiagFoundKind = 1;
7792 break;
7793 }
7794 Kind = TTP->templateParameterKind();
7795 } else if (isa<ConceptDecl>(Template)) {
7797 DiagFoundKind = 3;
7798 } else if (isa<FunctionTemplateDecl>(Template)) {
7800 DiagFoundKind = 0;
7801 } else if (isa<VarTemplateDecl>(Template)) {
7803 DiagFoundKind = 2;
7804 } else if (isa<ClassTemplateDecl>(Template) ||
7808 DiagFoundKind = 1;
7809 } else {
7810 assert(false && "Unexpected Decl");
7811 }
7812
7813 if (Kind == Param->templateParameterKind()) {
7814 return true;
7815 }
7816
7817 unsigned DiagKind = 0;
7818 switch (Param->templateParameterKind()) {
7820 DiagKind = 2;
7821 break;
7823 DiagKind = 1;
7824 break;
7825 default:
7826 DiagKind = 0;
7827 break;
7828 }
7829 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7830 << DiagKind;
7831 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7832 << DiagFoundKind << Template;
7833 return false;
7834}
7835
7836/// Check a template argument against its corresponding
7837/// template template parameter.
7838///
7839/// This routine implements the semantics of C++ [temp.arg.template].
7840/// It returns true if an error occurred, and false otherwise.
7842 TemplateParameterList *Params,
7844 bool PartialOrdering,
7845 bool *StrictPackMatch) {
7847 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7848 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7849 if (!Template) {
7850 // FIXME: Handle AssumedTemplateNames
7851 // Any dependent template name is fine.
7852 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7853 return false;
7854 }
7855
7856 if (Template->isInvalidDecl())
7857 return true;
7858
7860 return true;
7861 }
7862
7863 // C++1z [temp.arg.template]p3: (DR 150)
7864 // A template-argument matches a template template-parameter P when P
7865 // is at least as specialized as the template-argument A.
7867 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7868 PartialOrdering, StrictPackMatch))
7869 return true;
7870 // P2113
7871 // C++20[temp.func.order]p2
7872 // [...] If both deductions succeed, the partial ordering selects the
7873 // more constrained template (if one exists) as determined below.
7874 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7875 Params->getAssociatedConstraints(ParamsAC);
7876 // C++20[temp.arg.template]p3
7877 // [...] In this comparison, if P is unconstrained, the constraints on A
7878 // are not considered.
7879 if (ParamsAC.empty())
7880 return false;
7881
7882 Template->getAssociatedConstraints(TemplateAC);
7883
7884 bool IsParamAtLeastAsConstrained;
7885 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7886 IsParamAtLeastAsConstrained))
7887 return true;
7888 if (!IsParamAtLeastAsConstrained) {
7889 Diag(Arg.getLocation(),
7890 diag::err_template_template_parameter_not_at_least_as_constrained)
7891 << Template << Param << Arg.getSourceRange();
7892 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7893 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7895 TemplateAC);
7896 return true;
7897 }
7898 return false;
7899}
7900
7902 unsigned HereDiagID,
7903 unsigned ExternalDiagID) {
7904 if (Decl.getLocation().isValid())
7905 return S.Diag(Decl.getLocation(), HereDiagID);
7906
7907 SmallString<128> Str;
7908 llvm::raw_svector_ostream Out(Str);
7910 PP.TerseOutput = 1;
7911 Decl.print(Out, PP);
7912 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7913}
7914
7916 std::optional<SourceRange> ParamRange) {
7918 noteLocation(*this, Decl, diag::note_template_decl_here,
7919 diag::note_template_decl_external);
7920 if (ParamRange && ParamRange->isValid()) {
7921 assert(Decl.getLocation().isValid() &&
7922 "Parameter range has location when Decl does not");
7923 DB << *ParamRange;
7924 }
7925}
7926
7928 noteLocation(*this, Decl, diag::note_template_param_here,
7929 diag::note_template_param_external);
7930}
7931
7932/// Given a non-type template argument that refers to a
7933/// declaration and the type of its corresponding non-type template
7934/// parameter, produce an expression that properly refers to that
7935/// declaration.
7937 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 (NonTypeTemplateParmDecl *NTTP =
8004 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
8005 QualType TemplateParamType = NTTP->getType();
8006 const AutoType *AT = TemplateParamType->getAs<AutoType>();
8007 if (AT && AT->isDecltypeAuto()) {
8009 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
8010 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
8011 /*PackIndex=*/std::nullopt,
8012 /*RefParam=*/true, /*Final=*/true);
8013 }
8014 }
8015 }
8016
8017 // At this point we should have the right value category.
8018 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8019 "value kind mismatch for non-type template argument");
8020
8021 // The type of the template parameter can differ from the type of the
8022 // argument in various ways; convert it now if necessary.
8023 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8024 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8025 CastKind CK;
8026 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8027 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8028 CK = CK_NoOp;
8029 } else if (ParamType->isVoidPointerType() &&
8030 RefExpr.get()->getType()->isPointerType()) {
8031 CK = CK_BitCast;
8032 } else {
8033 // FIXME: Pointers to members can need conversion derived-to-base or
8034 // base-to-derived conversions. We currently don't retain enough
8035 // information to convert properly (we need to track a cast path or
8036 // subobject number in the template argument).
8037 llvm_unreachable(
8038 "unexpected conversion required for non-type template argument");
8039 }
8040 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8041 RefExpr.get()->getValueKind());
8042 }
8043
8044 return RefExpr;
8045}
8046
8047/// Construct a new expression that refers to the given
8048/// integral template argument with the given source-location
8049/// information.
8050///
8051/// This routine takes care of the mapping from an integral template
8052/// argument (which may have any integral type) to the appropriate
8053/// literal value.
8055 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8056 assert(OrigT->isIntegralOrEnumerationType());
8057
8058 // If this is an enum type that we're instantiating, we need to use an integer
8059 // type the same size as the enumerator. We don't want to build an
8060 // IntegerLiteral with enum type. The integer type of an enum type can be of
8061 // any integral type with C++11 enum classes, make sure we create the right
8062 // type of literal for it.
8063 QualType T = OrigT;
8064 if (const auto *ED = OrigT->getAsEnumDecl())
8065 T = ED->getIntegerType();
8066
8067 Expr *E;
8068 if (T->isAnyCharacterType()) {
8070 if (T->isWideCharType())
8072 else if (T->isChar8Type() && S.getLangOpts().Char8)
8074 else if (T->isChar16Type())
8076 else if (T->isChar32Type())
8078 else
8080
8081 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8082 } else if (T->isBooleanType()) {
8083 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8084 } else {
8085 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8086 }
8087
8088 if (OrigT->isEnumeralType()) {
8089 // FIXME: This is a hack. We need a better way to handle substituted
8090 // non-type template parameters.
8091 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8092 nullptr, S.CurFPFeatureOverrides(),
8093 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8094 Loc, Loc);
8095 }
8096
8097 return E;
8098}
8099
8101 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8102 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8103 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8104 ILE->setType(T);
8105 return ILE;
8106 };
8107
8108 switch (Val.getKind()) {
8110 // This cannot occur in a template argument at all.
8111 case APValue::Array:
8112 case APValue::Struct:
8113 case APValue::Union:
8114 // These can only occur within a template parameter object, which is
8115 // represented as a TemplateArgument::Declaration.
8116 llvm_unreachable("unexpected template argument value");
8117
8118 case APValue::Int:
8120 Loc);
8121
8122 case APValue::Float:
8123 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8124 T, Loc);
8125
8128 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8129 Val.getFixedPoint().getScale());
8130
8131 case APValue::ComplexInt: {
8132 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8134 S, ElemT, Val.getComplexIntReal(), Loc),
8136 S, ElemT, Val.getComplexIntImag(), Loc)});
8137 }
8138
8139 case APValue::ComplexFloat: {
8140 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8141 return MakeInitList(
8143 ElemT, Loc),
8145 ElemT, Loc)});
8146 }
8147
8148 case APValue::Vector: {
8149 QualType ElemT = T->castAs<VectorType>()->getElementType();
8151 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8153 S, ElemT, Val.getVectorElt(I), Loc));
8154 return MakeInitList(Elts);
8155 }
8156
8157 case APValue::Matrix:
8158 llvm_unreachable("Matrix template argument expression not yet supported");
8159
8160 case APValue::None:
8162 llvm_unreachable("Unexpected APValue kind.");
8163 case APValue::LValue:
8165 // There isn't necessarily a valid equivalent source-level syntax for
8166 // these; in particular, a naive lowering might violate access control.
8167 // So for now we lower to a ConstantExpr holding the value, wrapped around
8168 // an OpaqueValueExpr.
8169 // FIXME: We should have a better representation for this.
8171 if (T->isReferenceType()) {
8172 T = T->getPointeeType();
8173 VK = VK_LValue;
8174 }
8175 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8176 return ConstantExpr::Create(S.Context, OVE, Val);
8177 }
8178 llvm_unreachable("Unhandled APValue::ValueKind enum");
8179}
8180
8183 SourceLocation Loc) {
8184 switch (Arg.getKind()) {
8190 llvm_unreachable("not a non-type template argument");
8191
8193 return Arg.getAsExpr();
8194
8198 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8199
8202 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8203
8206 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8207 }
8208 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8209}
8210
8211/// Match two template parameters within template parameter lists.
8213 Sema &S, NamedDecl *New,
8214 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8215 const NamedDecl *OldInstFrom, bool Complain,
8217 // Check the actual kind (type, non-type, template).
8218 if (Old->getKind() != New->getKind()) {
8219 if (Complain) {
8220 unsigned NextDiag = diag::err_template_param_different_kind;
8221 if (TemplateArgLoc.isValid()) {
8222 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8223 NextDiag = diag::note_template_param_different_kind;
8224 }
8225 S.Diag(New->getLocation(), NextDiag)
8226 << (Kind != Sema::TPL_TemplateMatch);
8227 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8228 << (Kind != Sema::TPL_TemplateMatch);
8229 }
8230
8231 return false;
8232 }
8233
8234 // Check that both are parameter packs or neither are parameter packs.
8235 // However, if we are matching a template template argument to a
8236 // template template parameter, the template template parameter can have
8237 // a parameter pack where the template template argument does not.
8238 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8239 if (Complain) {
8240 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8241 if (TemplateArgLoc.isValid()) {
8242 S.Diag(TemplateArgLoc,
8243 diag::err_template_arg_template_params_mismatch);
8244 NextDiag = diag::note_template_parameter_pack_non_pack;
8245 }
8246
8247 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8249 : 2;
8250 S.Diag(New->getLocation(), NextDiag)
8251 << ParamKind << New->isParameterPack();
8252 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8253 << ParamKind << Old->isParameterPack();
8254 }
8255
8256 return false;
8257 }
8258 // For non-type template parameters, check the type of the parameter.
8259 if (NonTypeTemplateParmDecl *OldNTTP =
8260 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8262
8263 // If we are matching a template template argument to a template
8264 // template parameter and one of the non-type template parameter types
8265 // is dependent, then we must wait until template instantiation time
8266 // to actually compare the arguments.
8268 (!OldNTTP->getType()->isDependentType() &&
8269 !NewNTTP->getType()->isDependentType())) {
8270 // C++20 [temp.over.link]p6:
8271 // Two [non-type] template-parameters are equivalent [if] they have
8272 // equivalent types ignoring the use of type-constraints for
8273 // placeholder types
8274 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8275 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8276 if (!S.Context.hasSameType(OldType, NewType)) {
8277 if (Complain) {
8278 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8279 if (TemplateArgLoc.isValid()) {
8280 S.Diag(TemplateArgLoc,
8281 diag::err_template_arg_template_params_mismatch);
8282 NextDiag = diag::note_template_nontype_parm_different_type;
8283 }
8284 S.Diag(NewNTTP->getLocation(), NextDiag)
8285 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8286 S.Diag(OldNTTP->getLocation(),
8287 diag::note_template_nontype_parm_prev_declaration)
8288 << OldNTTP->getType();
8289 }
8290 return false;
8291 }
8292 }
8293 }
8294 // For template template parameters, check the template parameter types.
8295 // The template parameter lists of template template
8296 // parameters must agree.
8297 else if (TemplateTemplateParmDecl *OldTTP =
8298 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8300 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8301 return false;
8303 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8304 OldTTP->getTemplateParameters(), Complain,
8307 : Kind),
8308 TemplateArgLoc))
8309 return false;
8310 }
8311
8315 const Expr *NewC = nullptr, *OldC = nullptr;
8316
8318 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8319 NewC = TC->getImmediatelyDeclaredConstraint();
8320 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8321 OldC = TC->getImmediatelyDeclaredConstraint();
8322 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8323 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8324 ->getPlaceholderTypeConstraint())
8325 NewC = E;
8326 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8327 ->getPlaceholderTypeConstraint())
8328 OldC = E;
8329 } else
8330 llvm_unreachable("unexpected template parameter type");
8331
8332 auto Diagnose = [&] {
8333 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8334 diag::err_template_different_type_constraint);
8335 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8336 diag::note_template_prev_declaration) << /*declaration*/0;
8337 };
8338
8339 if (!NewC != !OldC) {
8340 if (Complain)
8341 Diagnose();
8342 return false;
8343 }
8344
8345 if (NewC) {
8346 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8347 NewC)) {
8348 if (Complain)
8349 Diagnose();
8350 return false;
8351 }
8352 }
8353 }
8354
8355 return true;
8356}
8357
8358/// Diagnose a known arity mismatch when comparing template argument
8359/// lists.
8360static
8365 SourceLocation TemplateArgLoc) {
8366 unsigned NextDiag = diag::err_template_param_list_different_arity;
8367 if (TemplateArgLoc.isValid()) {
8368 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8369 NextDiag = diag::note_template_param_list_different_arity;
8370 }
8371 S.Diag(New->getTemplateLoc(), NextDiag)
8372 << (New->size() > Old->size())
8373 << (Kind != Sema::TPL_TemplateMatch)
8374 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8375 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8376 << (Kind != Sema::TPL_TemplateMatch)
8377 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8378}
8379
8382 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8383 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8384 if (Old->size() != New->size()) {
8385 if (Complain)
8387 TemplateArgLoc);
8388
8389 return false;
8390 }
8391
8392 // C++0x [temp.arg.template]p3:
8393 // A template-argument matches a template template-parameter (call it P)
8394 // when each of the template parameters in the template-parameter-list of
8395 // the template-argument's corresponding class template or alias template
8396 // (call it A) matches the corresponding template parameter in the
8397 // template-parameter-list of P. [...]
8398 TemplateParameterList::iterator NewParm = New->begin();
8399 TemplateParameterList::iterator NewParmEnd = New->end();
8400 for (TemplateParameterList::iterator OldParm = Old->begin(),
8401 OldParmEnd = Old->end();
8402 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8403 if (NewParm == NewParmEnd) {
8404 if (Complain)
8406 TemplateArgLoc);
8407 return false;
8408 }
8409 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8410 OldInstFrom, Complain, Kind,
8411 TemplateArgLoc))
8412 return false;
8413 }
8414
8415 // Make sure we exhausted all of the arguments.
8416 if (NewParm != NewParmEnd) {
8417 if (Complain)
8419 TemplateArgLoc);
8420
8421 return false;
8422 }
8423
8424 if (Kind != TPL_TemplateParamsEquivalent) {
8425 const Expr *NewRC = New->getRequiresClause();
8426 const Expr *OldRC = Old->getRequiresClause();
8427
8428 auto Diagnose = [&] {
8429 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8430 diag::err_template_different_requires_clause);
8431 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8432 diag::note_template_prev_declaration) << /*declaration*/0;
8433 };
8434
8435 if (!NewRC != !OldRC) {
8436 if (Complain)
8437 Diagnose();
8438 return false;
8439 }
8440
8441 if (NewRC) {
8442 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8443 NewRC)) {
8444 if (Complain)
8445 Diagnose();
8446 return false;
8447 }
8448 }
8449 }
8450
8451 return true;
8452}
8453
8454bool
8456 if (!S)
8457 return false;
8458
8459 // Find the nearest enclosing declaration scope.
8460 S = S->getDeclParent();
8461
8462 // C++ [temp.pre]p6: [P2096]
8463 // A template, explicit specialization, or partial specialization shall not
8464 // have C linkage.
8465 DeclContext *Ctx = S->getEntity();
8466 if (Ctx && Ctx->isExternCContext()) {
8467 SourceRange Range =
8468 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8469 ? TemplateParams->getParam(0)->getSourceRange()
8470 : TemplateParams->getSourceRange();
8471 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8472 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8473 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8474 return true;
8475 }
8476 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8477
8478 // C++ [temp]p2:
8479 // A template-declaration can appear only as a namespace scope or
8480 // class scope declaration.
8481 // C++ [temp.expl.spec]p3:
8482 // An explicit specialization may be declared in any scope in which the
8483 // corresponding primary template may be defined.
8484 // C++ [temp.class.spec]p6: [P2096]
8485 // A partial specialization may be declared in any scope in which the
8486 // corresponding primary template may be defined.
8487 if (Ctx) {
8488 if (Ctx->isFileContext())
8489 return false;
8490 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8491 // C++ [temp.mem]p2:
8492 // A local class shall not have member templates.
8493 if (RD->isLocalClass())
8494 return Diag(TemplateParams->getTemplateLoc(),
8495 diag::err_template_inside_local_class)
8496 << TemplateParams->getSourceRange();
8497 else
8498 return false;
8499 }
8500 }
8501
8502 return Diag(TemplateParams->getTemplateLoc(),
8503 diag::err_template_outside_namespace_or_class_scope)
8504 << TemplateParams->getSourceRange();
8505}
8506
8507/// Determine what kind of template specialization the given declaration
8508/// is.
8510 if (!D)
8511 return TSK_Undeclared;
8512
8513 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8514 return Record->getTemplateSpecializationKind();
8515 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8516 return Function->getTemplateSpecializationKind();
8517 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8518 return Var->getTemplateSpecializationKind();
8519
8520 return TSK_Undeclared;
8521}
8522
8523/// Check whether a specialization is well-formed in the current
8524/// context.
8525///
8526/// This routine determines whether a template specialization can be declared
8527/// in the current context (C++ [temp.expl.spec]p2).
8528///
8529/// \param S the semantic analysis object for which this check is being
8530/// performed.
8531///
8532/// \param Specialized the entity being specialized or instantiated, which
8533/// may be a kind of template (class template, function template, etc.) or
8534/// a member of a class template (member function, static data member,
8535/// member class).
8536///
8537/// \param PrevDecl the previous declaration of this entity, if any.
8538///
8539/// \param Loc the location of the explicit specialization or instantiation of
8540/// this entity.
8541///
8542/// \param IsPartialSpecialization whether this is a partial specialization of
8543/// a class template.
8544///
8545/// \returns true if there was an error that we cannot recover from, false
8546/// otherwise.
8548 NamedDecl *Specialized,
8549 NamedDecl *PrevDecl,
8550 SourceLocation Loc,
8552 // Keep these "kind" numbers in sync with the %select statements in the
8553 // various diagnostics emitted by this routine.
8554 int EntityKind = 0;
8555 if (isa<ClassTemplateDecl>(Specialized))
8556 EntityKind = IsPartialSpecialization? 1 : 0;
8557 else if (isa<VarTemplateDecl>(Specialized))
8558 EntityKind = IsPartialSpecialization ? 3 : 2;
8559 else if (isa<FunctionTemplateDecl>(Specialized))
8560 EntityKind = 4;
8561 else if (isa<CXXMethodDecl>(Specialized))
8562 EntityKind = 5;
8563 else if (isa<VarDecl>(Specialized))
8564 EntityKind = 6;
8565 else if (isa<RecordDecl>(Specialized))
8566 EntityKind = 7;
8567 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8568 EntityKind = 8;
8569 else {
8570 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8571 << S.getLangOpts().CPlusPlus11;
8572 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8573 return true;
8574 }
8575
8576 // C++ [temp.expl.spec]p2:
8577 // An explicit specialization may be declared in any scope in which
8578 // the corresponding primary template may be defined.
8580 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8581 << Specialized;
8582 return true;
8583 }
8584
8585 // C++ [temp.class.spec]p6:
8586 // A class template partial specialization may be declared in any
8587 // scope in which the primary template may be defined.
8588 DeclContext *SpecializedContext =
8589 Specialized->getDeclContext()->getRedeclContext();
8591
8592 // Make sure that this redeclaration (or definition) occurs in the same
8593 // scope or an enclosing namespace.
8594 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8595 : DC->Equals(SpecializedContext))) {
8596 if (isa<TranslationUnitDecl>(SpecializedContext))
8597 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8598 << EntityKind << Specialized;
8599 else {
8600 auto *ND = cast<NamedDecl>(SpecializedContext);
8601 int Diag = diag::err_template_spec_redecl_out_of_scope;
8602 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8603 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8604 S.Diag(Loc, Diag) << EntityKind << Specialized
8605 << ND << isa<CXXRecordDecl>(ND);
8606 }
8607
8608 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8609
8610 // Don't allow specializing in the wrong class during error recovery.
8611 // Otherwise, things can go horribly wrong.
8612 if (DC->isRecord())
8613 return true;
8614 }
8615
8616 return false;
8617}
8618
8620 if (!E->isTypeDependent())
8621 return SourceLocation();
8622 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8623 Checker.TraverseStmt(E);
8624 if (Checker.MatchLoc.isInvalid())
8625 return E->getSourceRange();
8626 return Checker.MatchLoc;
8627}
8628
8629static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8630 if (!TL.getType()->isDependentType())
8631 return SourceLocation();
8632 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8633 Checker.TraverseTypeLoc(TL);
8634 if (Checker.MatchLoc.isInvalid())
8635 return TL.getSourceRange();
8636 return Checker.MatchLoc;
8637}
8638
8639/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8640/// that checks non-type template partial specialization arguments.
8642 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8643 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8644 bool HasError = false;
8645 for (unsigned I = 0; I != NumArgs; ++I) {
8646 if (Args[I].getKind() == TemplateArgument::Pack) {
8648 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8649 Args[I].pack_size(), IsDefaultArgument))
8650 return true;
8651
8652 continue;
8653 }
8654
8655 if (Args[I].getKind() != TemplateArgument::Expression)
8656 continue;
8657
8658 Expr *ArgExpr = Args[I].getAsExpr();
8659 if (ArgExpr->containsErrors()) {
8660 HasError = true;
8661 continue;
8662 }
8663
8664 // We can have a pack expansion of any of the bullets below.
8665 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8666 ArgExpr = Expansion->getPattern();
8667
8668 // Strip off any implicit casts we added as part of type checking.
8669 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8670 ArgExpr = ICE->getSubExpr();
8671
8672 // C++ [temp.class.spec]p8:
8673 // A non-type argument is non-specialized if it is the name of a
8674 // non-type parameter. All other non-type arguments are
8675 // specialized.
8676 //
8677 // Below, we check the two conditions that only apply to
8678 // specialized non-type arguments, so skip any non-specialized
8679 // arguments.
8680 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8681 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8682 continue;
8683
8684 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8685 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8686 continue;
8687 }
8688
8689 // C++ [temp.class.spec]p9:
8690 // Within the argument list of a class template partial
8691 // specialization, the following restrictions apply:
8692 // -- A partially specialized non-type argument expression
8693 // shall not involve a template parameter of the partial
8694 // specialization except when the argument expression is a
8695 // simple identifier.
8696 // -- The type of a template parameter corresponding to a
8697 // specialized non-type argument shall not be dependent on a
8698 // parameter of the specialization.
8699 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8700 // We implement a compromise between the original rules and DR1315:
8701 // -- A specialized non-type template argument shall not be
8702 // type-dependent and the corresponding template parameter
8703 // shall have a non-dependent type.
8704 SourceRange ParamUseRange =
8705 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8706 if (ParamUseRange.isValid()) {
8707 if (IsDefaultArgument) {
8708 S.Diag(TemplateNameLoc,
8709 diag::err_dependent_non_type_arg_in_partial_spec);
8710 S.Diag(ParamUseRange.getBegin(),
8711 diag::note_dependent_non_type_default_arg_in_partial_spec)
8712 << ParamUseRange;
8713 } else {
8714 S.Diag(ParamUseRange.getBegin(),
8715 diag::err_dependent_non_type_arg_in_partial_spec)
8716 << ParamUseRange;
8717 }
8718 return true;
8719 }
8720
8721 ParamUseRange = findTemplateParameter(
8722 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8723 if (ParamUseRange.isValid()) {
8724 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8725 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8726 << Param->getType();
8728 return true;
8729 }
8730 }
8731
8732 return HasError;
8733}
8734
8736 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8737 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8738 // We have to be conservative when checking a template in a dependent
8739 // context.
8740 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8741 return false;
8742
8743 TemplateParameterList *TemplateParams =
8744 PrimaryTemplate->getTemplateParameters();
8745 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8747 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8748 if (!Param)
8749 continue;
8750
8751 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8752 Param, &TemplateArgs[I],
8753 1, I >= NumExplicit))
8754 return true;
8755 }
8756
8757 return false;
8758}
8759
8761 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8762 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8764 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8765 assert(TUK != TagUseKind::Reference && "References are not specializations");
8766
8767 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8768 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8769 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8770
8771 // Find the class template we're specializing
8772 TemplateName Name = TemplateId.Template.get();
8774 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8775
8776 if (!ClassTemplate) {
8777 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8778 << (Name.getAsTemplateDecl() &&
8780 return true;
8781 }
8782
8783 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8784 auto Message = DSA->getMessage();
8785 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8786 << ClassTemplate << !Message.empty() << Message;
8787 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8788 }
8789
8790 if (S->isTemplateParamScope())
8791 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8792
8793 DeclContext *DC = ClassTemplate->getDeclContext();
8794
8795 bool isMemberSpecialization = false;
8796 bool isPartialSpecialization = false;
8797
8798 if (SS.isSet()) {
8799 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8800 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8801 TemplateNameLoc, &TemplateId,
8802 /*IsMemberSpecialization=*/false))
8803 return true;
8804 }
8805
8806 // Check the validity of the template headers that introduce this
8807 // template.
8808 // FIXME: We probably shouldn't complain about these headers for
8809 // friend declarations.
8810 bool Invalid = false;
8811 TemplateParameterList *TemplateParams =
8813 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8814 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8815 if (Invalid)
8816 return true;
8817
8818 // Check that we can declare a template specialization here.
8819 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8820 return true;
8821
8822 if (TemplateParams && DC->isDependentContext()) {
8823 ContextRAII SavedContext(*this, DC);
8825 return true;
8826 }
8827
8828 if (TemplateParams && TemplateParams->size() > 0) {
8829 isPartialSpecialization = true;
8830
8831 if (TUK == TagUseKind::Friend) {
8832 Diag(KWLoc, diag::err_partial_specialization_friend)
8833 << SourceRange(LAngleLoc, RAngleLoc);
8834 return true;
8835 }
8836
8837 // C++ [temp.class.spec]p10:
8838 // The template parameter list of a specialization shall not
8839 // contain default template argument values.
8840 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8841 Decl *Param = TemplateParams->getParam(I);
8842 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8843 if (TTP->hasDefaultArgument()) {
8844 Diag(TTP->getDefaultArgumentLoc(),
8845 diag::err_default_arg_in_partial_spec);
8846 TTP->removeDefaultArgument();
8847 }
8848 } else if (NonTypeTemplateParmDecl *NTTP
8849 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8850 if (NTTP->hasDefaultArgument()) {
8851 Diag(NTTP->getDefaultArgumentLoc(),
8852 diag::err_default_arg_in_partial_spec)
8853 << NTTP->getDefaultArgument().getSourceRange();
8854 NTTP->removeDefaultArgument();
8855 }
8856 } else {
8858 if (TTP->hasDefaultArgument()) {
8860 diag::err_default_arg_in_partial_spec)
8862 TTP->removeDefaultArgument();
8863 }
8864 }
8865 }
8866 } else if (TemplateParams) {
8867 if (TUK == TagUseKind::Friend)
8868 Diag(KWLoc, diag::err_template_spec_friend)
8870 SourceRange(TemplateParams->getTemplateLoc(),
8871 TemplateParams->getRAngleLoc()))
8872 << SourceRange(LAngleLoc, RAngleLoc);
8873 } else {
8874 assert(TUK == TagUseKind::Friend &&
8875 "should have a 'template<>' for this decl");
8876 }
8877
8878 // Check that the specialization uses the same tag kind as the
8879 // original template.
8881 assert(Kind != TagTypeKind::Enum &&
8882 "Invalid enum tag in class template spec!");
8883 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8884 TUK == TagUseKind::Definition, KWLoc,
8885 ClassTemplate->getIdentifier())) {
8886 Diag(KWLoc, diag::err_use_with_wrong_tag)
8887 << ClassTemplate
8889 ClassTemplate->getTemplatedDecl()->getKindName());
8890 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8891 diag::note_previous_use);
8892 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8893 }
8894
8895 // Translate the parser's template argument list in our AST format.
8896 TemplateArgumentListInfo TemplateArgs =
8897 makeTemplateArgumentListInfo(*this, TemplateId);
8898
8899 // Check for unexpanded parameter packs in any of the template arguments.
8900 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8901 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8902 isPartialSpecialization
8905 return true;
8906
8907 // Check that the template argument list is well-formed for this
8908 // template.
8910 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8911 /*DefaultArgs=*/{},
8912 /*PartialTemplateArgs=*/false, CTAI,
8913 /*UpdateArgsWithConversions=*/true))
8914 return true;
8915
8916 // Find the class template (partial) specialization declaration that
8917 // corresponds to these arguments.
8918 if (isPartialSpecialization) {
8920 TemplateArgs.size(),
8921 CTAI.CanonicalConverted))
8922 return true;
8923
8924 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8925 // also do it during instantiation.
8926 if (!Name.isDependent() &&
8927 !TemplateSpecializationType::anyDependentTemplateArguments(
8928 TemplateArgs, CTAI.CanonicalConverted)) {
8929 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8930 << ClassTemplate->getDeclName();
8931 isPartialSpecialization = false;
8932 Invalid = true;
8933 }
8934 }
8935
8936 void *InsertPos = nullptr;
8937 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8938
8939 if (isPartialSpecialization)
8940 PrevDecl = ClassTemplate->findPartialSpecialization(
8941 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8942 else
8943 PrevDecl =
8944 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8945
8947
8948 // Check whether we can declare a class template specialization in
8949 // the current scope.
8950 if (TUK != TagUseKind::Friend &&
8952 TemplateNameLoc,
8953 isPartialSpecialization))
8954 return true;
8955
8956 if (!isPartialSpecialization) {
8957 // Create a new class template specialization declaration node for
8958 // this explicit specialization or friend declaration.
8960 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8961 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8962 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8964 if (TemplateParameterLists.size() > 0) {
8965 Specialization->setTemplateParameterListsInfo(Context,
8966 TemplateParameterLists);
8967 }
8968
8969 if (!PrevDecl)
8970 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8971 } else {
8973 Context.getCanonicalTemplateSpecializationType(
8975 TemplateName(ClassTemplate->getCanonicalDecl()),
8976 CTAI.CanonicalConverted));
8977 if (Context.hasSameType(
8978 CanonType,
8979 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8980 (!Context.getLangOpts().CPlusPlus20 ||
8981 !TemplateParams->hasAssociatedConstraints())) {
8982 // C++ [temp.class.spec]p9b3:
8983 //
8984 // -- The argument list of the specialization shall not be identical
8985 // to the implicit argument list of the primary template.
8986 //
8987 // This rule has since been removed, because it's redundant given DR1495,
8988 // but we keep it because it produces better diagnostics and recovery.
8989 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8990 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8991 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8992 return CheckClassTemplate(
8993 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8994 TemplateNameLoc, Attr, TemplateParams, AS_none,
8995 /*ModulePrivateLoc=*/SourceLocation(),
8996 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8997 TemplateParameterLists.data());
8998 }
8999
9000 // Create a new class template partial specialization declaration node.
9002 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9005 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9006 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9007 Partial->setTemplateArgsAsWritten(TemplateArgs);
9008 SetNestedNameSpecifier(*this, Partial, SS);
9009 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9011 Context, TemplateParameterLists.drop_back(1));
9012 }
9013
9014 if (!PrevPartial)
9015 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9016 Specialization = Partial;
9017
9018 // If we are providing an explicit specialization of a member class
9019 // template specialization, make a note of that.
9020 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9021 PrevPartial->setMemberSpecialization();
9022
9024 }
9025
9026 // C++ [temp.expl.spec]p6:
9027 // If a template, a member template or the member of a class template is
9028 // explicitly specialized then that specialization shall be declared
9029 // before the first use of that specialization that would cause an implicit
9030 // instantiation to take place, in every translation unit in which such a
9031 // use occurs; no diagnostic is required.
9032 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9033 bool Okay = false;
9034 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9035 // Is there any previous explicit specialization declaration?
9037 Okay = true;
9038 break;
9039 }
9040 }
9041
9042 if (!Okay) {
9043 SourceRange Range(TemplateNameLoc, RAngleLoc);
9044 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9045 << Context.getCanonicalTagType(Specialization) << Range;
9046
9047 Diag(PrevDecl->getPointOfInstantiation(),
9048 diag::note_instantiation_required_here)
9049 << (PrevDecl->getTemplateSpecializationKind()
9051 return true;
9052 }
9053 }
9054
9055 // If this is not a friend, note that this is an explicit specialization.
9056 if (TUK != TagUseKind::Friend)
9057 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9058
9059 // Check that this isn't a redefinition of this specialization.
9060 if (TUK == TagUseKind::Definition) {
9061 RecordDecl *Def = Specialization->getDefinition();
9062 NamedDecl *Hidden = nullptr;
9063 bool HiddenDefVisible = false;
9064 if (Def && SkipBody &&
9065 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9066 SkipBody->ShouldSkip = true;
9067 SkipBody->Previous = Def;
9068 if (!HiddenDefVisible && Hidden)
9070 } else if (Def) {
9071 SourceRange Range(TemplateNameLoc, RAngleLoc);
9072 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9073 Diag(Def->getLocation(), diag::note_previous_definition);
9074 Specialization->setInvalidDecl();
9075 return true;
9076 }
9077 }
9078
9081
9082 // Add alignment attributes if necessary; these attributes are checked when
9083 // the ASTContext lays out the structure.
9084 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9085 if (LangOpts.HLSL)
9086 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9089 }
9090
9091 if (ModulePrivateLoc.isValid())
9092 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9093 << (isPartialSpecialization? 1 : 0)
9094 << FixItHint::CreateRemoval(ModulePrivateLoc);
9095
9096 // C++ [temp.expl.spec]p9:
9097 // A template explicit specialization is in the scope of the
9098 // namespace in which the template was defined.
9099 //
9100 // We actually implement this paragraph where we set the semantic
9101 // context (in the creation of the ClassTemplateSpecializationDecl),
9102 // but we also maintain the lexical context where the actual
9103 // definition occurs.
9104 Specialization->setLexicalDeclContext(CurContext);
9105
9106 // We may be starting the definition of this specialization.
9107 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9108 Specialization->startDefinition();
9109
9110 if (TUK == TagUseKind::Friend) {
9111 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9112 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9113 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9115 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9116 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9117
9118 // Build the fully-sugared type for this class template
9119 // specialization as the user wrote in the specialization
9120 // itself. This means that we'll pretty-print the type retrieved
9121 // from the specialization's declaration the way that the user
9122 // actually wrote the specialization, rather than formatting the
9123 // name based on the "canonical" representation used to store the
9124 // template arguments in the specialization.
9126 TemplateNameLoc,
9127 WrittenTy,
9128 /*FIXME:*/KWLoc);
9129 Friend->setAccess(AS_public);
9130 CurContext->addDecl(Friend);
9131 } else {
9132 // Add the specialization into its lexical context, so that it can
9133 // be seen when iterating through the list of declarations in that
9134 // context. However, specializations are not found by name lookup.
9135 CurContext->addDecl(Specialization);
9136 }
9137
9138 if (SkipBody && SkipBody->ShouldSkip)
9139 return SkipBody->Previous;
9140
9141 Specialization->setInvalidDecl(Invalid);
9143 return Specialization;
9144}
9145
9147 MultiTemplateParamsArg TemplateParameterLists,
9148 Declarator &D) {
9149 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9150 ActOnDocumentableDecl(NewDecl);
9151 return NewDecl;
9152}
9153
9155 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9156 const IdentifierInfo *Name, SourceLocation NameLoc) {
9157 DeclContext *DC = CurContext;
9158
9159 if (!DC->getRedeclContext()->isFileContext()) {
9160 Diag(NameLoc,
9161 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9162 return nullptr;
9163 }
9164
9165 if (TemplateParameterLists.size() > 1) {
9166 Diag(NameLoc, diag::err_concept_extra_headers);
9167 return nullptr;
9168 }
9169
9170 TemplateParameterList *Params = TemplateParameterLists.front();
9171
9172 if (Params->size() == 0) {
9173 Diag(NameLoc, diag::err_concept_no_parameters);
9174 return nullptr;
9175 }
9176
9177 // Ensure that the parameter pack, if present, is the last parameter in the
9178 // template.
9179 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9180 ParamEnd = Params->end();
9181 ParamIt != ParamEnd; ++ParamIt) {
9182 Decl const *Param = *ParamIt;
9183 if (Param->isParameterPack()) {
9184 if (++ParamIt == ParamEnd)
9185 break;
9186 Diag(Param->getLocation(),
9187 diag::err_template_param_pack_must_be_last_template_parameter);
9188 return nullptr;
9189 }
9190 }
9191
9192 ConceptDecl *NewDecl =
9193 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9194
9195 if (NewDecl->hasAssociatedConstraints()) {
9196 // C++2a [temp.concept]p4:
9197 // A concept shall not have associated constraints.
9198 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9199 NewDecl->setInvalidDecl();
9200 }
9201
9202 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9203 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9205 LookupName(Previous, S);
9206 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9207 /*AllowInlineNamespace*/ false);
9208
9209 // We cannot properly handle redeclarations until we parse the constraint
9210 // expression, so only inject the name if we are sure we are not redeclaring a
9211 // symbol
9212 if (Previous.empty())
9213 PushOnScopeChains(NewDecl, S, true);
9214
9215 return NewDecl;
9216}
9217
9219 bool Found = false;
9220 LookupResult::Filter F = R.makeFilter();
9221 while (F.hasNext()) {
9222 NamedDecl *D = F.next();
9223 if (D == C) {
9224 F.erase();
9225 Found = true;
9226 break;
9227 }
9228 }
9229 F.done();
9230 return Found;
9231}
9232
9235 Expr *ConstraintExpr,
9236 const ParsedAttributesView &Attrs) {
9237 assert(!C->hasDefinition() && "Concept already defined");
9238 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9239 C->setInvalidDecl();
9240 return nullptr;
9241 }
9242 C->setDefinition(ConstraintExpr);
9243 ProcessDeclAttributeList(S, C, Attrs);
9244
9245 // Check for conflicting previous declaration.
9246 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9247 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9249 LookupName(Previous, S);
9250 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9251 /*AllowInlineNamespace*/ false);
9252 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9253 bool AddToScope = true;
9254 CheckConceptRedefinition(C, Previous, AddToScope);
9255
9257 if (!WasAlreadyAdded && AddToScope)
9258 PushOnScopeChains(C, S);
9259
9260 return C;
9261}
9262
9264 LookupResult &Previous, bool &AddToScope) {
9265 AddToScope = true;
9266
9267 if (Previous.empty())
9268 return;
9269
9270 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9271 if (!OldConcept) {
9272 auto *Old = Previous.getRepresentativeDecl();
9273 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9274 << NewDecl->getDeclName();
9275 notePreviousDefinition(Old, NewDecl->getLocation());
9276 AddToScope = false;
9277 return;
9278 }
9279 // Check if we can merge with a concept declaration.
9280 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9281 if (!IsSame) {
9282 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9283 << NewDecl->getDeclName();
9284 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9285 AddToScope = false;
9286 return;
9287 }
9288 if (hasReachableDefinition(OldConcept) &&
9289 IsRedefinitionInModule(NewDecl, OldConcept)) {
9290 Diag(NewDecl->getLocation(), diag::err_redefinition)
9291 << NewDecl->getDeclName();
9292 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9293 AddToScope = false;
9294 return;
9295 }
9296 if (!Previous.isSingleResult()) {
9297 // FIXME: we should produce an error in case of ambig and failed lookups.
9298 // Other decls (e.g. namespaces) also have this shortcoming.
9299 return;
9300 }
9301 // We unwrap canonical decl late to check for module visibility.
9302 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9303}
9304
9306 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9307 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9308 Diag(Loc, diag::err_recursive_concept) << CE;
9309 Diag(CE->getLocation(), diag::note_declared_at);
9310 return true;
9311 }
9312 // Concept template parameters don't have a definition and can't
9313 // be defined recursively.
9314 return false;
9315}
9316
9317/// \brief Strips various properties off an implicit instantiation
9318/// that has just been explicitly specialized.
9319static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9320 if (MinGW || (isa<FunctionDecl>(D) &&
9321 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9322 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9323
9324 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9325 FD->setInlineSpecified(false);
9326}
9327
9328/// Compute the diagnostic location for an explicit instantiation
9329// declaration or definition.
9331 NamedDecl* D, SourceLocation PointOfInstantiation) {
9332 // Explicit instantiations following a specialization have no effect and
9333 // hence no PointOfInstantiation. In that case, walk decl backwards
9334 // until a valid name loc is found.
9335 SourceLocation PrevDiagLoc = PointOfInstantiation;
9336 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9337 Prev = Prev->getPreviousDecl()) {
9338 PrevDiagLoc = Prev->getLocation();
9339 }
9340 assert(PrevDiagLoc.isValid() &&
9341 "Explicit instantiation without point of instantiation?");
9342 return PrevDiagLoc;
9343}
9344
9345bool
9348 NamedDecl *PrevDecl,
9350 SourceLocation PrevPointOfInstantiation,
9351 bool &HasNoEffect) {
9352 HasNoEffect = false;
9353
9354 switch (NewTSK) {
9355 case TSK_Undeclared:
9357 assert(
9358 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9359 "previous declaration must be implicit!");
9360 return false;
9361
9363 switch (PrevTSK) {
9364 case TSK_Undeclared:
9366 // Okay, we're just specializing something that is either already
9367 // explicitly specialized or has merely been mentioned without any
9368 // instantiation.
9369 return false;
9370
9372 if (PrevPointOfInstantiation.isInvalid()) {
9373 // The declaration itself has not actually been instantiated, so it is
9374 // still okay to specialize it.
9376 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9377 return false;
9378 }
9379 // Fall through
9380 [[fallthrough]];
9381
9384 assert((PrevTSK == TSK_ImplicitInstantiation ||
9385 PrevPointOfInstantiation.isValid()) &&
9386 "Explicit instantiation without point of instantiation?");
9387
9388 // C++ [temp.expl.spec]p6:
9389 // If a template, a member template or the member of a class template
9390 // is explicitly specialized then that specialization shall be declared
9391 // before the first use of that specialization that would cause an
9392 // implicit instantiation to take place, in every translation unit in
9393 // which such a use occurs; no diagnostic is required.
9394 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9395 // Is there any previous explicit specialization declaration?
9397 return false;
9398 }
9399
9400 Diag(NewLoc, diag::err_specialization_after_instantiation)
9401 << PrevDecl;
9402 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9403 << (PrevTSK != TSK_ImplicitInstantiation);
9404
9405 return true;
9406 }
9407 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9408
9410 switch (PrevTSK) {
9412 // This explicit instantiation declaration is redundant (that's okay).
9413 HasNoEffect = true;
9414 return false;
9415
9416 case TSK_Undeclared:
9418 // We're explicitly instantiating something that may have already been
9419 // implicitly instantiated; that's fine.
9420 return false;
9421
9423 // C++0x [temp.explicit]p4:
9424 // For a given set of template parameters, if an explicit instantiation
9425 // of a template appears after a declaration of an explicit
9426 // specialization for that template, the explicit instantiation has no
9427 // effect.
9428 HasNoEffect = true;
9429 return false;
9430
9432 // C++0x [temp.explicit]p10:
9433 // If an entity is the subject of both an explicit instantiation
9434 // declaration and an explicit instantiation definition in the same
9435 // translation unit, the definition shall follow the declaration.
9436 Diag(NewLoc,
9437 diag::err_explicit_instantiation_declaration_after_definition);
9438
9439 // Explicit instantiations following a specialization have no effect and
9440 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9441 // until a valid name loc is found.
9442 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9443 diag::note_explicit_instantiation_definition_here);
9444 HasNoEffect = true;
9445 return false;
9446 }
9447 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9448
9450 switch (PrevTSK) {
9451 case TSK_Undeclared:
9453 // We're explicitly instantiating something that may have already been
9454 // implicitly instantiated; that's fine.
9455 return false;
9456
9458 // C++ DR 259, C++0x [temp.explicit]p4:
9459 // For a given set of template parameters, if an explicit
9460 // instantiation of a template appears after a declaration of
9461 // an explicit specialization for that template, the explicit
9462 // instantiation has no effect.
9463 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9464 << PrevDecl;
9465 Diag(PrevDecl->getLocation(),
9466 diag::note_previous_template_specialization);
9467 HasNoEffect = true;
9468 return false;
9469
9471 // We're explicitly instantiating a definition for something for which we
9472 // were previously asked to suppress instantiations. That's fine.
9473
9474 // C++0x [temp.explicit]p4:
9475 // For a given set of template parameters, if an explicit instantiation
9476 // of a template appears after a declaration of an explicit
9477 // specialization for that template, the explicit instantiation has no
9478 // effect.
9479 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9480 // Is there any previous explicit specialization declaration?
9482 HasNoEffect = true;
9483 break;
9484 }
9485 }
9486
9487 return false;
9488
9490 // C++0x [temp.spec]p5:
9491 // For a given template and a given set of template-arguments,
9492 // - an explicit instantiation definition shall appear at most once
9493 // in a program,
9494
9495 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9496 Diag(NewLoc, (getLangOpts().MSVCCompat)
9497 ? diag::ext_explicit_instantiation_duplicate
9498 : diag::err_explicit_instantiation_duplicate)
9499 << PrevDecl;
9500 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9501 diag::note_previous_explicit_instantiation);
9502 HasNoEffect = true;
9503 return false;
9504 }
9505 }
9506
9507 llvm_unreachable("Missing specialization/instantiation case?");
9508}
9509
9511 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9513 // Remove anything from Previous that isn't a function template in
9514 // the correct context.
9515 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9516 LookupResult::Filter F = Previous.makeFilter();
9517 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9518 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9519 while (F.hasNext()) {
9520 NamedDecl *D = F.next()->getUnderlyingDecl();
9521 if (!isa<FunctionTemplateDecl>(D)) {
9522 F.erase();
9523 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9524 continue;
9525 }
9526
9527 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9529 F.erase();
9530 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9531 continue;
9532 }
9533 }
9534 F.done();
9535
9536 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9537 if (Previous.empty()) {
9538 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9539 << IsFriend;
9540 for (auto &P : DiscardedCandidates)
9541 Diag(P.second->getLocation(),
9542 diag::note_dependent_function_template_spec_discard_reason)
9543 << P.first << IsFriend;
9544 return true;
9545 }
9546
9548 ExplicitTemplateArgs);
9549 return false;
9550}
9551
9553 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9554 LookupResult &Previous, bool QualifiedFriend) {
9555 // The set of function template specializations that could match this
9556 // explicit function template specialization.
9557 UnresolvedSet<8> Candidates;
9558 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9559 /*ForTakingAddress=*/false);
9560
9561 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9562 ConvertedTemplateArgs;
9563
9564 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9565 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9566 I != E; ++I) {
9567 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9568 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9569 // Only consider templates found within the same semantic lookup scope as
9570 // FD.
9571 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9573 continue;
9574
9575 QualType FT = FD->getType();
9576 // C++11 [dcl.constexpr]p8:
9577 // A constexpr specifier for a non-static member function that is not
9578 // a constructor declares that member function to be const.
9579 //
9580 // When matching a constexpr member function template specialization
9581 // against the primary template, we don't yet know whether the
9582 // specialization has an implicit 'const' (because we don't know whether
9583 // it will be a static member function until we know which template it
9584 // specializes). This rule was removed in C++14.
9585 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9586 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9588 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9589 if (OldMD && OldMD->isConst()) {
9590 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9592 EPI.TypeQuals.addConst();
9593 FT = Context.getFunctionType(FPT->getReturnType(),
9594 FPT->getParamTypes(), EPI);
9595 }
9596 }
9597
9599 if (ExplicitTemplateArgs)
9600 Args = *ExplicitTemplateArgs;
9601
9602 // C++ [temp.expl.spec]p11:
9603 // A trailing template-argument can be left unspecified in the
9604 // template-id naming an explicit function template specialization
9605 // provided it can be deduced from the function argument type.
9606 // Perform template argument deduction to determine whether we may be
9607 // specializing this template.
9608 // FIXME: It is somewhat wasteful to build
9609 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9610 FunctionDecl *Specialization = nullptr;
9612 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9613 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9615 // Template argument deduction failed; record why it failed, so
9616 // that we can provide nifty diagnostics.
9617 FailedCandidates.addCandidate().set(
9618 I.getPair(), FunTmpl->getTemplatedDecl(),
9619 MakeDeductionFailureInfo(Context, TDK, Info));
9620 (void)TDK;
9621 continue;
9622 }
9623
9624 // Target attributes are part of the cuda function signature, so
9625 // the deduced template's cuda target must match that of the
9626 // specialization. Given that C++ template deduction does not
9627 // take target attributes into account, we reject candidates
9628 // here that have a different target.
9629 if (LangOpts.CUDA &&
9630 CUDA().IdentifyTarget(Specialization,
9631 /* IgnoreImplicitHDAttr = */ true) !=
9632 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9633 FailedCandidates.addCandidate().set(
9634 I.getPair(), FunTmpl->getTemplatedDecl(),
9637 continue;
9638 }
9639
9640 // Record this candidate.
9641 if (ExplicitTemplateArgs)
9642 ConvertedTemplateArgs[Specialization] = std::move(Args);
9643 Candidates.addDecl(Specialization, I.getAccess());
9644 }
9645 }
9646
9647 // For a qualified friend declaration (with no explicit marker to indicate
9648 // that a template specialization was intended), note all (template and
9649 // non-template) candidates.
9650 if (QualifiedFriend && Candidates.empty()) {
9651 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9652 << FD->getDeclName() << FDLookupContext;
9653 // FIXME: We should form a single candidate list and diagnose all
9654 // candidates at once, to get proper sorting and limiting.
9655 for (auto *OldND : Previous) {
9656 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9657 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9658 }
9659 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9660 return true;
9661 }
9662
9663 // Find the most specialized function template.
9665 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9666 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9667 PDiag(diag::err_function_template_spec_ambiguous)
9668 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9669 PDiag(diag::note_function_template_spec_matched));
9670
9671 if (Result == Candidates.end())
9672 return true;
9673
9674 // Ignore access information; it doesn't figure into redeclaration checking.
9676
9677 if (const auto *PT = Specialization->getPrimaryTemplate();
9678 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9679 auto Message = DSA->getMessage();
9680 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9681 << PT << !Message.empty() << Message;
9682 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9683 }
9684
9685 // C++23 [except.spec]p13:
9686 // An exception specification is considered to be needed when:
9687 // - [...]
9688 // - the exception specification is compared to that of another declaration
9689 // (e.g., an explicit specialization or an overriding virtual function);
9690 // - [...]
9691 //
9692 // The exception specification of a defaulted function is evaluated as
9693 // described above only when needed; similarly, the noexcept-specifier of a
9694 // specialization of a function template or member function of a class
9695 // template is instantiated only when needed.
9696 //
9697 // The standard doesn't specify what the "comparison with another declaration"
9698 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9699 // not state which properties of an explicit specialization must match the
9700 // primary template.
9701 //
9702 // We assume that an explicit specialization must correspond with (per
9703 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9704 // the declaration produced by substitution into the function template.
9705 //
9706 // Since the determination whether two function declarations correspond does
9707 // not consider exception specification, we only need to instantiate it once
9708 // we determine the primary template when comparing types per
9709 // [basic.link]p11.1.
9710 auto *SpecializationFPT =
9711 Specialization->getType()->castAs<FunctionProtoType>();
9712 // If the function has a dependent exception specification, resolve it after
9713 // we have selected the primary template so we can check whether it matches.
9714 if (getLangOpts().CPlusPlus17 &&
9715 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9716 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9717 return true;
9718
9720 = Specialization->getTemplateSpecializationInfo();
9721 assert(SpecInfo && "Function template specialization info missing?");
9722
9723 // Note: do not overwrite location info if previous template
9724 // specialization kind was explicit.
9726 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9727 Specialization->setLocation(FD->getLocation());
9728 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9729 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9730 // function can differ from the template declaration with respect to
9731 // the constexpr specifier.
9732 // FIXME: We need an update record for this AST mutation.
9733 // FIXME: What if there are multiple such prior declarations (for instance,
9734 // from different modules)?
9735 Specialization->setConstexprKind(FD->getConstexprKind());
9736 }
9737
9738 // FIXME: Check if the prior specialization has a point of instantiation.
9739 // If so, we have run afoul of .
9740
9741 // If this is a friend declaration, then we're not really declaring
9742 // an explicit specialization.
9743 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9744
9745 // Check the scope of this explicit specialization.
9746 if (!isFriend &&
9748 Specialization->getPrimaryTemplate(),
9750 false))
9751 return true;
9752
9753 // C++ [temp.expl.spec]p6:
9754 // If a template, a member template or the member of a class template is
9755 // explicitly specialized then that specialization shall be declared
9756 // before the first use of that specialization that would cause an implicit
9757 // instantiation to take place, in every translation unit in which such a
9758 // use occurs; no diagnostic is required.
9759 bool HasNoEffect = false;
9760 if (!isFriend &&
9765 SpecInfo->getPointOfInstantiation(),
9766 HasNoEffect))
9767 return true;
9768
9769 // Mark the prior declaration as an explicit specialization, so that later
9770 // clients know that this is an explicit specialization.
9771 // A dependent friend specialization which has a definition should be treated
9772 // as explicit specialization, despite being invalid.
9773 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9774 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9775 // Since explicit specializations do not inherit '=delete' from their
9776 // primary function template - check if the 'specialization' that was
9777 // implicitly generated (during template argument deduction for partial
9778 // ordering) from the most specialized of all the function templates that
9779 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9780 // first check that it was implicitly generated during template argument
9781 // deduction by making sure it wasn't referenced, and then reset the deleted
9782 // flag to not-deleted, so that we can inherit that information from 'FD'.
9783 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9784 !Specialization->getCanonicalDecl()->isReferenced()) {
9785 // FIXME: This assert will not hold in the presence of modules.
9786 assert(
9787 Specialization->getCanonicalDecl() == Specialization &&
9788 "This must be the only existing declaration of this specialization");
9789 // FIXME: We need an update record for this AST mutation.
9790 Specialization->setDeletedAsWritten(false);
9791 }
9792 // FIXME: We need an update record for this AST mutation.
9795 }
9796
9797 // Turn the given function declaration into a function template
9798 // specialization, with the template arguments from the previous
9799 // specialization.
9800 // Take copies of (semantic and syntactic) template argument lists.
9802 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9803 FD->setFunctionTemplateSpecialization(
9804 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9806 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9807
9808 // A function template specialization inherits the target attributes
9809 // of its template. (We require the attributes explicitly in the
9810 // code to match, but a template may have implicit attributes by
9811 // virtue e.g. of being constexpr, and it passes these implicit
9812 // attributes on to its specializations.)
9813 if (LangOpts.CUDA)
9814 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9815
9816 // The "previous declaration" for this function template specialization is
9817 // the prior function template specialization.
9818 Previous.clear();
9819 Previous.addDecl(Specialization);
9820 return false;
9821}
9822
9823bool
9825 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9826 "Only for non-template members");
9827
9828 // Try to find the member we are instantiating.
9829 NamedDecl *FoundInstantiation = nullptr;
9830 NamedDecl *Instantiation = nullptr;
9831 NamedDecl *InstantiatedFrom = nullptr;
9832 MemberSpecializationInfo *MSInfo = nullptr;
9833
9834 if (Previous.empty()) {
9835 // Nowhere to look anyway.
9836 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9837 UnresolvedSet<8> Candidates;
9838 for (NamedDecl *Candidate : Previous) {
9839 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9840 // Ignore any candidates that aren't member functions.
9841 if (!Method)
9842 continue;
9843
9844 QualType Adjusted = Function->getType();
9845 if (!hasExplicitCallingConv(Adjusted))
9846 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9847 // Ignore any candidates with the wrong type.
9848 // This doesn't handle deduced return types, but both function
9849 // declarations should be undeduced at this point.
9850 // FIXME: The exception specification should probably be ignored when
9851 // comparing the types.
9852 if (!Context.hasSameType(Adjusted, Method->getType()))
9853 continue;
9854
9855 // Ignore any candidates with unsatisfied constraints.
9856 if (ConstraintSatisfaction Satisfaction;
9857 Method->getTrailingRequiresClause() &&
9858 (CheckFunctionConstraints(Method, Satisfaction,
9859 /*UsageLoc=*/Member->getLocation(),
9860 /*ForOverloadResolution=*/true) ||
9861 !Satisfaction.IsSatisfied))
9862 continue;
9863
9864 Candidates.addDecl(Candidate);
9865 }
9866
9867 // If we have no viable candidates left after filtering, we are done.
9868 if (Candidates.empty())
9869 return false;
9870
9871 // Find the function that is more constrained than every other function it
9872 // has been compared to.
9873 UnresolvedSetIterator Best = Candidates.begin();
9874 CXXMethodDecl *BestMethod = nullptr;
9875 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9876 I != E; ++I) {
9877 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9878 if (I == Best ||
9879 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9880 Best = I;
9881 BestMethod = Method;
9882 }
9883 }
9884
9885 FoundInstantiation = *Best;
9886 Instantiation = BestMethod;
9887 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9888 MSInfo = BestMethod->getMemberSpecializationInfo();
9889
9890 // Make sure the best candidate is more constrained than all of the others.
9891 bool Ambiguous = false;
9892 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9893 I != E; ++I) {
9894 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9895 if (I != Best &&
9896 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9897 Ambiguous = true;
9898 break;
9899 }
9900 }
9901
9902 if (Ambiguous) {
9903 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9904 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9905 for (NamedDecl *Candidate : Candidates) {
9906 Candidate = Candidate->getUnderlyingDecl();
9907 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9908 << Candidate;
9909 }
9910 return true;
9911 }
9912 } else if (isa<VarDecl>(Member)) {
9913 VarDecl *PrevVar;
9914 if (Previous.isSingleResult() &&
9915 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9916 if (PrevVar->isStaticDataMember()) {
9917 FoundInstantiation = Previous.getRepresentativeDecl();
9918 Instantiation = PrevVar;
9919 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9920 MSInfo = PrevVar->getMemberSpecializationInfo();
9921 }
9922 } else if (isa<RecordDecl>(Member)) {
9923 CXXRecordDecl *PrevRecord;
9924 if (Previous.isSingleResult() &&
9925 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9926 FoundInstantiation = Previous.getRepresentativeDecl();
9927 Instantiation = PrevRecord;
9928 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9929 MSInfo = PrevRecord->getMemberSpecializationInfo();
9930 }
9931 } else if (isa<EnumDecl>(Member)) {
9932 EnumDecl *PrevEnum;
9933 if (Previous.isSingleResult() &&
9934 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9935 FoundInstantiation = Previous.getRepresentativeDecl();
9936 Instantiation = PrevEnum;
9937 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9938 MSInfo = PrevEnum->getMemberSpecializationInfo();
9939 }
9940 }
9941
9942 if (!Instantiation) {
9943 // There is no previous declaration that matches. Since member
9944 // specializations are always out-of-line, the caller will complain about
9945 // this mismatch later.
9946 return false;
9947 }
9948
9949 // A member specialization in a friend declaration isn't really declaring
9950 // an explicit specialization, just identifying a specific (possibly implicit)
9951 // specialization. Don't change the template specialization kind.
9952 //
9953 // FIXME: Is this really valid? Other compilers reject.
9954 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9955 // Preserve instantiation information.
9956 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9957 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9958 cast<CXXMethodDecl>(InstantiatedFrom),
9960 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9961 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9962 cast<CXXRecordDecl>(InstantiatedFrom),
9964 }
9965
9966 Previous.clear();
9967 Previous.addDecl(FoundInstantiation);
9968 return false;
9969 }
9970
9971 // Make sure that this is a specialization of a member.
9972 if (!InstantiatedFrom) {
9973 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9974 << Member;
9975 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9976 return true;
9977 }
9978
9979 // C++ [temp.expl.spec]p6:
9980 // If a template, a member template or the member of a class template is
9981 // explicitly specialized then that specialization shall be declared
9982 // before the first use of that specialization that would cause an implicit
9983 // instantiation to take place, in every translation unit in which such a
9984 // use occurs; no diagnostic is required.
9985 assert(MSInfo && "Member specialization info missing?");
9986
9987 bool HasNoEffect = false;
9990 Instantiation,
9992 MSInfo->getPointOfInstantiation(),
9993 HasNoEffect))
9994 return true;
9995
9996 // Check the scope of this explicit specialization.
9998 InstantiatedFrom,
9999 Instantiation, Member->getLocation(),
10000 false))
10001 return true;
10002
10003 // Note that this member specialization is an "instantiation of" the
10004 // corresponding member of the original template.
10005 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10006 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10007 if (InstantiationFunction->getTemplateSpecializationKind() ==
10009 // Explicit specializations of member functions of class templates do not
10010 // inherit '=delete' from the member function they are specializing.
10011 if (InstantiationFunction->isDeleted()) {
10012 // FIXME: This assert will not hold in the presence of modules.
10013 assert(InstantiationFunction->getCanonicalDecl() ==
10014 InstantiationFunction);
10015 // FIXME: We need an update record for this AST mutation.
10016 InstantiationFunction->setDeletedAsWritten(false);
10017 }
10018 }
10019
10020 MemberFunction->setInstantiationOfMemberFunction(
10022 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10023 MemberVar->setInstantiationOfStaticDataMember(
10024 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10025 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10026 MemberClass->setInstantiationOfMemberClass(
10028 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10029 MemberEnum->setInstantiationOfMemberEnum(
10030 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10031 } else {
10032 llvm_unreachable("unknown member specialization kind");
10033 }
10034
10035 // Save the caller the trouble of having to figure out which declaration
10036 // this specialization matches.
10037 Previous.clear();
10038 Previous.addDecl(FoundInstantiation);
10039 return false;
10040}
10041
10042/// Complete the explicit specialization of a member of a class template by
10043/// updating the instantiated member to be marked as an explicit specialization.
10044///
10045/// \param OrigD The member declaration instantiated from the template.
10046/// \param Loc The location of the explicit specialization of the member.
10047template<typename DeclT>
10048static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10049 SourceLocation Loc) {
10050 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10051 return;
10052
10053 // FIXME: Inform AST mutation listeners of this AST mutation.
10054 // FIXME: If there are multiple in-class declarations of the member (from
10055 // multiple modules, or a declaration and later definition of a member type),
10056 // should we update all of them?
10057 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10058 OrigD->setLocation(Loc);
10059}
10060
10063 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10064 if (Instantiation == Member)
10065 return;
10066
10067 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10068 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10069 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10070 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10071 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10072 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10073 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10074 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10075 else
10076 llvm_unreachable("unknown member specialization kind");
10077}
10078
10079/// Check the scope of an explicit instantiation.
10080///
10081/// \returns true if a serious error occurs, false otherwise.
10083 SourceLocation InstLoc,
10084 bool WasQualifiedName) {
10086 DeclContext *CurContext = S.CurContext->getRedeclContext();
10087
10088 if (CurContext->isRecord()) {
10089 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10090 << D;
10091 return true;
10092 }
10093
10094 // C++11 [temp.explicit]p3:
10095 // An explicit instantiation shall appear in an enclosing namespace of its
10096 // template. If the name declared in the explicit instantiation is an
10097 // unqualified name, the explicit instantiation shall appear in the
10098 // namespace where its template is declared or, if that namespace is inline
10099 // (7.3.1), any namespace from its enclosing namespace set.
10100 //
10101 // This is DR275, which we do not retroactively apply to C++98/03.
10102 if (WasQualifiedName) {
10103 if (CurContext->Encloses(OrigContext))
10104 return false;
10105 } else {
10106 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10107 return false;
10108 }
10109
10110 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10111 if (WasQualifiedName)
10112 S.Diag(InstLoc,
10113 S.getLangOpts().CPlusPlus11?
10114 diag::err_explicit_instantiation_out_of_scope :
10115 diag::warn_explicit_instantiation_out_of_scope_0x)
10116 << D << NS;
10117 else
10118 S.Diag(InstLoc,
10119 S.getLangOpts().CPlusPlus11?
10120 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10121 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10122 << D << NS;
10123 } else
10124 S.Diag(InstLoc,
10125 S.getLangOpts().CPlusPlus11?
10126 diag::err_explicit_instantiation_must_be_global :
10127 diag::warn_explicit_instantiation_must_be_global_0x)
10128 << D;
10129 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10130 return false;
10131}
10132
10133/// Common checks for whether an explicit instantiation of \p D is valid.
10135 SourceLocation InstLoc,
10136 bool WasQualifiedName,
10138 // C++ [temp.explicit]p13:
10139 // An explicit instantiation declaration shall not name a specialization of
10140 // a template with internal linkage.
10143 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10144 return true;
10145 }
10146
10147 // C++11 [temp.explicit]p3: [DR 275]
10148 // An explicit instantiation shall appear in an enclosing namespace of its
10149 // template.
10150 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10151 return true;
10152
10153 return false;
10154}
10155
10156/// Determine whether the given scope specifier has a template-id in it.
10158 // C++11 [temp.explicit]p3:
10159 // If the explicit instantiation is for a member function, a member class
10160 // or a static data member of a class template specialization, the name of
10161 // the class template specialization in the qualified-id for the member
10162 // name shall be a simple-template-id.
10163 //
10164 // C++98 has the same restriction, just worded differently.
10165 for (NestedNameSpecifier NNS = SS.getScopeRep();
10167 /**/) {
10168 const Type *T = NNS.getAsType();
10170 return true;
10171 NNS = T->getPrefix();
10172 }
10173 return false;
10174}
10175
10176/// Make a dllexport or dllimport attr on a class template specialization take
10177/// effect.
10180 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10181 assert(A && "dllExportImportClassTemplateSpecialization called "
10182 "on Def without dllexport or dllimport");
10183
10184 // We reject explicit instantiations in class scope, so there should
10185 // never be any delayed exported classes to worry about.
10186 assert(S.DelayedDllExportClasses.empty() &&
10187 "delayed exports present at explicit instantiation");
10189
10190 // Propagate attribute to base class templates.
10191 for (auto &B : Def->bases()) {
10192 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10193 B.getType()->getAsCXXRecordDecl()))
10195 }
10196
10198}
10199
10201 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10202 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10203 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10204 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10205 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10206 // Find the class template we're specializing
10207 TemplateName Name = TemplateD.get();
10208 TemplateDecl *TD = Name.getAsTemplateDecl();
10209 // Check that the specialization uses the same tag kind as the
10210 // original template.
10212 assert(Kind != TagTypeKind::Enum &&
10213 "Invalid enum tag in class template explicit instantiation!");
10214
10215 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10216
10217 if (!ClassTemplate) {
10218 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10219 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10220 Diag(TD->getLocation(), diag::note_previous_use);
10221 return true;
10222 }
10223
10224 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10225 Kind, /*isDefinition*/false, KWLoc,
10226 ClassTemplate->getIdentifier())) {
10227 Diag(KWLoc, diag::err_use_with_wrong_tag)
10228 << ClassTemplate
10230 ClassTemplate->getTemplatedDecl()->getKindName());
10231 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10232 diag::note_previous_use);
10233 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10234 }
10235
10236 // C++0x [temp.explicit]p2:
10237 // There are two forms of explicit instantiation: an explicit instantiation
10238 // definition and an explicit instantiation declaration. An explicit
10239 // instantiation declaration begins with the extern keyword. [...]
10240 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10243
10245 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10246 // Check for dllexport class template instantiation declarations,
10247 // except for MinGW mode.
10248 for (const ParsedAttr &AL : Attr) {
10249 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10250 Diag(ExternLoc,
10251 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10252 Diag(AL.getLoc(), diag::note_attribute);
10253 break;
10254 }
10255 }
10256
10257 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10258 Diag(ExternLoc,
10259 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10260 Diag(A->getLocation(), diag::note_attribute);
10261 }
10262 }
10263
10264 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10265 // instantiation declarations for most purposes.
10266 bool DLLImportExplicitInstantiationDef = false;
10268 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10269 // Check for dllimport class template instantiation definitions.
10270 bool DLLImport =
10271 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10272 for (const ParsedAttr &AL : Attr) {
10273 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10274 DLLImport = true;
10275 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10276 // dllexport trumps dllimport here.
10277 DLLImport = false;
10278 break;
10279 }
10280 }
10281 if (DLLImport) {
10283 DLLImportExplicitInstantiationDef = true;
10284 }
10285 }
10286
10287 // Translate the parser's template argument list in our AST format.
10288 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10289 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10290
10291 // Check that the template argument list is well-formed for this
10292 // template.
10294 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10295 /*DefaultArgs=*/{}, false, CTAI,
10296 /*UpdateArgsWithConversions=*/true,
10297 /*ConstraintsNotSatisfied=*/nullptr))
10298 return true;
10299
10300 // Find the class template specialization declaration that
10301 // corresponds to these arguments.
10302 void *InsertPos = nullptr;
10304 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10305
10306 TemplateSpecializationKind PrevDecl_TSK
10307 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10308
10309 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10310 Context.getTargetInfo().getTriple().isOSCygMing()) {
10311 // Check for dllexport class template instantiation definitions in MinGW
10312 // mode, if a previous declaration of the instantiation was seen.
10313 for (const ParsedAttr &AL : Attr) {
10314 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10315 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10316 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10317 } else {
10318 Diag(AL.getLoc(),
10319 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10320 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10321 }
10322 break;
10323 }
10324 }
10325 }
10326
10327 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10328 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10329 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10330 return AL.getKind() == ParsedAttr::AT_DLLExport;
10331 })) {
10332 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10333 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10334 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10335 }
10336 }
10337
10338 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10339 SS.isSet(), TSK))
10340 return true;
10341
10343
10344 bool HasNoEffect = false;
10345 if (PrevDecl) {
10346 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10347 PrevDecl, PrevDecl_TSK,
10348 PrevDecl->getPointOfInstantiation(),
10349 HasNoEffect))
10350 return PrevDecl;
10351
10352 // Even though HasNoEffect == true means that this explicit instantiation
10353 // has no effect on semantics, we go on to put its syntax in the AST.
10354
10355 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10356 PrevDecl_TSK == TSK_Undeclared) {
10357 // Since the only prior class template specialization with these
10358 // arguments was referenced but not declared, reuse that
10359 // declaration node as our own, updating the source location
10360 // for the template name to reflect our new declaration.
10361 // (Other source locations will be updated later.)
10362 Specialization = PrevDecl;
10363 Specialization->setLocation(TemplateNameLoc);
10364 PrevDecl = nullptr;
10365 }
10366
10367 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10368 DLLImportExplicitInstantiationDef) {
10369 // The new specialization might add a dllimport attribute.
10370 HasNoEffect = false;
10371 }
10372 }
10373
10374 if (!Specialization) {
10375 // Create a new class template specialization declaration node for
10376 // this explicit specialization.
10378 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10379 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10381
10382 // A MSInheritanceAttr attached to the previous declaration must be
10383 // propagated to the new node prior to instantiation.
10384 if (PrevDecl) {
10385 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10386 auto *Clone = A->clone(getASTContext());
10387 Clone->setInherited(true);
10388 Specialization->addAttr(Clone);
10389 Consumer.AssignInheritanceModel(Specialization);
10390 }
10391 }
10392
10393 if (!HasNoEffect && !PrevDecl) {
10394 // Insert the new specialization.
10395 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10396 }
10397 }
10398
10399 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10400
10401 // Set source locations for keywords.
10402 Specialization->setExternKeywordLoc(ExternLoc);
10403 Specialization->setTemplateKeywordLoc(TemplateLoc);
10404 Specialization->setBraceRange(SourceRange());
10405
10406 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10409
10410 // Add the explicit instantiation into its lexical context. However,
10411 // since explicit instantiations are never found by name lookup, we
10412 // just put it into the declaration context directly.
10413 Specialization->setLexicalDeclContext(CurContext);
10414 CurContext->addDecl(Specialization);
10415
10416 // Syntax is now OK, so return if it has no other effect on semantics.
10417 if (HasNoEffect) {
10418 // Set the template specialization kind.
10419 Specialization->setTemplateSpecializationKind(TSK);
10420 return Specialization;
10421 }
10422
10423 // C++ [temp.explicit]p3:
10424 // A definition of a class template or class member template
10425 // shall be in scope at the point of the explicit instantiation of
10426 // the class template or class member template.
10427 //
10428 // This check comes when we actually try to perform the
10429 // instantiation.
10431 = cast_or_null<ClassTemplateSpecializationDecl>(
10432 Specialization->getDefinition());
10433 if (!Def)
10435 /*Complain=*/true,
10436 CTAI.StrictPackMatch);
10437 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10438 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10439 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10440 }
10441
10442 // Instantiate the members of this class template specialization.
10443 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10444 Specialization->getDefinition());
10445 if (Def) {
10447 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10448 // TSK_ExplicitInstantiationDefinition
10449 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10451 DLLImportExplicitInstantiationDef)) {
10452 // FIXME: Need to notify the ASTMutationListener that we did this.
10454
10455 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10456 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10457 // An explicit instantiation definition can add a dll attribute to a
10458 // template with a previous instantiation declaration. MinGW doesn't
10459 // allow this.
10460 auto *A = cast<InheritableAttr>(
10462 A->setInherited(true);
10463 Def->addAttr(A);
10465 }
10466 }
10467
10468 // Fix a TSK_ImplicitInstantiation followed by a
10469 // TSK_ExplicitInstantiationDefinition
10470 bool NewlyDLLExported =
10471 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10472 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10473 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10474 // An explicit instantiation definition can add a dll attribute to a
10475 // template with a previous implicit instantiation. MinGW doesn't allow
10476 // this. We limit clang to only adding dllexport, to avoid potentially
10477 // strange codegen behavior. For example, if we extend this conditional
10478 // to dllimport, and we have a source file calling a method on an
10479 // implicitly instantiated template class instance and then declaring a
10480 // dllimport explicit instantiation definition for the same template
10481 // class, the codegen for the method call will not respect the dllimport,
10482 // while it will with cl. The Def will already have the DLL attribute,
10483 // since the Def and Specialization will be the same in the case of
10484 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10485 // attribute to the Specialization; we just need to make it take effect.
10486 assert(Def == Specialization &&
10487 "Def and Specialization should match for implicit instantiation");
10489 }
10490
10491 // In MinGW mode, export the template instantiation if the declaration
10492 // was marked dllexport.
10493 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10494 Context.getTargetInfo().getTriple().isOSCygMing() &&
10495 PrevDecl->hasAttr<DLLExportAttr>()) {
10497 }
10498
10499 // Set the template specialization kind. Make sure it is set before
10500 // instantiating the members which will trigger ASTConsumer callbacks.
10501 Specialization->setTemplateSpecializationKind(TSK);
10502 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10503 } else {
10504
10505 // Set the template specialization kind.
10506 Specialization->setTemplateSpecializationKind(TSK);
10507 }
10508
10509 return Specialization;
10510}
10511
10514 SourceLocation TemplateLoc, unsigned TagSpec,
10515 SourceLocation KWLoc, CXXScopeSpec &SS,
10516 IdentifierInfo *Name, SourceLocation NameLoc,
10517 const ParsedAttributesView &Attr) {
10518
10519 bool Owned = false;
10520 bool IsDependent = false;
10521 Decl *TagD =
10522 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10523 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10524 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10525 false, TypeResult(), /*IsTypeSpecifier*/ false,
10526 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10527 .get();
10528 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10529
10530 if (!TagD)
10531 return true;
10532
10533 TagDecl *Tag = cast<TagDecl>(TagD);
10534 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10535
10536 if (Tag->isInvalidDecl())
10537 return true;
10538
10540 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10541 if (!Pattern) {
10542 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10543 << Context.getCanonicalTagType(Record);
10544 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10545 return true;
10546 }
10547
10548 // C++0x [temp.explicit]p2:
10549 // If the explicit instantiation is for a class or member class, the
10550 // elaborated-type-specifier in the declaration shall include a
10551 // simple-template-id.
10552 //
10553 // C++98 has the same restriction, just worded differently.
10555 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10556 << Record << SS.getRange();
10557
10558 // C++0x [temp.explicit]p2:
10559 // There are two forms of explicit instantiation: an explicit instantiation
10560 // definition and an explicit instantiation declaration. An explicit
10561 // instantiation declaration begins with the extern keyword. [...]
10565
10566 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10567
10568 // Verify that it is okay to explicitly instantiate here.
10569 CXXRecordDecl *PrevDecl
10570 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10571 if (!PrevDecl && Record->getDefinition())
10572 PrevDecl = Record;
10573 if (PrevDecl) {
10575 bool HasNoEffect = false;
10576 assert(MSInfo && "No member specialization information?");
10577 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10578 PrevDecl,
10580 MSInfo->getPointOfInstantiation(),
10581 HasNoEffect))
10582 return true;
10583 if (HasNoEffect)
10584 return TagD;
10585 }
10586
10587 CXXRecordDecl *RecordDef
10588 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10589 if (!RecordDef) {
10590 // C++ [temp.explicit]p3:
10591 // A definition of a member class of a class template shall be in scope
10592 // at the point of an explicit instantiation of the member class.
10593 CXXRecordDecl *Def
10594 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10595 if (!Def) {
10596 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10597 << 0 << Record->getDeclName() << Record->getDeclContext();
10598 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10599 << Pattern;
10600 return true;
10601 } else {
10602 if (InstantiateClass(NameLoc, Record, Def,
10604 TSK))
10605 return true;
10606
10607 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10608 if (!RecordDef)
10609 return true;
10610 }
10611 }
10612
10613 // Instantiate all of the members of the class.
10614 InstantiateClassMembers(NameLoc, RecordDef,
10616
10618 MarkVTableUsed(NameLoc, RecordDef, true);
10619
10620 // FIXME: We don't have any representation for explicit instantiations of
10621 // member classes. Such a representation is not needed for compilation, but it
10622 // should be available for clients that want to see all of the declarations in
10623 // the source code.
10624 return TagD;
10625}
10626
10628 SourceLocation ExternLoc,
10629 SourceLocation TemplateLoc,
10630 Declarator &D) {
10631 // Explicit instantiations always require a name.
10632 // TODO: check if/when DNInfo should replace Name.
10634 DeclarationName Name = NameInfo.getName();
10635 if (!Name) {
10636 if (!D.isInvalidType())
10638 diag::err_explicit_instantiation_requires_name)
10640
10641 return true;
10642 }
10643
10644 // Get the innermost enclosing declaration scope.
10645 S = S->getDeclParent();
10646
10647 // Determine the type of the declaration.
10649 QualType R = T->getType();
10650 if (R.isNull())
10651 return true;
10652
10653 // C++ [dcl.stc]p1:
10654 // A storage-class-specifier shall not be specified in [...] an explicit
10655 // instantiation (14.7.2) directive.
10657 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10658 << Name;
10659 return true;
10660 } else if (D.getDeclSpec().getStorageClassSpec()
10662 // Complain about then remove the storage class specifier.
10663 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10665
10667 }
10668
10669 // C++0x [temp.explicit]p1:
10670 // [...] An explicit instantiation of a function template shall not use the
10671 // inline or constexpr specifiers.
10672 // Presumably, this also applies to member functions of class templates as
10673 // well.
10677 diag::err_explicit_instantiation_inline :
10678 diag::warn_explicit_instantiation_inline_0x)
10680 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10681 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10682 // not already specified.
10684 diag::err_explicit_instantiation_constexpr);
10685
10686 // A deduction guide is not on the list of entities that can be explicitly
10687 // instantiated.
10689 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10690 << /*explicit instantiation*/ 0;
10691 return true;
10692 }
10693
10694 // C++0x [temp.explicit]p2:
10695 // There are two forms of explicit instantiation: an explicit instantiation
10696 // definition and an explicit instantiation declaration. An explicit
10697 // instantiation declaration begins with the extern keyword. [...]
10701
10702 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10704 /*ObjectType=*/QualType());
10705
10706 if (!R->isFunctionType()) {
10707 // C++ [temp.explicit]p1:
10708 // A [...] static data member of a class template can be explicitly
10709 // instantiated from the member definition associated with its class
10710 // template.
10711 // C++1y [temp.explicit]p1:
10712 // A [...] variable [...] template specialization can be explicitly
10713 // instantiated from its template.
10714 if (Previous.isAmbiguous())
10715 return true;
10716
10717 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10718 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10719
10720 if (!PrevTemplate) {
10721 if (!Prev || !Prev->isStaticDataMember()) {
10722 // We expect to see a static data member here.
10723 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10724 << Name;
10725 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10726 P != PEnd; ++P)
10727 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10728 return true;
10729 }
10730
10732 // FIXME: Check for explicit specialization?
10734 diag::err_explicit_instantiation_data_member_not_instantiated)
10735 << Prev;
10736 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10737 // FIXME: Can we provide a note showing where this was declared?
10738 return true;
10739 }
10740 } else {
10741 // Explicitly instantiate a variable template.
10742
10743 // C++1y [dcl.spec.auto]p6:
10744 // ... A program that uses auto or decltype(auto) in a context not
10745 // explicitly allowed in this section is ill-formed.
10746 //
10747 // This includes auto-typed variable template instantiations.
10748 if (R->isUndeducedType()) {
10749 Diag(T->getTypeLoc().getBeginLoc(),
10750 diag::err_auto_not_allowed_var_inst);
10751 return true;
10752 }
10753
10755 // C++1y [temp.explicit]p3:
10756 // If the explicit instantiation is for a variable, the unqualified-id
10757 // in the declaration shall be a template-id.
10759 diag::err_explicit_instantiation_without_template_id)
10760 << PrevTemplate;
10761 Diag(PrevTemplate->getLocation(),
10762 diag::note_explicit_instantiation_here);
10763 return true;
10764 }
10765
10766 // Translate the parser's template argument list into our AST format.
10767 TemplateArgumentListInfo TemplateArgs =
10769
10770 DeclResult Res =
10771 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10772 TemplateArgs, /*SetWrittenArgs=*/true);
10773 if (Res.isInvalid())
10774 return true;
10775
10776 if (!Res.isUsable()) {
10777 // We somehow specified dependent template arguments in an explicit
10778 // instantiation. This should probably only happen during error
10779 // recovery.
10780 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10781 return true;
10782 }
10783
10784 // Ignore access control bits, we don't need them for redeclaration
10785 // checking.
10786 Prev = cast<VarDecl>(Res.get());
10787 }
10788
10789 // C++0x [temp.explicit]p2:
10790 // If the explicit instantiation is for a member function, a member class
10791 // or a static data member of a class template specialization, the name of
10792 // the class template specialization in the qualified-id for the member
10793 // name shall be a simple-template-id.
10794 //
10795 // C++98 has the same restriction, just worded differently.
10796 //
10797 // This does not apply to variable template specializations, where the
10798 // template-id is in the unqualified-id instead.
10799 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10801 diag::ext_explicit_instantiation_without_qualified_id)
10802 << Prev << D.getCXXScopeSpec().getRange();
10803
10804 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10805
10806 // Verify that it is okay to explicitly instantiate here.
10809 bool HasNoEffect = false;
10811 PrevTSK, POI, HasNoEffect))
10812 return true;
10813
10814 if (!HasNoEffect) {
10815 // Instantiate static data member or variable template.
10817 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10818 VTSD->setExternKeywordLoc(ExternLoc);
10819 VTSD->setTemplateKeywordLoc(TemplateLoc);
10820 }
10821
10822 // Merge attributes.
10824 if (PrevTemplate)
10825 ProcessAPINotes(Prev);
10826
10829 }
10830
10831 // Check the new variable specialization against the parsed input.
10832 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10833 Diag(T->getTypeLoc().getBeginLoc(),
10834 diag::err_invalid_var_template_spec_type)
10835 << 0 << PrevTemplate << R << Prev->getType();
10836 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10837 << 2 << PrevTemplate->getDeclName();
10838 return true;
10839 }
10840
10841 // FIXME: Create an ExplicitInstantiation node?
10842 return (Decl*) nullptr;
10843 }
10844
10845 // If the declarator is a template-id, translate the parser's template
10846 // argument list into our AST format.
10847 bool HasExplicitTemplateArgs = false;
10848 TemplateArgumentListInfo TemplateArgs;
10850 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10851 HasExplicitTemplateArgs = true;
10852 }
10853
10854 // C++ [temp.explicit]p1:
10855 // A [...] function [...] can be explicitly instantiated from its template.
10856 // A member function [...] of a class template can be explicitly
10857 // instantiated from the member definition associated with its class
10858 // template.
10859 UnresolvedSet<8> TemplateMatches;
10860 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10862 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10863 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10864 P != PEnd; ++P) {
10865 NamedDecl *Prev = *P;
10866 if (!HasExplicitTemplateArgs) {
10867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10868 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10869 /*AdjustExceptionSpec*/true);
10870 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10871 if (Method->getPrimaryTemplate()) {
10872 TemplateMatches.addDecl(Method, P.getAccess());
10873 } else {
10874 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10875 C.FoundDecl = P.getPair();
10876 C.Function = Method;
10877 C.Viable = true;
10879 if (Method->getTrailingRequiresClause() &&
10881 /*ForOverloadResolution=*/true) ||
10882 !S.IsSatisfied)) {
10883 C.Viable = false;
10885 }
10886 }
10887 }
10888 }
10889 }
10890
10891 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10892 if (!FunTmpl)
10893 continue;
10894
10895 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10896 FunctionDecl *Specialization = nullptr;
10898 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10899 Specialization, Info);
10901 // Keep track of almost-matches.
10902 FailedTemplateCandidates.addCandidate().set(
10903 P.getPair(), FunTmpl->getTemplatedDecl(),
10904 MakeDeductionFailureInfo(Context, TDK, Info));
10905 (void)TDK;
10906 continue;
10907 }
10908
10909 // Target attributes are part of the cuda function signature, so
10910 // the cuda target of the instantiated function must match that of its
10911 // template. Given that C++ template deduction does not take
10912 // target attributes into account, we reject candidates here that
10913 // have a different target.
10914 if (LangOpts.CUDA &&
10915 CUDA().IdentifyTarget(Specialization,
10916 /* IgnoreImplicitHDAttr = */ true) !=
10917 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10918 FailedTemplateCandidates.addCandidate().set(
10919 P.getPair(), FunTmpl->getTemplatedDecl(),
10922 continue;
10923 }
10924
10925 TemplateMatches.addDecl(Specialization, P.getAccess());
10926 }
10927
10928 FunctionDecl *Specialization = nullptr;
10929 if (!NonTemplateMatches.empty()) {
10930 unsigned Msg = 0;
10931 OverloadCandidateDisplayKind DisplayKind;
10933 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10934 Best)) {
10935 case OR_Success:
10936 case OR_Deleted:
10937 Specialization = cast<FunctionDecl>(Best->Function);
10938 break;
10939 case OR_Ambiguous:
10940 Msg = diag::err_explicit_instantiation_ambiguous;
10941 DisplayKind = OCD_AmbiguousCandidates;
10942 break;
10944 Msg = diag::err_explicit_instantiation_no_candidate;
10945 DisplayKind = OCD_AllCandidates;
10946 break;
10947 }
10948 if (Msg) {
10949 PartialDiagnostic Diag = PDiag(Msg) << Name;
10950 NonTemplateMatches.NoteCandidates(
10951 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10952 {});
10953 return true;
10954 }
10955 }
10956
10957 if (!Specialization) {
10958 // Find the most specialized function template specialization.
10960 TemplateMatches.begin(), TemplateMatches.end(),
10961 FailedTemplateCandidates, D.getIdentifierLoc(),
10962 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10963 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10964 PDiag(diag::note_explicit_instantiation_candidate));
10965
10966 if (Result == TemplateMatches.end())
10967 return true;
10968
10969 // Ignore access control bits, we don't need them for redeclaration checking.
10971 }
10972
10973 // C++11 [except.spec]p4
10974 // In an explicit instantiation an exception-specification may be specified,
10975 // but is not required.
10976 // If an exception-specification is specified in an explicit instantiation
10977 // directive, it shall be compatible with the exception-specifications of
10978 // other declarations of that function.
10979 if (auto *FPT = R->getAs<FunctionProtoType>())
10980 if (FPT->hasExceptionSpec()) {
10981 unsigned DiagID =
10982 diag::err_mismatched_exception_spec_explicit_instantiation;
10983 if (getLangOpts().MicrosoftExt)
10984 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10986 PDiag(DiagID) << Specialization->getType(),
10987 PDiag(diag::note_explicit_instantiation_here),
10988 Specialization->getType()->getAs<FunctionProtoType>(),
10989 Specialization->getLocation(), FPT, D.getBeginLoc());
10990 // In Microsoft mode, mismatching exception specifications just cause a
10991 // warning.
10992 if (!getLangOpts().MicrosoftExt && Result)
10993 return true;
10994 }
10995
10996 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10998 diag::err_explicit_instantiation_member_function_not_instantiated)
11000 << (Specialization->getTemplateSpecializationKind() ==
11002 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11003 return true;
11004 }
11005
11006 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11007 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11008 PrevDecl = Specialization;
11009
11010 if (PrevDecl) {
11011 bool HasNoEffect = false;
11013 PrevDecl,
11015 PrevDecl->getPointOfInstantiation(),
11016 HasNoEffect))
11017 return true;
11018
11019 // FIXME: We may still want to build some representation of this
11020 // explicit specialization.
11021 if (HasNoEffect)
11022 return (Decl*) nullptr;
11023 }
11024
11025 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11026 // functions
11027 // valarray<size_t>::valarray(size_t) and
11028 // valarray<size_t>::~valarray()
11029 // that it declared to have internal linkage with the internal_linkage
11030 // attribute. Ignore the explicit instantiation declaration in this case.
11031 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11033 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11034 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11035 RD->isInStdNamespace())
11036 return (Decl*) nullptr;
11037 }
11038
11041
11042 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11043 // instantiation declarations.
11045 Specialization->hasAttr<DLLImportAttr>() &&
11046 Context.getTargetInfo().getCXXABI().isMicrosoft())
11048
11049 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11050
11051 if (Specialization->isDefined()) {
11052 // Let the ASTConsumer know that this function has been explicitly
11053 // instantiated now, and its linkage might have changed.
11054 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11055 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11057
11058 // C++0x [temp.explicit]p2:
11059 // If the explicit instantiation is for a member function, a member class
11060 // or a static data member of a class template specialization, the name of
11061 // the class template specialization in the qualified-id for the member
11062 // name shall be a simple-template-id.
11063 //
11064 // C++98 has the same restriction, just worded differently.
11065 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11066 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11067 D.getCXXScopeSpec().isSet() &&
11070 diag::ext_explicit_instantiation_without_qualified_id)
11072
11074 *this,
11075 FunTmpl ? (NamedDecl *)FunTmpl
11076 : Specialization->getInstantiatedFromMemberFunction(),
11077 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11078
11079 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11080 return (Decl*) nullptr;
11081}
11082
11084 const CXXScopeSpec &SS,
11085 const IdentifierInfo *Name,
11086 SourceLocation TagLoc,
11087 SourceLocation NameLoc) {
11088 // This has to hold, because SS is expected to be defined.
11089 assert(Name && "Expected a name in a dependent tag");
11090
11092 if (!NNS)
11093 return true;
11094
11096
11097 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11098 Diag(NameLoc, diag::err_dependent_tag_decl)
11099 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11100 return true;
11101 }
11102
11103 // Create the resulting type.
11105 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11106
11107 // Create type-source location information for this type.
11108 TypeLocBuilder TLB;
11110 TL.setElaboratedKeywordLoc(TagLoc);
11112 TL.setNameLoc(NameLoc);
11114}
11115
11117 const CXXScopeSpec &SS,
11118 const IdentifierInfo &II,
11119 SourceLocation IdLoc,
11120 ImplicitTypenameContext IsImplicitTypename) {
11121 if (SS.isInvalid())
11122 return true;
11123
11124 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11125 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11126 << FixItHint::CreateRemoval(TypenameLoc);
11127
11129 TypeSourceInfo *TSI = nullptr;
11130 QualType T =
11133 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11134 /*DeducedTSTContext=*/true);
11135 if (T.isNull())
11136 return true;
11137 return CreateParsedType(T, TSI);
11138}
11139
11142 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11143 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11144 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11145 ASTTemplateArgsPtr TemplateArgsIn,
11146 SourceLocation RAngleLoc) {
11147 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11148 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11149 ? diag::compat_cxx11_typename_outside_of_template
11150 : diag::compat_pre_cxx11_typename_outside_of_template)
11151 << FixItHint::CreateRemoval(TypenameLoc);
11152
11153 // Strangely, non-type results are not ignored by this lookup, so the
11154 // program is ill-formed if it finds an injected-class-name.
11155 if (TypenameLoc.isValid()) {
11156 auto *LookupRD =
11157 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11158 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11159 Diag(TemplateIILoc,
11160 diag::ext_out_of_line_qualified_id_type_names_constructor)
11161 << TemplateII << 0 /*injected-class-name used as template name*/
11162 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11163 }
11164 }
11165
11166 // Translate the parser's template argument list in our AST format.
11167 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11168 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11169
11173 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11174 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11175 if (T.isNull())
11176 return true;
11177
11178 // Provide source-location information for the template specialization type.
11179 TypeLocBuilder Builder;
11181 = Builder.push<TemplateSpecializationTypeLoc>(T);
11182 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11183 TemplateIILoc, TemplateArgs);
11184 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11185 return CreateParsedType(T, TSI);
11186}
11187
11188/// Determine whether this failed name lookup should be treated as being
11189/// disabled by a usage of std::enable_if.
11191 SourceRange &CondRange, Expr *&Cond) {
11192 // We must be looking for a ::type...
11193 if (!II.isStr("type"))
11194 return false;
11195
11196 // ... within an explicitly-written template specialization...
11198 return false;
11199
11200 // FIXME: Look through sugar.
11201 auto EnableIfTSTLoc =
11203 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11204 return false;
11205 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11206
11207 // ... which names a complete class template declaration...
11208 const TemplateDecl *EnableIfDecl =
11209 EnableIfTST->getTemplateName().getAsTemplateDecl();
11210 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11211 return false;
11212
11213 // ... called "enable_if".
11214 const IdentifierInfo *EnableIfII =
11215 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11216 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11217 return false;
11218
11219 // Assume the first template argument is the condition.
11220 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11221
11222 // Dig out the condition.
11223 Cond = nullptr;
11224 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11226 return true;
11227
11228 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11229
11230 // Ignore Boolean literals; they add no value.
11231 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11232 Cond = nullptr;
11233
11234 return true;
11235}
11236
11239 SourceLocation KeywordLoc,
11240 NestedNameSpecifierLoc QualifierLoc,
11241 const IdentifierInfo &II,
11242 SourceLocation IILoc,
11243 TypeSourceInfo **TSI,
11244 bool DeducedTSTContext) {
11245 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11246 DeducedTSTContext);
11247 if (T.isNull())
11248 return QualType();
11249
11250 TypeLocBuilder TLB;
11251 if (isa<DependentNameType>(T)) {
11252 auto TL = TLB.push<DependentNameTypeLoc>(T);
11253 TL.setElaboratedKeywordLoc(KeywordLoc);
11254 TL.setQualifierLoc(QualifierLoc);
11255 TL.setNameLoc(IILoc);
11258 TL.setElaboratedKeywordLoc(KeywordLoc);
11259 TL.setQualifierLoc(QualifierLoc);
11260 TL.setNameLoc(IILoc);
11261 } else if (isa<TemplateTypeParmType>(T)) {
11262 // FIXME: There might be a 'typename' keyword here, but we just drop it
11263 // as it can't be represented.
11264 assert(!QualifierLoc);
11265 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11266 } else if (isa<TagType>(T)) {
11267 auto TL = TLB.push<TagTypeLoc>(T);
11268 TL.setElaboratedKeywordLoc(KeywordLoc);
11269 TL.setQualifierLoc(QualifierLoc);
11270 TL.setNameLoc(IILoc);
11271 } else if (isa<TypedefType>(T)) {
11272 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11273 } else {
11274 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11275 }
11276 *TSI = TLB.getTypeSourceInfo(Context, T);
11277 return T;
11278}
11279
11280/// Build the type that describes a C++ typename specifier,
11281/// e.g., "typename T::type".
11284 SourceLocation KeywordLoc,
11285 NestedNameSpecifierLoc QualifierLoc,
11286 const IdentifierInfo &II,
11287 SourceLocation IILoc, bool DeducedTSTContext) {
11288 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11289
11290 CXXScopeSpec SS;
11291 SS.Adopt(QualifierLoc);
11292
11293 DeclContext *Ctx = nullptr;
11294 if (QualifierLoc) {
11295 Ctx = computeDeclContext(SS);
11296 if (!Ctx) {
11297 // If the nested-name-specifier is dependent and couldn't be
11298 // resolved to a type, build a typename type.
11299 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11300 return Context.getDependentNameType(Keyword,
11301 QualifierLoc.getNestedNameSpecifier(),
11302 &II);
11303 }
11304
11305 // If the nested-name-specifier refers to the current instantiation,
11306 // the "typename" keyword itself is superfluous. In C++03, the
11307 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11308 // allows such extraneous "typename" keywords, and we retroactively
11309 // apply this DR to C++03 code with only a warning. In any case we continue.
11310
11311 if (RequireCompleteDeclContext(SS, Ctx))
11312 return QualType();
11313 }
11314
11315 DeclarationName Name(&II);
11316 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11317 if (Ctx)
11318 LookupQualifiedName(Result, Ctx, SS);
11319 else
11320 LookupName(Result, CurScope);
11321 unsigned DiagID = 0;
11322 Decl *Referenced = nullptr;
11323 switch (Result.getResultKind()) {
11325 // If we're looking up 'type' within a template named 'enable_if', produce
11326 // a more specific diagnostic.
11327 SourceRange CondRange;
11328 Expr *Cond = nullptr;
11329 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11330 // If we have a condition, narrow it down to the specific failed
11331 // condition.
11332 if (Cond) {
11333 Expr *FailedCond;
11334 std::string FailedDescription;
11335 std::tie(FailedCond, FailedDescription) =
11337
11338 Diag(FailedCond->getExprLoc(),
11339 diag::err_typename_nested_not_found_requirement)
11340 << FailedDescription
11341 << FailedCond->getSourceRange();
11342 return QualType();
11343 }
11344
11345 Diag(CondRange.getBegin(),
11346 diag::err_typename_nested_not_found_enable_if)
11347 << Ctx << CondRange;
11348 return QualType();
11349 }
11350
11351 DiagID = Ctx ? diag::err_typename_nested_not_found
11352 : diag::err_unknown_typename;
11353 break;
11354 }
11355
11357 // We found a using declaration that is a value. Most likely, the using
11358 // declaration itself is meant to have the 'typename' keyword.
11359 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11360 IILoc);
11361 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11362 << Name << Ctx << FullRange;
11363 if (UnresolvedUsingValueDecl *Using
11364 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11365 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11366 Diag(Loc, diag::note_using_value_decl_missing_typename)
11367 << FixItHint::CreateInsertion(Loc, "typename ");
11368 }
11369 }
11370 // Fall through to create a dependent typename type, from which we can
11371 // recover better.
11372 [[fallthrough]];
11373
11375 // Okay, it's a member of an unknown instantiation.
11376 return Context.getDependentNameType(Keyword,
11377 QualifierLoc.getNestedNameSpecifier(),
11378 &II);
11379
11381 // FXIME: Missing support for UsingShadowDecl on this path?
11382 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11383 // C++ [class.qual]p2:
11384 // In a lookup in which function names are not ignored and the
11385 // nested-name-specifier nominates a class C, if the name specified
11386 // after the nested-name-specifier, when looked up in C, is the
11387 // injected-class-name of C [...] then the name is instead considered
11388 // to name the constructor of class C.
11389 //
11390 // Unlike in an elaborated-type-specifier, function names are not ignored
11391 // in typename-specifier lookup. However, they are ignored in all the
11392 // contexts where we form a typename type with no keyword (that is, in
11393 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11394 //
11395 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11396 // ignore functions, but that appears to be an oversight.
11401 Type, IILoc);
11402 // FIXME: This appears to be the only case where a template type parameter
11403 // can have an elaborated keyword. We should preserve it somehow.
11406 assert(!QualifierLoc);
11408 }
11409 return Context.getTypeDeclType(
11410 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11411 }
11412
11413 // C++ [dcl.type.simple]p2:
11414 // A type-specifier of the form
11415 // typename[opt] nested-name-specifier[opt] template-name
11416 // is a placeholder for a deduced class type [...].
11417 if (getLangOpts().CPlusPlus17) {
11418 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11419 if (!DeducedTSTContext) {
11420 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11421 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11422 Diag(IILoc, diag::err_dependent_deduced_tst)
11424 << QualType(Qualifier.getAsType(), 0);
11425 else
11426 Diag(IILoc, diag::err_deduced_tst)
11429 return QualType();
11430 }
11431 TemplateName Name = Context.getQualifiedTemplateName(
11432 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11433 TemplateName(TD));
11434 return Context.getDeducedTemplateSpecializationType(
11435 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11436 Name);
11437 }
11438 }
11439
11440 DiagID = Ctx ? diag::err_typename_nested_not_type
11441 : diag::err_typename_not_type;
11442 Referenced = Result.getFoundDecl();
11443 break;
11444
11446 DiagID = Ctx ? diag::err_typename_nested_not_type
11447 : diag::err_typename_not_type;
11448 Referenced = *Result.begin();
11449 break;
11450
11452 return QualType();
11453 }
11454
11455 // If we get here, it's because name lookup did not find a
11456 // type. Emit an appropriate diagnostic and return an error.
11457 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11458 IILoc);
11459 if (Ctx)
11460 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11461 else
11462 Diag(IILoc, DiagID) << FullRange << Name;
11463 if (Referenced)
11464 Diag(Referenced->getLocation(),
11465 Ctx ? diag::note_typename_member_refers_here
11466 : diag::note_typename_refers_here)
11467 << Name;
11468 return QualType();
11469}
11470
11471namespace {
11472 // See Sema::RebuildTypeInCurrentInstantiation
11473 class CurrentInstantiationRebuilder
11474 : public TreeTransform<CurrentInstantiationRebuilder> {
11475 SourceLocation Loc;
11476 DeclarationName Entity;
11477
11478 public:
11480
11481 CurrentInstantiationRebuilder(Sema &SemaRef,
11482 SourceLocation Loc,
11483 DeclarationName Entity)
11484 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11485 Loc(Loc), Entity(Entity) { }
11486
11487 /// Determine whether the given type \p T has already been
11488 /// transformed.
11489 ///
11490 /// For the purposes of type reconstruction, a type has already been
11491 /// transformed if it is NULL or if it is not dependent.
11492 bool AlreadyTransformed(QualType T) {
11493 return T.isNull() || !T->isInstantiationDependentType();
11494 }
11495
11496 /// Returns the location of the entity whose type is being
11497 /// rebuilt.
11498 SourceLocation getBaseLocation() { return Loc; }
11499
11500 /// Returns the name of the entity whose type is being rebuilt.
11501 DeclarationName getBaseEntity() { return Entity; }
11502
11503 /// Sets the "base" location and entity when that
11504 /// information is known based on another transformation.
11505 void setBase(SourceLocation Loc, DeclarationName Entity) {
11506 this->Loc = Loc;
11507 this->Entity = Entity;
11508 }
11509
11510 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11511 // Lambdas never need to be transformed.
11512 return E;
11513 }
11514 };
11515} // end anonymous namespace
11516
11518 SourceLocation Loc,
11519 DeclarationName Name) {
11520 if (!T || !T->getType()->isInstantiationDependentType())
11521 return T;
11522
11523 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11524 return Rebuilder.TransformType(T);
11525}
11526
11528 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11529 DeclarationName());
11530 return Rebuilder.TransformExpr(E);
11531}
11532
11534 if (SS.isInvalid())
11535 return true;
11536
11538 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11539 DeclarationName());
11541 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11542 if (!Rebuilt)
11543 return true;
11544
11545 SS.Adopt(Rebuilt);
11546 return false;
11547}
11548
11550 TemplateParameterList *Params) {
11551 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11552 Decl *Param = Params->getParam(I);
11553
11554 // There is nothing to rebuild in a type parameter.
11555 if (isa<TemplateTypeParmDecl>(Param))
11556 continue;
11557
11558 // Rebuild the template parameter list of a template template parameter.
11560 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11562 TTP->getTemplateParameters()))
11563 return true;
11564
11565 continue;
11566 }
11567
11568 // Rebuild the type of a non-type template parameter.
11570 TypeSourceInfo *NewTSI
11572 NTTP->getLocation(),
11573 NTTP->getDeclName());
11574 if (!NewTSI)
11575 return true;
11576
11577 if (NewTSI->getType()->isUndeducedType()) {
11578 // C++17 [temp.dep.expr]p3:
11579 // An id-expression is type-dependent if it contains
11580 // - an identifier associated by name lookup with a non-type
11581 // template-parameter declared with a type that contains a
11582 // placeholder type (7.1.7.4),
11583 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11584 }
11585
11586 if (NewTSI != NTTP->getTypeSourceInfo()) {
11587 NTTP->setTypeSourceInfo(NewTSI);
11588 NTTP->setType(NewTSI->getType());
11589 }
11590 }
11591
11592 return false;
11593}
11594
11595std::string
11597 const TemplateArgumentList &Args) {
11598 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11599}
11600
11601std::string
11603 const TemplateArgument *Args,
11604 unsigned NumArgs) {
11605 SmallString<128> Str;
11606 llvm::raw_svector_ostream Out(Str);
11607
11608 if (!Params || Params->size() == 0 || NumArgs == 0)
11609 return std::string();
11610
11611 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11612 if (I >= NumArgs)
11613 break;
11614
11615 if (I == 0)
11616 Out << "[with ";
11617 else
11618 Out << ", ";
11619
11620 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11621 Out << Id->getName();
11622 } else {
11623 Out << '$' << I;
11624 }
11625
11626 Out << " = ";
11627 Args[I].print(getPrintingPolicy(), Out,
11629 getPrintingPolicy(), Params, I));
11630 }
11631
11632 Out << ']';
11633 return std::string(Out.str());
11634}
11635
11637 CachedTokens &Toks) {
11638 if (!FD)
11639 return;
11640
11641 auto LPT = std::make_unique<LateParsedTemplate>();
11642
11643 // Take tokens to avoid allocations
11644 LPT->Toks.swap(Toks);
11645 LPT->D = FnD;
11646 LPT->FPO = getCurFPFeatures();
11647 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11648
11649 FD->setLateTemplateParsed(true);
11650}
11651
11653 if (!FD)
11654 return;
11655 FD->setLateTemplateParsed(false);
11656}
11657
11659 DeclContext *DC = CurContext;
11660
11661 while (DC) {
11662 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11663 const FunctionDecl *FD = RD->isLocalClass();
11664 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11665 } else if (DC->isTranslationUnit() || DC->isNamespace())
11666 return false;
11667
11668 DC = DC->getParent();
11669 }
11670 return false;
11671}
11672
11673namespace {
11674/// Walk the path from which a declaration was instantiated, and check
11675/// that every explicit specialization along that path is visible. This enforces
11676/// C++ [temp.expl.spec]/6:
11677///
11678/// If a template, a member template or a member of a class template is
11679/// explicitly specialized then that specialization shall be declared before
11680/// the first use of that specialization that would cause an implicit
11681/// instantiation to take place, in every translation unit in which such a
11682/// use occurs; no diagnostic is required.
11683///
11684/// and also C++ [temp.class.spec]/1:
11685///
11686/// A partial specialization shall be declared before the first use of a
11687/// class template specialization that would make use of the partial
11688/// specialization as the result of an implicit or explicit instantiation
11689/// in every translation unit in which such a use occurs; no diagnostic is
11690/// required.
11691class ExplicitSpecializationVisibilityChecker {
11692 Sema &S;
11693 SourceLocation Loc;
11696
11697public:
11698 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11700 : S(S), Loc(Loc), Kind(Kind) {}
11701
11702 void check(NamedDecl *ND) {
11703 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11704 return checkImpl(FD);
11705 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11706 return checkImpl(RD);
11707 if (auto *VD = dyn_cast<VarDecl>(ND))
11708 return checkImpl(VD);
11709 if (auto *ED = dyn_cast<EnumDecl>(ND))
11710 return checkImpl(ED);
11711 }
11712
11713private:
11714 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11715 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11716 : Sema::MissingImportKind::ExplicitSpecialization;
11717 const bool Recover = true;
11718
11719 // If we got a custom set of modules (because only a subset of the
11720 // declarations are interesting), use them, otherwise let
11721 // diagnoseMissingImport intelligently pick some.
11722 if (Modules.empty())
11723 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11724 else
11725 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11726 }
11727
11728 bool CheckMemberSpecialization(const NamedDecl *D) {
11729 return Kind == Sema::AcceptableKind::Visible
11732 }
11733
11734 bool CheckExplicitSpecialization(const NamedDecl *D) {
11735 return Kind == Sema::AcceptableKind::Visible
11738 }
11739
11740 bool CheckDeclaration(const NamedDecl *D) {
11741 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11743 }
11744
11745 // Check a specific declaration. There are three problematic cases:
11746 //
11747 // 1) The declaration is an explicit specialization of a template
11748 // specialization.
11749 // 2) The declaration is an explicit specialization of a member of an
11750 // templated class.
11751 // 3) The declaration is an instantiation of a template, and that template
11752 // is an explicit specialization of a member of a templated class.
11753 //
11754 // We don't need to go any deeper than that, as the instantiation of the
11755 // surrounding class / etc is not triggered by whatever triggered this
11756 // instantiation, and thus should be checked elsewhere.
11757 template<typename SpecDecl>
11758 void checkImpl(SpecDecl *Spec) {
11759 bool IsHiddenExplicitSpecialization = false;
11760 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11761 // Some invalid friend declarations are written as specializations but are
11762 // instantiated implicitly.
11763 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11764 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11765 if (SpecKind == TSK_ExplicitSpecialization) {
11766 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11767 ? !CheckMemberSpecialization(Spec)
11768 : !CheckExplicitSpecialization(Spec);
11769 } else {
11770 checkInstantiated(Spec);
11771 }
11772
11773 if (IsHiddenExplicitSpecialization)
11774 diagnose(Spec->getMostRecentDecl(), false);
11775 }
11776
11777 void checkInstantiated(FunctionDecl *FD) {
11778 if (auto *TD = FD->getPrimaryTemplate())
11779 checkTemplate(TD);
11780 }
11781
11782 void checkInstantiated(CXXRecordDecl *RD) {
11783 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11784 if (!SD)
11785 return;
11786
11787 auto From = SD->getSpecializedTemplateOrPartial();
11788 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11789 checkTemplate(TD);
11790 else if (auto *TD =
11791 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11792 if (!CheckDeclaration(TD))
11793 diagnose(TD, true);
11794 checkTemplate(TD);
11795 }
11796 }
11797
11798 void checkInstantiated(VarDecl *RD) {
11799 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11800 if (!SD)
11801 return;
11802
11803 auto From = SD->getSpecializedTemplateOrPartial();
11804 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11805 checkTemplate(TD);
11806 else if (auto *TD =
11807 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11808 if (!CheckDeclaration(TD))
11809 diagnose(TD, true);
11810 checkTemplate(TD);
11811 }
11812 }
11813
11814 void checkInstantiated(EnumDecl *FD) {}
11815
11816 template<typename TemplDecl>
11817 void checkTemplate(TemplDecl *TD) {
11818 if (TD->isMemberSpecialization()) {
11819 if (!CheckMemberSpecialization(TD))
11820 diagnose(TD->getMostRecentDecl(), false);
11821 }
11822 }
11823};
11824} // end anonymous namespace
11825
11827 if (!getLangOpts().Modules)
11828 return;
11829
11830 ExplicitSpecializationVisibilityChecker(*this, Loc,
11832 .check(Spec);
11833}
11834
11836 NamedDecl *Spec) {
11837 if (!getLangOpts().CPlusPlusModules)
11838 return checkSpecializationVisibility(Loc, Spec);
11839
11840 ExplicitSpecializationVisibilityChecker(*this, Loc,
11842 .check(Spec);
11843}
11844
11847 return N->getLocation();
11848 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11850 return FD->getLocation();
11853 return N->getLocation();
11854 }
11855 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11856 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11857 continue;
11858 return CSC.PointOfInstantiation;
11859 }
11860 return N->getLocation();
11861}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1015
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:1098
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:988
@ 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:1051
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:226
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:952
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
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:3942
QualType getElementType() const
Definition TypeBase.h:3784
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:8230
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:8283
Pointer to a block type.
Definition TypeBase.h:3592
QualType getPointeeType() const
Definition TypeBase.h:3604
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:3214
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:2104
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:1552
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
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:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp: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:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:207
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
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:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
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:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
QualType getElementType() const
Definition TypeBase.h:3335
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:3810
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
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 ...
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:1273
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
ValueDecl * getDecl()
Definition Expr.h:1341
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
bool isVirtualSpecified() const
Definition DeclSpec.h:653
void ClearStorageClassSpecs()
Definition DeclSpec.h:498
bool isNoreturnSpecified() const
Definition DeclSpec.h:666
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:493
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:558
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:667
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:659
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:485
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
bool isInlineSpecified() const
Definition DeclSpec.h:642
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:494
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:654
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:841
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:645
bool hasExplicitSpecifier() const
Definition DeclSpec.h:656
bool hasConstexprSpecifier() const
Definition DeclSpec.h:842
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
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:1921
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2747
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
bool hasEllipsis() const
Definition DeclSpec.h:2746
bool isInvalidType() const
Definition DeclSpec.h:2735
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2075
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4111
QualType getPointeeType() const
Definition TypeBase.h:4123
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:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4061
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4151
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4523
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4277
QualType getElementType() const
Definition TypeBase.h:4289
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:4028
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4300
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5156
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:3095
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:3090
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:830
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:3070
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:4068
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Represents a member of a struct/union/class.
Definition Decl.h:3175
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:997
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1076
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:2015
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2491
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4207
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4516
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4315
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4174
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3749
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2555
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4146
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:4380
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2377
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4419
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3171
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4167
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4935
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5797
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:4893
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:3856
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3959
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5302
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:975
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
Represents a linkage specification.
Definition DeclCXX.h:3031
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:4414
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4401
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3735
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5535
QualType getPointeeType() const
Definition TypeBase.h:3721
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:259
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.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7993
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
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:1181
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:277
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
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:8249
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
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:8520
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3630
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
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:8431
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:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3623
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
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:3685
Represents a struct/union/class.
Definition Decl.h:4342
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4526
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5347
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
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:90
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:13755
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8532
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:11492
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11500
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12551
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12585
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7801
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:13694
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:2628
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9411
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9418
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:9725
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 BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
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:4199
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:11463
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12061
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12064
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12068
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:12241
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12259
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12249
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12269
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:11513
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11520
@ None
This is not assumed to be a template name.
Definition Sema.h:11515
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11517
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:11449
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)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp: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,...
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:13793
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:4697
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:6810
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6789
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:14070
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:11490
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:11673
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11683
@ TPC_FriendFunctionTemplate
Definition Sema.h:11681
@ TPC_ClassTemplateMember
Definition Sema.h:11679
@ TPC_FunctionTemplate
Definition Sema.h:11678
@ TPC_FriendClassTemplate
Definition Sema.h:11680
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11682
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:6360
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6497
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1300
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3519
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11455
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:9734
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:8743
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13790
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:3732
StringRef getKindName() const
Definition Decl.h:3928
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4908
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5044
TagKind getTagKind() const
Definition Decl.h:3932
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)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3703
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:3528
const Type * getTypeForDecl() const
Definition Decl.h:3553
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3562
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:6268
A container of type source information.
Definition TypeBase.h:8402
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:8413
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:1866
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2533
bool isBooleanType() const
Definition TypeBase.h:9171
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2254
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2308
bool isRValueReferenceType() const
Definition TypeBase.h:8700
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:714
bool isArrayType() const
Definition TypeBase.h:8767
bool isPointerType() const
Definition TypeBase.h:8668
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
bool isEnumeralType() const
Definition TypeBase.h:8799
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2121
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:473
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9156
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8855
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2949
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2840
bool isLValueReferenceType() const
Definition TypeBase.h:8696
bool isBitIntType() const
Definition TypeBase.h:8943
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8791
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2074
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2850
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
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:4979
bool isPointerOrReferenceType() const
Definition TypeBase.h:8672
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2480
bool isFunctionType() const
Definition TypeBase.h:8664
bool isVectorType() const
Definition TypeBase.h:8807
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2459
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isNullPtrType() const
Definition TypeBase.h:9071
bool isRecordType() const
Definition TypeBase.h:8795
QualType getUnderlyingType() const
Definition Decl.h:3632
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4121
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:2247
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1065
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1245
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1061
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
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:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6073
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3956
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3415
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3479
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:926
TLSKind getTLSKind() const
Definition Decl.cpp:2181
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1298
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2785
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:2920
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:2813
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:2792
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2911
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4016
Represents a GCC generic vector type.
Definition TypeBase.h:4225
QualType getElementType() const
Definition TypeBase.h:4239
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:1904
@ 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:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1017
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1013
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:5981
@ Enum
The "enum" keyword.
Definition TypeBase.h:5995
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:1800
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:1250
@ 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:5956
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5970
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5974
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:1606
#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:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5442
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3333
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3350
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3315
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:12099
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12095
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12088
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12085
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12085
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:13306
A stack object to be created when performing template instantiation.
Definition Sema.h:13393
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13546
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:1044