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