clang 24.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
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
179Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
180 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
181 bool EnteringContext, TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool AllowTypoCorrection) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
188
189 switch (Name.getKind()) {
191 TName = DeclarationName(Name.Identifier);
192 break;
193
195 TName = Context.DeclarationNames.getCXXOperatorName(
197 break;
198
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201 break;
202
203 default:
204 return TNK_Non_template;
205 }
206
207 QualType ObjectType = ObjectTypePtr.get();
208
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 /*RequiredTemplate=*/SourceLocation(),
213 &AssumedTemplate, AllowTypoCorrection))
214 return TNK_Non_template;
215 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238 if (isa<FunctionTemplateDecl>(FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(*R.begin());
280 assert(D && "unambiguous result is not a template name");
281 }
282
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (!SS.isInvalid()) {
294 NestedNameSpecifier Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296 Template);
297 }
298
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
308 TemplateKind =
310 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
314 }
315 }
316
318 S->getTemplateParamParent() == nullptr)
319 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
320 // Recover by returning the template, even though we would never be able to
321 // substitute it.
322
323 TemplateResult = TemplateTy::make(Template);
324 return TemplateKind;
325}
326
328 SourceLocation NameLoc, CXXScopeSpec &SS,
329 ParsedTemplateTy *Template /*=nullptr*/) {
330 // We could use redeclaration lookup here, but we don't need to: the
331 // syntactic form of a deduction guide is enough to identify it even
332 // if we can't look up the template name at all.
333 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
334 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
335 /*EnteringContext*/ false))
336 return false;
337
338 if (R.empty()) return false;
339 if (R.isAmbiguous()) {
340 // FIXME: Diagnose an ambiguity if we find at least one template.
341 R.suppressDiagnostics();
342 return false;
343 }
344
345 // We only treat template-names that name type templates as valid deduction
346 // guide names.
347 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
348 if (!TD || !getAsTypeTemplateDecl(TD))
349 return false;
350
351 if (Template) {
352 TemplateName Name = Context.getQualifiedTemplateName(
353 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
354 *Template = TemplateTy::make(Name);
355 }
356 return true;
357}
358
360 SourceLocation IILoc,
361 Scope *S,
362 const CXXScopeSpec *SS,
363 TemplateTy &SuggestedTemplate,
364 TemplateNameKind &SuggestedKind) {
365 // We can't recover unless there's a dependent scope specifier preceding the
366 // template name.
367 // FIXME: Typo correction?
368 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
370 return false;
371
372 // The code is missing a 'template' keyword prior to the dependent template
373 // name.
374 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
375 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
376 Diag(IILoc, diag::err_template_kw_missing)
377 << SuggestedTemplate.get()
378 << FixItHint::CreateInsertion(IILoc, "template ");
379 SuggestedKind = TNK_Dependent_template_name;
380 return true;
381}
382
384 QualType ObjectType, bool EnteringContext,
385 RequiredTemplateKind RequiredTemplate,
387 bool AllowTypoCorrection) {
388 if (ATK)
390
391 if (SS.isInvalid())
392 return true;
393
394 Found.setTemplateNameLookup(true);
395
396 // Determine where to perform name lookup
397 DeclContext *LookupCtx = nullptr;
398 bool IsDependent = false;
399 if (!ObjectType.isNull()) {
400 // This nested-name-specifier occurs in a member access expression, e.g.,
401 // x->B::f, and we are looking into the type of the object.
402 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
403 LookupCtx = computeDeclContext(ObjectType);
404 IsDependent = !LookupCtx && ObjectType->isDependentType();
405 assert((IsDependent || !ObjectType->isIncompleteType() ||
406 !ObjectType->getAs<TagType>() ||
407 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
408 "Caller should have completed object type");
409
410 // Template names cannot appear inside an Objective-C class or object type
411 // or a vector type.
412 //
413 // FIXME: This is wrong. For example:
414 //
415 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
416 // Vec<int> vi;
417 // vi.Vec<int>::~Vec<int>();
418 //
419 // ... should be accepted but we will not treat 'Vec' as a template name
420 // here. The right thing to do would be to check if the name is a valid
421 // vector component name, and look up a template name if not. And similarly
422 // for lookups into Objective-C class and object types, where the same
423 // problem can arise.
424 if (ObjectType->isObjCObjectOrInterfaceType() ||
425 ObjectType->isVectorType()) {
426 Found.clear();
427 return false;
428 }
429 } else if (SS.isNotEmpty()) {
430 // This nested-name-specifier occurs after another nested-name-specifier,
431 // so long into the context associated with the prior nested-name-specifier.
432 LookupCtx = computeDeclContext(SS, EnteringContext);
433 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
434
435 // The declaration context must be complete.
436 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
437 return true;
438 }
439
440 bool ObjectTypeSearchedInScope = false;
441 bool AllowFunctionTemplatesInLookup = true;
442 if (LookupCtx) {
443 // Perform "qualified" name lookup into the declaration context we
444 // computed, which is either the type of the base of a member access
445 // expression or the declaration context associated with a prior
446 // nested-name-specifier.
447 LookupQualifiedName(Found, LookupCtx);
448
449 // FIXME: The C++ standard does not clearly specify what happens in the
450 // case where the object type is dependent, and implementations vary. In
451 // Clang, we treat a name after a . or -> as a template-name if lookup
452 // finds a non-dependent member or member of the current instantiation that
453 // is a type template, or finds no such members and lookup in the context
454 // of the postfix-expression finds a type template. In the latter case, the
455 // name is nonetheless dependent, and we may resolve it to a member of an
456 // unknown specialization when we come to instantiate the template.
457 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
458 }
459
460 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
461 // C++ [basic.lookup.classref]p1:
462 // In a class member access expression (5.2.5), if the . or -> token is
463 // immediately followed by an identifier followed by a <, the
464 // identifier must be looked up to determine whether the < is the
465 // beginning of a template argument list (14.2) or a less-than operator.
466 // The identifier is first looked up in the class of the object
467 // expression. If the identifier is not found, it is then looked up in
468 // the context of the entire postfix-expression and shall name a class
469 // template.
470 if (S)
471 LookupName(Found, S);
472
473 if (!ObjectType.isNull()) {
474 // FIXME: We should filter out all non-type templates here, particularly
475 // variable templates and concepts. But the exclusion of alias templates
476 // and template template parameters is a wording defect.
477 AllowFunctionTemplatesInLookup = false;
478 ObjectTypeSearchedInScope = true;
479 }
480
481 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
482 }
483
484 if (Found.isAmbiguous())
485 return false;
486
487 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
488 !RequiredTemplate.hasTemplateKeyword()) {
489 // C++2a [temp.names]p2:
490 // A name is also considered to refer to a template if it is an
491 // unqualified-id followed by a < and name lookup finds either one or more
492 // functions or finds nothing.
493 //
494 // To keep our behavior consistent, we apply the "finds nothing" part in
495 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
496 // successfully form a call to an undeclared template-id.
497 bool AllFunctions =
498 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
500 });
501 if (AllFunctions || (Found.empty() && !IsDependent)) {
502 // If lookup found any functions, or if this is a name that can only be
503 // used for a function, then strongly assume this is a function
504 // template-id.
505 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
508 Found.clear();
509 return false;
510 }
511 }
512
513 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
514 // If we did not find any names, and this is not a disambiguation, attempt
515 // to correct any typos.
516 DeclarationName Name = Found.getLookupName();
517 Found.clear();
518
519 class TemplateNameLookupValidatorCCC final
521 public:
523
524 bool ValidateCandidate(const TypoCorrection &Candidate) final {
525 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
526 !ND || !isa<TemplateDecl>(ND))
527 return false;
529 }
530
531 std::unique_ptr<CorrectionCandidateCallback> clone() final {
532 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
533 }
534 };
535
536 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
537 FilterCCC.WantTypeSpecifiers = false;
538 FilterCCC.WantExpressionKeywords = false;
539 FilterCCC.WantRemainingKeywords = false;
540 FilterCCC.WantCXXNamedCasts = true;
541 if (TypoCorrection Corrected = CorrectTypo(
542 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
543 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
544 if (auto *ND = Corrected.getFoundDecl())
545 Found.addDecl(ND);
547 if (Found.isAmbiguous()) {
548 Found.clear();
549 } else if (!Found.empty()) {
550 // Do not erase the typo-corrected result to avoid duplicated
551 // diagnostics.
552 AllowFunctionTemplatesInLookup = true;
553 Found.setLookupName(Corrected.getCorrection());
554 if (LookupCtx) {
555 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
556 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
557 Name.getAsString() == CorrectedStr;
558 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
559 << Name << LookupCtx << DroppedSpecifier
560 << SS.getRange());
561 } else {
562 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
563 }
564
565 if (Corrected.WillReplaceSpecifier()) {
566 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
567 // In order to be valid, a non-empty CXXScopeSpec needs a source
568 // range.
569 SS.MakeTrivial(Context, NNS,
570 NNS ? Found.getNameLoc() : SourceRange());
571 }
572 }
573 }
574 }
575
576 NamedDecl *ExampleLookupResult =
577 Found.empty() ? nullptr : Found.getRepresentativeDecl();
578 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
579 if (Found.empty()) {
580 if (IsDependent) {
581 Found.setNotFoundInCurrentInstantiation();
582 return false;
583 }
584
585 // If a 'template' keyword was used, a lookup that finds only non-template
586 // names is an error.
587 if (ExampleLookupResult && RequiredTemplate) {
588 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
589 << Found.getLookupName() << SS.getRange()
590 << RequiredTemplate.hasTemplateKeyword()
591 << RequiredTemplate.getTemplateKeywordLoc();
592 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
593 diag::note_template_kw_refers_to_non_template)
594 << Found.getLookupName();
595 return true;
596 }
597
598 return false;
599 }
600
601 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
603 // C++03 [basic.lookup.classref]p1:
604 // [...] If the lookup in the class of the object expression finds a
605 // template, the name is also looked up in the context of the entire
606 // postfix-expression and [...]
607 //
608 // Note: C++11 does not perform this second lookup.
609 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
611 FoundOuter.setTemplateNameLookup(true);
612 LookupName(FoundOuter, S);
613 // FIXME: We silently accept an ambiguous lookup here, in violation of
614 // [basic.lookup]/1.
615 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
616
617 NamedDecl *OuterTemplate;
618 if (FoundOuter.empty()) {
619 // - if the name is not found, the name found in the class of the
620 // object expression is used, otherwise
621 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
622 !(OuterTemplate =
623 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
624 // - if the name is found in the context of the entire
625 // postfix-expression and does not name a class template, the name
626 // found in the class of the object expression is used, otherwise
627 FoundOuter.clear();
628 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
629 // - if the name found is a class template, it must refer to the same
630 // entity as the one found in the class of the object expression,
631 // otherwise the program is ill-formed.
632 if (!Found.isSingleResult() ||
633 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
634 OuterTemplate->getCanonicalDecl()) {
635 Diag(Found.getNameLoc(),
636 diag::ext_nested_name_member_ref_lookup_ambiguous)
637 << Found.getLookupName()
638 << ObjectType;
639 Diag(Found.getRepresentativeDecl()->getLocation(),
640 diag::note_ambig_member_ref_object_type)
641 << ObjectType;
642 Diag(FoundOuter.getFoundDecl()->getLocation(),
643 diag::note_ambig_member_ref_scope);
644
645 // Recover by taking the template that we found in the object
646 // expression's type.
647 }
648 }
649 }
650
651 return false;
652}
653
657 if (TemplateName.isInvalid())
658 return;
659
660 DeclarationNameInfo NameInfo;
661 CXXScopeSpec SS;
662 LookupNameKind LookupKind;
663
664 DeclContext *LookupCtx = nullptr;
665 NamedDecl *Found = nullptr;
666 bool MissingTemplateKeyword = false;
667
668 // Figure out what name we looked up.
669 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
670 NameInfo = DRE->getNameInfo();
671 SS.Adopt(DRE->getQualifierLoc());
672 LookupKind = LookupOrdinaryName;
673 Found = DRE->getFoundDecl();
674 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
675 NameInfo = ME->getMemberNameInfo();
676 SS.Adopt(ME->getQualifierLoc());
677 LookupKind = LookupMemberName;
678 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
679 Found = ME->getMemberDecl();
680 } else if (auto *DSDRE =
681 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
682 NameInfo = DSDRE->getNameInfo();
683 SS.Adopt(DSDRE->getQualifierLoc());
684 MissingTemplateKeyword = true;
685 } else if (auto *DSME =
686 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
687 NameInfo = DSME->getMemberNameInfo();
688 SS.Adopt(DSME->getQualifierLoc());
689 MissingTemplateKeyword = true;
690 } else {
691 llvm_unreachable("unexpected kind of potential template name");
692 }
693
694 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
695 // was missing.
696 if (MissingTemplateKeyword) {
697 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
698 << NameInfo.getName() << SourceRange(Less, Greater);
699 return;
700 }
701
702 // Try to correct the name by looking for templates and C++ named casts.
703 struct TemplateCandidateFilter : CorrectionCandidateCallback {
704 Sema &S;
705 TemplateCandidateFilter(Sema &S) : S(S) {
706 WantTypeSpecifiers = false;
707 WantExpressionKeywords = false;
708 WantRemainingKeywords = false;
709 WantCXXNamedCasts = true;
710 };
711 bool ValidateCandidate(const TypoCorrection &Candidate) override {
712 if (auto *ND = Candidate.getCorrectionDecl())
713 return S.getAsTemplateNameDecl(ND);
714 return Candidate.isKeyword();
715 }
716
717 std::unique_ptr<CorrectionCandidateCallback> clone() override {
718 return std::make_unique<TemplateCandidateFilter>(*this);
719 }
720 };
721
722 DeclarationName Name = NameInfo.getName();
723 TemplateCandidateFilter CCC(*this);
724 if (TypoCorrection Corrected =
725 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
726 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
727 auto *ND = Corrected.getFoundDecl();
728 if (ND)
729 ND = getAsTemplateNameDecl(ND);
730 if (ND || Corrected.isKeyword()) {
731 if (LookupCtx) {
732 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
733 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
734 Name.getAsString() == CorrectedStr;
735 diagnoseTypo(Corrected,
736 PDiag(diag::err_non_template_in_member_template_id_suggest)
737 << Name << LookupCtx << DroppedSpecifier
738 << SS.getRange(), false);
739 } else {
740 diagnoseTypo(Corrected,
741 PDiag(diag::err_non_template_in_template_id_suggest)
742 << Name, false);
743 }
744 if (Found)
745 Diag(Found->getLocation(),
746 diag::note_non_template_in_template_id_found);
747 return;
748 }
749 }
750
751 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
752 << Name << SourceRange(Less, Greater);
753 if (Found)
754 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
755}
756
759 SourceLocation TemplateKWLoc,
760 const DeclarationNameInfo &NameInfo,
761 bool isAddressOfOperand,
762 const TemplateArgumentListInfo *TemplateArgs) {
763 if (SS.isEmpty()) {
764 // FIXME: This codepath is only used by dependent unqualified names
765 // (e.g. a dependent conversion-function-id, or operator= once we support
766 // it). It doesn't quite do the right thing, and it will silently fail if
767 // getCurrentThisType() returns null.
768 QualType ThisType = getCurrentThisType();
769 if (ThisType.isNull())
770 return ExprError();
771
773 Context, /*Base=*/nullptr, ThisType,
774 /*IsArrow=*/!Context.getLangOpts().HLSL,
775 /*OperatorLoc=*/SourceLocation(),
776 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
777 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
778 }
779 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
780}
781
784 SourceLocation TemplateKWLoc,
785 const DeclarationNameInfo &NameInfo,
786 const TemplateArgumentListInfo *TemplateArgs) {
787 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
788 if (!SS.isValid())
789 return CreateRecoveryExpr(
790 SS.getBeginLoc(),
791 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
792
794 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
795 TemplateArgs);
796}
797
799Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
800 QualType ParamType, SourceLocation Loc,
802 UnsignedOrNone PackIndex, bool Final) {
803 // The template argument itself might be an expression, in which case we just
804 // return that expression. This happens when substituting into an alias
805 // template.
806 Expr *Replacement;
808 Replacement = Arg.getAsExpr();
809 } else {
810 ExprResult result =
811 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
812 if (result.isInvalid())
813 return ExprError();
814 Replacement = result.get();
815 }
816 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
817 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
818 AssociatedDecl, ParamType, Index, PackIndex, Final);
819}
820
822 NamedDecl *Instantiation,
823 bool InstantiatedFromMember,
824 const NamedDecl *Pattern,
825 const NamedDecl *PatternDef,
827 bool Complain, bool *Unreachable) {
828 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
829 isa<VarDecl>(Instantiation));
830
831 bool IsEntityBeingDefined = false;
832 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
833 IsEntityBeingDefined = TD->isBeingDefined();
834
835 if (PatternDef && !IsEntityBeingDefined) {
836 NamedDecl *SuggestedDef = nullptr;
837 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
838 &SuggestedDef,
839 /*OnlyNeedComplete*/ false)) {
840 if (Unreachable)
841 *Unreachable = true;
842 // If we're allowed to diagnose this and recover, do so.
843 bool Recover = Complain && !isSFINAEContext();
844 if (Complain)
845 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
847 return !Recover;
848 }
849 return false;
850 }
851
852 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
853 return true;
854
855 CanQualType InstantiationTy;
856 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
857 InstantiationTy = Context.getCanonicalTagType(TD);
858 if (PatternDef) {
859 Diag(PointOfInstantiation,
860 diag::err_template_instantiate_within_definition)
861 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
862 << InstantiationTy;
863 // Not much point in noting the template declaration here, since
864 // we're lexically inside it.
865 Instantiation->setInvalidDecl();
866 } else if (InstantiatedFromMember) {
867 if (isa<FunctionDecl>(Instantiation)) {
868 Diag(PointOfInstantiation,
869 diag::err_explicit_instantiation_undefined_member)
870 << /*member function*/ 1 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
873 } else {
874 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
875 Diag(PointOfInstantiation,
876 diag::err_implicit_instantiate_member_undefined)
877 << InstantiationTy;
878 Diag(Pattern->getLocation(), diag::note_member_declared_at);
879 }
880 } else {
881 if (isa<FunctionDecl>(Instantiation)) {
882 Diag(PointOfInstantiation,
883 diag::err_explicit_instantiation_undefined_func_template)
884 << Pattern;
885 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
886 } else if (isa<TagDecl>(Instantiation)) {
887 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
888 << (TSK != TSK_ImplicitInstantiation)
889 << InstantiationTy;
890 NoteTemplateLocation(*Pattern);
891 } else {
892 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
893 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
894 Diag(PointOfInstantiation,
895 diag::err_explicit_instantiation_undefined_var_template)
896 << Instantiation;
897 Instantiation->setInvalidDecl();
898 } else
899 Diag(PointOfInstantiation,
900 diag::err_explicit_instantiation_undefined_member)
901 << /*static data member*/ 2 << Instantiation->getDeclName()
902 << Instantiation->getDeclContext();
903 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
904 }
905 }
906
907 // In general, Instantiation isn't marked invalid to get more than one
908 // error for multiple undefined instantiations. But the code that does
909 // explicit declaration -> explicit definition conversion can't handle
910 // invalid declarations, so mark as invalid in that case.
912 Instantiation->setInvalidDecl();
913 return true;
914}
915
917 bool SupportedForCompatibility) {
918 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
919
920 // C++23 [temp.local]p6:
921 // The name of a template-parameter shall not be bound to any following.
922 // declaration whose locus is contained by the scope to which the
923 // template-parameter belongs.
924 //
925 // When MSVC compatibility is enabled, the diagnostic is always a warning
926 // by default. Otherwise, it an error unless SupportedForCompatibility is
927 // true, in which case it is a default-to-error warning.
928 unsigned DiagId =
929 getLangOpts().MSVCCompat
930 ? diag::ext_template_param_shadow
931 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
932 : diag::err_template_param_shadow);
933 const auto *ND = cast<NamedDecl>(PrevDecl);
934 Diag(Loc, DiagId) << ND->getDeclName();
936}
937
939 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
940 D = Temp->getTemplatedDecl();
941 return Temp;
942 }
943 return nullptr;
944}
945
947 SourceLocation EllipsisLoc) const {
948 assert(Kind == Template &&
949 "Only template template arguments can be pack expansions here");
950 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
951 "Template template argument pack expansion without packs");
953 Result.EllipsisLoc = EllipsisLoc;
954 return Result;
955}
956
958 const ParsedTemplateArgument &Arg) {
959
960 switch (Arg.getKind()) {
962 TypeSourceInfo *TSI;
963 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
964 if (!TSI)
965 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
967 }
968
970 Expr *E = Arg.getAsExpr();
971 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
972 }
973
976 TemplateArgument TArg;
977 if (Arg.getEllipsisLoc().isValid())
978 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
979 else
980 TArg = Template;
981 return TemplateArgumentLoc(
982 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
984 Arg.getNameLoc(), Arg.getEllipsisLoc());
985 }
986 }
987
988 llvm_unreachable("Unhandled parsed template argument");
989}
990
992 TemplateArgumentListInfo &TemplateArgs) {
993 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
994 TemplateArgs.addArgument(translateTemplateArgument(*this,
995 TemplateArgsIn[I]));
996}
997
999 SourceLocation Loc,
1000 const IdentifierInfo *Name) {
1001 NamedDecl *PrevDecl =
1002 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1004 if (PrevDecl && PrevDecl->isTemplateParameter())
1005 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1006}
1007
1009 TypeSourceInfo *TInfo;
1010 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1011 if (T.isNull())
1012 return ParsedTemplateArgument();
1013 assert(TInfo && "template argument with no location");
1014
1015 // If we might have formed a deduced template specialization type, convert
1016 // it to a template template argument.
1017 if (getLangOpts().CPlusPlus17) {
1018 TypeLoc TL = TInfo->getTypeLoc();
1019 SourceLocation EllipsisLoc;
1020 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1021 EllipsisLoc = PET.getEllipsisLoc();
1022 TL = PET.getPatternLoc();
1023 }
1024
1025 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1026 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1027 CXXScopeSpec SS;
1028 SS.Adopt(DTST.getQualifierLoc());
1029 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1030 TemplateTy::make(Name),
1031 DTST.getTemplateNameLoc());
1032 if (EllipsisLoc.isValid())
1033 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1034 return Result;
1035 }
1036 }
1037
1038 // This is a normal type template argument. Note, if the type template
1039 // argument is an injected-class-name for a template, it has a dual nature
1040 // and can be used as either a type or a template. We handle that in
1041 // convertTypeTemplateArgumentToTemplate.
1043 ParsedType.get().getAsOpaquePtr(),
1044 TInfo->getTypeLoc().getBeginLoc());
1045}
1046
1048 SourceLocation EllipsisLoc,
1049 SourceLocation KeyLoc,
1050 IdentifierInfo *ParamName,
1051 SourceLocation ParamNameLoc,
1052 unsigned Depth, unsigned Position,
1053 SourceLocation EqualLoc,
1054 ParsedType DefaultArg,
1055 bool HasTypeConstraint) {
1056 assert(S->isTemplateParamScope() &&
1057 "Template type parameter not in template parameter scope!");
1058
1059 bool IsParameterPack = EllipsisLoc.isValid();
1061 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1062 KeyLoc, ParamNameLoc, Depth, Position,
1063 ParamName, Typename, IsParameterPack,
1064 HasTypeConstraint);
1065 Param->setAccess(AS_public);
1066
1067 if (Param->isParameterPack())
1068 if (auto *CSI = getEnclosingLambdaOrBlock())
1069 CSI->LocalPacks.push_back(Param);
1070
1071 if (ParamName) {
1072 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1073
1074 // Add the template parameter into the current scope.
1075 S->AddDecl(Param);
1076 IdResolver.AddDecl(Param);
1077 }
1078
1079 // C++0x [temp.param]p9:
1080 // A default template-argument may be specified for any kind of
1081 // template-parameter that is not a template parameter pack.
1082 if (DefaultArg && IsParameterPack) {
1083 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1084 DefaultArg = nullptr;
1085 }
1086
1087 // Handle the default argument, if provided.
1088 if (DefaultArg) {
1089 TypeSourceInfo *DefaultTInfo;
1090 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1091
1092 assert(DefaultTInfo && "expected source information for type");
1093
1094 // Check for unexpanded parameter packs.
1095 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1097 return Param;
1098
1099 // Check the template argument itself.
1100 if (CheckTemplateArgument(DefaultTInfo)) {
1101 Param->setInvalidDecl();
1102 return Param;
1103 }
1104
1105 Param->setDefaultArgument(
1106 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1107 }
1108
1109 return Param;
1110}
1111
1112/// Convert the parser's template argument list representation into our form.
1115 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1116 TemplateId.RAngleLoc);
1117 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1118 TemplateId.NumArgs);
1119 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1120 return TemplateArgs;
1121}
1122
1124
1125 TemplateName TN = TypeConstr->Template.get();
1126 NamedDecl *CD = nullptr;
1127 bool IsTypeConcept = false;
1128 bool RequiresArguments = false;
1129 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1130 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1131 RequiresArguments =
1132 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1133 CD = TTP;
1134 } else {
1135 CD = TN.getAsTemplateDecl();
1136 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1137 RequiresArguments = cast<ConceptDecl>(CD)
1138 ->getTemplateParameters()
1139 ->getMinRequiredArguments() > 1;
1140 }
1141
1142 // C++2a [temp.param]p4:
1143 // [...] The concept designated by a type-constraint shall be a type
1144 // concept ([temp.concept]).
1145 if (!IsTypeConcept) {
1146 Diag(TypeConstr->TemplateNameLoc,
1147 diag::err_type_constraint_non_type_concept);
1148 return true;
1149 }
1150
1151 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1152 return true;
1153
1154 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1155
1156 if (!WereArgsSpecified && RequiresArguments) {
1157 Diag(TypeConstr->TemplateNameLoc,
1158 diag::err_type_constraint_missing_arguments)
1159 << CD;
1160 return true;
1161 }
1162 return false;
1163}
1164
1166 TemplateIdAnnotation *TypeConstr,
1167 TemplateTypeParmDecl *ConstrainedParameter,
1168 SourceLocation EllipsisLoc) {
1169 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1170 false);
1171}
1172
1174 TemplateIdAnnotation *TypeConstr,
1175 TemplateTypeParmDecl *ConstrainedParameter,
1176 SourceLocation EllipsisLoc,
1177 bool AllowUnexpandedPack) {
1178
1179 if (CheckTypeConstraint(TypeConstr))
1180 return true;
1181
1182 TemplateName TN = TypeConstr->Template.get();
1185
1186 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1187 TypeConstr->TemplateNameLoc);
1188
1189 TemplateArgumentListInfo TemplateArgs;
1190 if (TypeConstr->LAngleLoc.isValid()) {
1191 TemplateArgs =
1192 makeTemplateArgumentListInfo(*this, *TypeConstr);
1193
1194 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1195 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1197 return true;
1198 }
1199 }
1200 }
1201 return AttachTypeConstraint(
1203 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1204 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1205 ConstrainedParameter, EllipsisLoc);
1206}
1207
1208template <typename ArgumentLocAppender>
1211 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1212 SourceLocation RAngleLoc, QualType ConstrainedType,
1213 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1214 SourceLocation EllipsisLoc) {
1215
1216 TemplateArgumentListInfo ConstraintArgs;
1217 ConstraintArgs.addArgument(
1219 /*NTTPType=*/QualType(), ParamNameLoc));
1220
1221 ConstraintArgs.setRAngleLoc(RAngleLoc);
1222 ConstraintArgs.setLAngleLoc(LAngleLoc);
1223 Appender(ConstraintArgs);
1224
1225 // C++2a [temp.param]p4:
1226 // [...] This constraint-expression E is called the immediately-declared
1227 // constraint of T. [...]
1228 CXXScopeSpec SS;
1229 SS.Adopt(NS);
1230 ExprResult ImmediatelyDeclaredConstraint;
1231 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1232 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1233 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1234 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1235 /*DoCheckConstraintSatisfaction=*/
1237 }
1238 // We have a template template parameter
1239 else {
1240 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1241 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1242 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1243 }
1244 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1245 return ImmediatelyDeclaredConstraint;
1246
1247 // C++2a [temp.param]p4:
1248 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1249 //
1250 // We have the following case:
1251 //
1252 // template<typename T> concept C1 = true;
1253 // template<C1... T> struct s1;
1254 //
1255 // The constraint: (C1<T> && ...)
1256 //
1257 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1258 // any unqualified lookups for 'operator&&' here.
1259 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1260 /*LParenLoc=*/SourceLocation(),
1261 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1262 EllipsisLoc, /*RHS=*/nullptr,
1263 /*RParenLoc=*/SourceLocation(),
1264 /*NumExpansions=*/std::nullopt);
1265}
1266
1268 DeclarationNameInfo NameInfo,
1269 TemplateDecl *NamedConcept,
1270 NamedDecl *FoundDecl,
1271 const TemplateArgumentListInfo *TemplateArgs,
1272 TemplateTypeParmDecl *ConstrainedParameter,
1273 SourceLocation EllipsisLoc) {
1274 // C++2a [temp.param]p4:
1275 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1276 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1277 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1279 *TemplateArgs) : nullptr;
1280
1281 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1282
1283 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1284 *this, NS, NameInfo, NamedConcept, FoundDecl,
1285 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1286 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1287 ParamAsArgument, ConstrainedParameter->getLocation(),
1288 [&](TemplateArgumentListInfo &ConstraintArgs) {
1289 if (TemplateArgs)
1290 for (const auto &ArgLoc : TemplateArgs->arguments())
1291 ConstraintArgs.addArgument(ArgLoc);
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid())
1295 return true;
1296
1297 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1298 /*TemplateKWLoc=*/SourceLocation{},
1299 /*ConceptNameInfo=*/NameInfo,
1300 /*FoundDecl=*/FoundDecl,
1301 /*NamedConcept=*/NamedConcept,
1302 /*ArgsWritten=*/ArgsAsWritten);
1303 ConstrainedParameter->setTypeConstraint(
1304 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1305 return false;
1306}
1307
1309 NonTypeTemplateParmDecl *NewConstrainedParm,
1310 NonTypeTemplateParmDecl *OrigConstrainedParm,
1311 SourceLocation EllipsisLoc) {
1312 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1314 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1315 diag::err_unsupported_placeholder_constraint)
1316 << NewConstrainedParm->getTypeSourceInfo()
1317 ->getTypeLoc()
1318 .getSourceRange();
1319 NewConstrainedParm->setType(TL.getType());
1320 return true;
1321 }
1322 // FIXME: Concepts: This should be the type of the placeholder, but this is
1323 // unclear in the wording right now.
1324 DeclRefExpr *Ref =
1325 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1326 VK_PRValue, OrigConstrainedParm->getLocation());
1327 if (!Ref)
1328 return true;
1329 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1331 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1333 OrigConstrainedParm->getLocation(),
1334 [&](TemplateArgumentListInfo &ConstraintArgs) {
1335 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1336 ConstraintArgs.addArgument(TL.getArgLoc(I));
1337 },
1338 EllipsisLoc);
1339 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1340 !ImmediatelyDeclaredConstraint.isUsable())
1341 return true;
1342
1343 NewConstrainedParm->setPlaceholderTypeConstraint(
1344 ImmediatelyDeclaredConstraint.get());
1345 return false;
1346}
1347
1349 SourceLocation Loc) {
1350 if (TSI->getType()->isUndeducedType()) {
1351 // C++17 [temp.dep.expr]p3:
1352 // An id-expression is type-dependent if it contains
1353 // - an identifier associated by name lookup with a non-type
1354 // template-parameter declared with a type that contains a
1355 // placeholder type (7.1.7.4),
1357 if (!NewTSI)
1358 return QualType();
1359 TSI = NewTSI;
1360 }
1361
1362 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1363}
1364
1366 if (T->isDependentType())
1367 return false;
1368
1369 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1370 return true;
1371
1372 if (T->isStructuralType())
1373 return false;
1374
1375 // Structural types are required to be object types or lvalue references.
1376 if (T->isRValueReferenceType()) {
1377 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1378 return true;
1379 }
1380
1381 // Don't mention structural types in our diagnostic prior to C++20. Also,
1382 // there's not much more we can say about non-scalar non-class types --
1383 // because we can't see functions or arrays here, those can only be language
1384 // extensions.
1385 if (!getLangOpts().CPlusPlus20 ||
1386 (!T->isScalarType() && !T->isRecordType())) {
1387 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1388 return true;
1389 }
1390
1391 // Structural types are required to be literal types.
1392 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1393 return true;
1394
1395 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1396
1397 // Drill down into the reason why the class is non-structural.
1398 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1399 // All members are required to be public and non-mutable, and can't be of
1400 // rvalue reference type. Check these conditions first to prefer a "local"
1401 // reason over a more distant one.
1402 for (const FieldDecl *FD : RD->fields()) {
1403 if (FD->getAccess() != AS_public) {
1404 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1405 return true;
1406 }
1407 if (FD->isMutable()) {
1408 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1409 return true;
1410 }
1411 if (FD->getType()->isRValueReferenceType()) {
1412 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1413 << T;
1414 return true;
1415 }
1416 }
1417
1418 // All bases are required to be public.
1419 for (const auto &BaseSpec : RD->bases()) {
1420 if (BaseSpec.getAccessSpecifier() != AS_public) {
1421 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1422 << T << 1;
1423 return true;
1424 }
1425 }
1426
1427 // All subobjects are required to be of structural types.
1428 SourceLocation SubLoc;
1429 QualType SubType;
1430 int Kind = -1;
1431
1432 for (const FieldDecl *FD : RD->fields()) {
1433 QualType T = Context.getBaseElementType(FD->getType());
1434 if (!T->isStructuralType()) {
1435 SubLoc = FD->getLocation();
1436 SubType = T;
1437 Kind = 0;
1438 break;
1439 }
1440 }
1441
1442 if (Kind == -1) {
1443 for (const auto &BaseSpec : RD->bases()) {
1444 QualType T = BaseSpec.getType();
1445 if (!T->isStructuralType()) {
1446 SubLoc = BaseSpec.getBaseTypeLoc();
1447 SubType = T;
1448 Kind = 1;
1449 break;
1450 }
1451 }
1452 }
1453
1454 assert(Kind != -1 && "couldn't find reason why type is not structural");
1455 Diag(SubLoc, diag::note_not_structural_subobject)
1456 << T << Kind << SubType;
1457 T = SubType;
1458 RD = T->getAsCXXRecordDecl();
1459 }
1460
1461 return true;
1462}
1463
1465 SourceLocation Loc) {
1466 // We don't allow variably-modified types as the type of non-type template
1467 // parameters.
1468 if (T->isVariablyModifiedType()) {
1469 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1470 << T;
1471 return QualType();
1472 }
1473
1474 if (T->isBlockPointerType()) {
1475 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1476 return QualType();
1477 }
1478
1479 // C++ [temp.param]p4:
1480 //
1481 // A non-type template-parameter shall have one of the following
1482 // (optionally cv-qualified) types:
1483 //
1484 // -- integral or enumeration type,
1485 if (T->isIntegralOrEnumerationType() ||
1486 // -- pointer to object or pointer to function,
1487 T->isPointerType() ||
1488 // -- lvalue reference to object or lvalue reference to function,
1489 T->isLValueReferenceType() ||
1490 // -- pointer to member,
1491 T->isMemberPointerType() ||
1492 // -- std::nullptr_t, or
1493 T->isNullPtrType() ||
1494 // -- a type that contains a placeholder type.
1495 T->isUndeducedType()) {
1496 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1497 // are ignored when determining its type.
1498 return T.getUnqualifiedType();
1499 }
1500
1501 // C++ [temp.param]p8:
1502 //
1503 // A non-type template-parameter of type "array of T" or
1504 // "function returning T" is adjusted to be of type "pointer to
1505 // T" or "pointer to function returning T", respectively.
1506 if (T->isArrayType() || T->isFunctionType())
1507 return Context.getDecayedType(T);
1508
1509 // If T is a dependent type, we can't do the check now, so we
1510 // assume that it is well-formed. Note that stripping off the
1511 // qualifiers here is not really correct if T turns out to be
1512 // an array type, but we'll recompute the type everywhere it's
1513 // used during instantiation, so that should be OK. (Using the
1514 // qualified type is equally wrong.)
1515 if (T->isDependentType())
1516 return T.getUnqualifiedType();
1517
1518 // C++20 [temp.param]p6:
1519 // -- a structural type
1520 if (RequireStructuralType(T, Loc))
1521 return QualType();
1522
1523 if (!getLangOpts().CPlusPlus20) {
1524 // FIXME: Consider allowing structural types as an extension in C++17. (In
1525 // earlier language modes, the template argument evaluation rules are too
1526 // inflexible.)
1527 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1528 return QualType();
1529 }
1530
1531 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1532 return T.getUnqualifiedType();
1533}
1534
1536 unsigned Depth,
1537 unsigned Position,
1538 SourceLocation EqualLoc,
1539 Expr *Default) {
1541
1542 // Check that we have valid decl-specifiers specified.
1543 auto CheckValidDeclSpecifiers = [this, &D] {
1544 // C++ [temp.param]
1545 // p1
1546 // template-parameter:
1547 // ...
1548 // parameter-declaration
1549 // p2
1550 // ... A storage class shall not be specified in a template-parameter
1551 // declaration.
1552 // [dcl.typedef]p1:
1553 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1554 // of a parameter-declaration
1555 const DeclSpec &DS = D.getDeclSpec();
1556 auto EmitDiag = [this](SourceLocation Loc) {
1557 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1559 };
1561 EmitDiag(DS.getStorageClassSpecLoc());
1562
1564 EmitDiag(DS.getThreadStorageClassSpecLoc());
1565
1566 // [dcl.inline]p1:
1567 // The inline specifier can be applied only to the declaration or
1568 // definition of a variable or function.
1569
1570 if (DS.isInlineSpecified())
1571 EmitDiag(DS.getInlineSpecLoc());
1572
1573 // [dcl.constexpr]p1:
1574 // The constexpr specifier shall be applied only to the definition of a
1575 // variable or variable template or the declaration of a function or
1576 // function template.
1577
1578 if (DS.hasConstexprSpecifier())
1579 EmitDiag(DS.getConstexprSpecLoc());
1580
1581 // [dcl.fct.spec]p1:
1582 // Function-specifiers can be used only in function declarations.
1583
1584 if (DS.isVirtualSpecified())
1585 EmitDiag(DS.getVirtualSpecLoc());
1586
1587 if (DS.hasExplicitSpecifier())
1588 EmitDiag(DS.getExplicitSpecLoc());
1589
1590 if (DS.isNoreturnSpecified())
1591 EmitDiag(DS.getNoreturnSpecLoc());
1592 };
1593
1594 CheckValidDeclSpecifiers();
1595
1596 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1597 if (isa<AutoType>(T))
1599 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1600 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1601
1602 assert(S->isTemplateParamScope() &&
1603 "Non-type template parameter not in template parameter scope!");
1604 bool Invalid = false;
1605
1607 if (T.isNull()) {
1608 T = Context.IntTy; // Recover with an 'int' type.
1609 Invalid = true;
1610 }
1611
1613
1614 const IdentifierInfo *ParamName = D.getIdentifier();
1615 bool IsParameterPack = D.hasEllipsis();
1617 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1618 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1619 TInfo);
1620 Param->setAccess(AS_public);
1621
1623 if (TL.isConstrained()) {
1624 if (D.getEllipsisLoc().isInvalid() &&
1625 T->containsUnexpandedParameterPack()) {
1626 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1627 for (auto &Loc :
1628 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1631 }
1632 if (!Invalid &&
1633 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1634 Invalid = true;
1635 }
1636
1637 if (Invalid)
1638 Param->setInvalidDecl();
1639
1640 if (Param->isParameterPack())
1641 if (auto *CSI = getEnclosingLambdaOrBlock())
1642 CSI->LocalPacks.push_back(Param);
1643
1644 if (ParamName) {
1646 ParamName);
1647
1648 // Add the template parameter into the current scope.
1649 S->AddDecl(Param);
1650 IdResolver.AddDecl(Param);
1651 }
1652
1653 // C++0x [temp.param]p9:
1654 // A default template-argument may be specified for any kind of
1655 // template-parameter that is not a template parameter pack.
1656 if (Default && IsParameterPack) {
1657 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1658 Default = nullptr;
1659 }
1660
1661 // Check the well-formedness of the default template argument, if provided.
1662 if (Default) {
1663 // Check for unexpanded parameter packs.
1665 return Param;
1666
1667 Param->setDefaultArgument(
1669 TemplateArgument(Default, /*IsCanonical=*/false),
1670 QualType(), SourceLocation()));
1671 }
1672
1673 return Param;
1674}
1675
1676/// ActOnTemplateTemplateParameter - Called when a C++ template template
1677/// parameter (e.g. T in template <template <typename> class T> class array)
1678/// has been parsed. S is the current scope.
1680 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1681 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1682 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1683 unsigned Position, SourceLocation EqualLoc,
1685 assert(S->isTemplateParamScope() &&
1686 "Template template parameter not in template parameter scope!");
1687
1688 bool IsParameterPack = EllipsisLoc.isValid();
1689
1690 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1691 if (Params->size() == 0) {
1692 Diag(Loc, diag::err_template_template_parm_no_parms)
1693 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1694
1695 // Recover as if there was a type template parameter pack.
1696 SmallVector<NamedDecl *, 4> ParamDecls;
1697 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1698 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1699 Depth + 1, 0, /*Id=*/nullptr,
1700 /*Typename=*/false, /*ParameterPack=*/true));
1702 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1703 Params->getRAngleLoc(), Params->getRequiresClause());
1704 }
1705
1706 bool Invalid = false;
1708 Params,
1709 /*OldParams=*/nullptr,
1710 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1711 Invalid = true;
1712
1713 // Construct the parameter object.
1715 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1716 IsParameterPack, Name, Kind, Typename, Params);
1717 Param->setAccess(AS_public);
1718
1719 if (Param->isParameterPack())
1720 if (auto *LSI = getEnclosingLambdaOrBlock())
1721 LSI->LocalPacks.push_back(Param);
1722
1723 // If the template template parameter has a name, then link the identifier
1724 // into the scope and lookup mechanisms.
1725 if (Name) {
1726 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1727
1728 S->AddDecl(Param);
1729 IdResolver.AddDecl(Param);
1730 }
1731
1732 if (Invalid)
1733 Param->setInvalidDecl();
1734
1735 // C++0x [temp.param]p9:
1736 // A default template-argument may be specified for any kind of
1737 // template-parameter that is not a template parameter pack.
1738 if (IsParameterPack && !Default.isInvalid()) {
1739 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1741 }
1742
1743 if (!Default.isInvalid()) {
1744 // Check only that we have a template template argument. We don't want to
1745 // try to check well-formedness now, because our template template parameter
1746 // might have dependent types in its template parameters, which we wouldn't
1747 // be able to match now.
1748 //
1749 // If none of the template template parameter's template arguments mention
1750 // other template parameters, we could actually perform more checking here.
1751 // However, it isn't worth doing.
1753 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1754 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1755 << DefaultArg.getSourceRange();
1756 return Param;
1757 }
1758
1759 TemplateName Name =
1762 if (Template &&
1764 return Param;
1765 }
1766
1767 // Check for unexpanded parameter packs.
1769 DefaultArg.getArgument().getAsTemplate(),
1771 return Param;
1772
1773 Param->setDefaultArgument(Context, DefaultArg);
1774 }
1775
1776 return Param;
1777}
1778
1779namespace {
1780class ConstraintRefersToContainingTemplateChecker
1782 using inherited = ConstDynamicRecursiveASTVisitor;
1783 bool Result = false;
1784 const FunctionDecl *Friend = nullptr;
1785 unsigned TemplateDepth = 0;
1786
1787 // Check a record-decl that we've seen to see if it is a lexical parent of the
1788 // Friend, likely because it was referred to without its template arguments.
1789 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1790 CheckingRD = CheckingRD->getMostRecentDecl();
1791 if (!CheckingRD->isTemplated())
1792 return true;
1793
1794 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1795 DC && !DC->isFileContext(); DC = DC->getParent())
1796 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1797 if (CheckingRD == RD->getMostRecentDecl()) {
1798 Result = true;
1799 return false;
1800 }
1801
1802 return true;
1803 }
1804
1805 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1806 if (D->getDepth() < TemplateDepth)
1807 Result = true;
1808
1809 // Necessary because the type of the NTTP might be what refers to the parent
1810 // constriant.
1811 return TraverseType(D->getType());
1812 }
1813
1814public:
1815 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1816 unsigned TemplateDepth)
1817 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1818
1819 bool getResult() const { return Result; }
1820
1821 // This should be the only template parm type that we have to deal with.
1822 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1823 // FunctionParmPackExpr are all partially substituted, which cannot happen
1824 // with concepts at this point in translation.
1825 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1826 if (Type->getDecl()->getDepth() < TemplateDepth) {
1827 Result = true;
1828 return false;
1829 }
1830 return true;
1831 }
1832
1833 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1834 return TraverseDecl(E->getDecl());
1835 }
1836
1837 bool TraverseTypedefType(const TypedefType *TT,
1838 bool /*TraverseQualifier*/) override {
1839 return TraverseType(TT->desugar());
1840 }
1841
1842 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1843 // We don't care about TypeLocs. So traverse Types instead.
1844 return TraverseType(TL.getType(), TraverseQualifier);
1845 }
1846
1847 bool VisitTagType(const TagType *T) override {
1848 return TraverseDecl(T->getDecl());
1849 }
1850
1851 bool TraverseDecl(const Decl *D) override {
1852 assert(D);
1853 // FIXME : This is possibly an incomplete list, but it is unclear what other
1854 // Decl kinds could be used to refer to the template parameters. This is a
1855 // best guess so far based on examples currently available, but the
1856 // unreachable should catch future instances/cases.
1857 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1858 return TraverseType(TD->getUnderlyingType());
1859 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1860 return CheckNonTypeTemplateParmDecl(NTTPD);
1861 if (auto *VD = dyn_cast<ValueDecl>(D))
1862 return TraverseType(VD->getType());
1863 if (isa<TemplateDecl>(D))
1864 return true;
1865 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1866 return CheckIfContainingRecord(RD);
1867
1869 // No direct types to visit here I believe.
1870 } else
1871 llvm_unreachable("Don't know how to handle this declaration type yet");
1872 return true;
1873 }
1874};
1875} // namespace
1876
1878 const FunctionDecl *Friend, unsigned TemplateDepth,
1879 const Expr *Constraint) {
1880 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1881 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1882 Checker.TraverseStmt(Constraint);
1883 return Checker.getResult();
1884}
1885
1888 SourceLocation ExportLoc,
1889 SourceLocation TemplateLoc,
1890 SourceLocation LAngleLoc,
1891 ArrayRef<NamedDecl *> Params,
1892 SourceLocation RAngleLoc,
1893 Expr *RequiresClause) {
1894 if (ExportLoc.isValid())
1895 Diag(ExportLoc, diag::warn_template_export_unsupported);
1896
1897 for (NamedDecl *P : Params)
1899
1900 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1901 llvm::ArrayRef(Params), RAngleLoc,
1902 RequiresClause);
1903}
1904
1906 const CXXScopeSpec &SS) {
1907 if (SS.isSet())
1908 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1909}
1910
1911// Returns the template parameter list with all default template argument
1912// information.
1914 // Make sure we get the template parameter list from the most
1915 // recent declaration, since that is the only one that is guaranteed to
1916 // have all the default template argument information.
1917 Decl *D = TD->getMostRecentDecl();
1918 // C++11 N3337 [temp.param]p12:
1919 // A default template argument shall not be specified in a friend class
1920 // template declaration.
1921 //
1922 // Skip past friend *declarations* because they are not supposed to contain
1923 // default template arguments. Moreover, these declarations may introduce
1924 // template parameters living in different template depths than the
1925 // corresponding template parameters in TD, causing unmatched constraint
1926 // substitution.
1927 //
1928 // FIXME: Diagnose such cases within a class template:
1929 // template <class T>
1930 // struct S {
1931 // template <class = void> friend struct C;
1932 // };
1933 // template struct S<int>;
1935 D->getPreviousDecl())
1936 D = D->getPreviousDecl();
1937 return cast<TemplateDecl>(D)->getTemplateParameters();
1938}
1939
1941 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1942 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1943 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1944 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1945 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1946 TemplateParameterList **OuterTemplateParamLists,
1947 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1948 assert(TemplateParams && TemplateParams->size() > 0 &&
1949 "No template parameters");
1950 assert(TUK != TagUseKind::Reference &&
1951 "Can only declare or define class templates");
1952 bool Invalid = false;
1953
1954 // Check that we can declare a template here.
1955 if (CheckTemplateDeclScope(S, TemplateParams))
1956 return true;
1957
1959 assert(Kind != TagTypeKind::Enum &&
1960 "can't build template of enumerated type");
1961
1962 // There is no such thing as an unnamed class template.
1963 if (!Name) {
1964 Diag(KWLoc, diag::err_template_unnamed_class);
1965 return true;
1966 }
1967
1968 // Find any previous declaration with this name. For a friend with no
1969 // scope explicitly specified, we only look for tag declarations (per
1970 // C++11 [basic.lookup.elab]p2).
1971 DeclContext *SemanticContext;
1972 LookupResult Previous(*this, Name, NameLoc,
1973 (SS.isEmpty() && TUK == TagUseKind::Friend)
1977 if (SS.isNotEmpty() && !SS.isInvalid()) {
1978 SemanticContext = computeDeclContext(SS, true);
1979 if (!SemanticContext) {
1980 // FIXME: Horrible, horrible hack! We can't currently represent this
1981 // in the AST, and historically we have just ignored such friend
1982 // class templates, so don't complain here.
1983 Diag(NameLoc, TUK == TagUseKind::Friend
1984 ? diag::warn_template_qualified_friend_ignored
1985 : diag::err_template_qualified_declarator_no_match)
1986 << SS.getScopeRep() << SS.getRange();
1987 return TUK != TagUseKind::Friend;
1988 }
1989
1990 if (RequireCompleteDeclContext(SS, SemanticContext))
1991 return true;
1992
1993 // If we're adding a template to a dependent context, we may need to
1994 // rebuilding some of the types used within the template parameter list,
1995 // now that we know what the current instantiation is.
1996 if (SemanticContext->isDependentContext()) {
1997 ContextRAII SavedContext(*this, SemanticContext);
1999 Invalid = true;
2000 }
2001
2002 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2003 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2004 /*TemplateId=*/nullptr,
2005 IsMemberSpecialization))
2006 return true;
2007
2008 LookupQualifiedName(Previous, SemanticContext);
2009 } else {
2010 SemanticContext = CurContext;
2011
2012 // C++14 [class.mem]p14:
2013 // If T is the name of a class, then each of the following shall have a
2014 // name different from T:
2015 // -- every member template of class T
2016 if (TUK != TagUseKind::Friend &&
2017 DiagnoseClassNameShadow(SemanticContext,
2018 DeclarationNameInfo(Name, NameLoc)))
2019 return true;
2020
2021 LookupName(Previous, S);
2022 }
2023
2024 if (Previous.isAmbiguous())
2025 return true;
2026
2027 // Let the template parameter scope enter the lookup chain of the current
2028 // class template. For example, given
2029 //
2030 // namespace ns {
2031 // template <class> bool Param = false;
2032 // template <class T> struct N;
2033 // }
2034 //
2035 // template <class Param> struct ns::N { void foo(Param); };
2036 //
2037 // When we reference Param inside the function parameter list, our name lookup
2038 // chain for it should be like:
2039 // FunctionScope foo
2040 // -> RecordScope N
2041 // -> TemplateParamScope (where we will find Param)
2042 // -> NamespaceScope ns
2043 //
2044 // See also CppLookupName().
2045 if (S->isTemplateParamScope())
2046 EnterTemplatedContext(S, SemanticContext);
2047
2048 NamedDecl *PrevDecl = nullptr;
2049 if (Previous.begin() != Previous.end())
2050 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2051
2052 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2053 // Maybe we will complain about the shadowed template parameter.
2054 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2055 // Just pretend that we didn't see the previous declaration.
2056 PrevDecl = nullptr;
2057 }
2058
2059 // If there is a previous declaration with the same name, check
2060 // whether this is a valid redeclaration.
2061 ClassTemplateDecl *PrevClassTemplate =
2062 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2063
2064 // We may have found the injected-class-name of a class template,
2065 // class template partial specialization, or class template specialization.
2066 // In these cases, grab the template that is being defined or specialized.
2067 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2068 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2069 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2070 PrevClassTemplate
2071 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2072 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2073 PrevClassTemplate
2075 ->getSpecializedTemplate();
2076 }
2077 }
2078
2079 if (TUK == TagUseKind::Friend) {
2080 // C++ [namespace.memdef]p3:
2081 // [...] When looking for a prior declaration of a class or a function
2082 // declared as a friend, and when the name of the friend class or
2083 // function is neither a qualified name nor a template-id, scopes outside
2084 // the innermost enclosing namespace scope are not considered.
2085 if (!SS.isSet()) {
2086 DeclContext *OutermostContext = CurContext;
2087 while (!OutermostContext->isFileContext())
2088 OutermostContext = OutermostContext->getLookupParent();
2089
2090 if (PrevDecl &&
2091 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2092 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2093 SemanticContext = PrevDecl->getDeclContext();
2094 } else {
2095 // Declarations in outer scopes don't matter. However, the outermost
2096 // context we computed is the semantic context for our new
2097 // declaration.
2098 PrevDecl = PrevClassTemplate = nullptr;
2099 SemanticContext = OutermostContext;
2100
2101 // Check that the chosen semantic context doesn't already contain a
2102 // declaration of this name as a non-tag type.
2104 DeclContext *LookupContext = SemanticContext;
2105 while (LookupContext->isTransparentContext())
2106 LookupContext = LookupContext->getLookupParent();
2107 LookupQualifiedName(Previous, LookupContext);
2108
2109 if (Previous.isAmbiguous())
2110 return true;
2111
2112 if (Previous.begin() != Previous.end())
2113 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2114 }
2115 }
2116 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2117 SemanticContext, S, SS.isValid()))
2118 PrevDecl = PrevClassTemplate = nullptr;
2119
2120 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2121 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2122 if (SS.isEmpty() &&
2123 !(PrevClassTemplate &&
2124 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2125 SemanticContext->getRedeclContext()))) {
2126 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2127 Diag(Shadow->getTargetDecl()->getLocation(),
2128 diag::note_using_decl_target);
2129 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2130 // Recover by ignoring the old declaration.
2131 PrevDecl = PrevClassTemplate = nullptr;
2132 }
2133 }
2134
2135 if (PrevClassTemplate) {
2136 // Ensure that the template parameter lists are compatible. Skip this check
2137 // for a friend in a dependent context: the template parameter list itself
2138 // could be dependent.
2139 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2141 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2142 : CurContext,
2143 CurContext, KWLoc),
2144 TemplateParams, PrevClassTemplate,
2145 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2147 return true;
2148
2149 // C++ [temp.class]p4:
2150 // In a redeclaration, partial specialization, explicit
2151 // specialization or explicit instantiation of a class template,
2152 // the class-key shall agree in kind with the original class
2153 // template declaration (7.1.5.3).
2154 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2156 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2157 Diag(KWLoc, diag::err_use_with_wrong_tag)
2158 << Name
2159 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2160 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2161 Kind = PrevRecordDecl->getTagKind();
2162 }
2163
2164 // Check for redefinition of this class template.
2165 if (TUK == TagUseKind::Definition) {
2166 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2167 // If we have a prior definition that is not visible, treat this as
2168 // simply making that previous definition visible.
2169 NamedDecl *Hidden = nullptr;
2170 bool HiddenDefVisible = false;
2171 if (SkipBody &&
2172 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2173 SkipBody->ShouldSkip = true;
2174 SkipBody->Previous = Def;
2175 if (!HiddenDefVisible && Hidden) {
2176 auto *Tmpl =
2177 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2178 assert(Tmpl && "original definition of a class template is not a "
2179 "class template?");
2182 }
2183 } else {
2184 Diag(NameLoc, diag::err_redefinition) << Name;
2185 Diag(Def->getLocation(), diag::note_previous_definition);
2186 // FIXME: Would it make sense to try to "forget" the previous
2187 // definition, as part of error recovery?
2188 return true;
2189 }
2190 }
2191 }
2192 } else if (PrevDecl) {
2193 // C++ [temp]p5:
2194 // A class template shall not have the same name as any other
2195 // template, class, function, object, enumeration, enumerator,
2196 // namespace, or type in the same scope (3.3), except as specified
2197 // in (14.5.4).
2198 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2199 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2200 return true;
2201 }
2202
2203 // Check the template parameter list of this declaration, possibly
2204 // merging in the template parameter list from the previous class
2205 // template declaration. Skip this check for a friend in a dependent
2206 // context, because the template parameter list might be dependent.
2207 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2209 TemplateParams,
2210 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2211 : nullptr,
2212 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2213 SemanticContext->isDependentContext())
2216 : TPC_Other,
2217 SkipBody))
2218 Invalid = true;
2219
2220 if (SS.isSet()) {
2221 // If the name of the template was qualified, we must be defining the
2222 // template out-of-line.
2223 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2224 return Diag(NameLoc, TUK == TagUseKind::Friend
2225 ? diag::err_friend_decl_does_not_match
2226 : diag::err_member_decl_does_not_match)
2227 << Name << SemanticContext << /*IsDefinition*/ true
2228 << SS.getRange();
2229 }
2230
2231 // If this is a templated friend in a dependent context we should not put it
2232 // on the redecl chain. In some cases, the templated friend can be the most
2233 // recent declaration tricking the template instantiator to make substitutions
2234 // there.
2235 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2236 bool ShouldAddRedecl =
2237 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2238
2240 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2241 PrevClassTemplate && ShouldAddRedecl
2242 ? PrevClassTemplate->getTemplatedDecl()
2243 : nullptr);
2244 SetNestedNameSpecifier(*this, NewClass, SS);
2245 if (NumOuterTemplateParamLists > 0)
2247 Context,
2248 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2249
2250 // Add alignment attributes if necessary; these attributes are checked when
2251 // the ASTContext lays out the structure.
2252 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2253 if (LangOpts.HLSL)
2254 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2257 }
2258
2259 ClassTemplateDecl *NewTemplate
2260 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2261 DeclarationName(Name), TemplateParams,
2262 NewClass);
2263
2264 if (ShouldAddRedecl)
2265 NewTemplate->setPreviousDecl(PrevClassTemplate);
2266
2267 NewClass->setDescribedClassTemplate(NewTemplate);
2268
2269 if (ModulePrivateLoc.isValid())
2270 NewTemplate->setModulePrivate();
2271
2272 if (IsMemberSpecialization) {
2273 assert(PrevClassTemplate &&
2274 "Member specialization without a primary template?");
2275 NewTemplate->setMemberSpecialization();
2276 }
2277
2278 // Set the access specifier.
2279 if (!Invalid && TUK != TagUseKind::Friend &&
2280 NewTemplate->getDeclContext()->isRecord())
2281 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2282
2283 // Set the lexical context of these templates
2285 NewTemplate->setLexicalDeclContext(CurContext);
2286
2287 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2288 NewClass->startDefinition();
2289
2290 ProcessDeclAttributeList(S, NewClass, Attr);
2291
2292 if (PrevClassTemplate) {
2293 mergeDeclAttributes(NewTemplate, PrevClassTemplate);
2294 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2295 }
2296
2300
2301 if (TUK != TagUseKind::Friend) {
2302 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2303 Scope *Outer = S;
2304 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2305 Outer = Outer->getParent();
2306 PushOnScopeChains(NewTemplate, Outer);
2307 } else {
2308 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2309 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2310 NewClass->setAccess(PrevClassTemplate->getAccess());
2311 }
2312
2313 NewTemplate->setObjectOfFriendDecl();
2314
2315 // Friend templates are visible in fairly strange ways.
2316 if (!CurContext->isDependentContext()) {
2317 DeclContext *DC = SemanticContext->getRedeclContext();
2318 DC->makeDeclVisibleInContext(NewTemplate);
2319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2320 PushOnScopeChains(NewTemplate, EnclosingScope,
2321 /* AddToContext = */ false);
2322 }
2323
2325 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2326 Friend->setAccess(AS_public);
2327 CurContext->addDecl(Friend);
2328 }
2329
2330 if (PrevClassTemplate)
2331 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2332
2333 if (Invalid) {
2334 NewTemplate->setInvalidDecl();
2335 NewClass->setInvalidDecl();
2336 }
2337
2338 ActOnDocumentableDecl(NewTemplate);
2339
2340 if (SkipBody && SkipBody->ShouldSkip)
2341 return SkipBody->Previous;
2342
2343 return NewTemplate;
2344}
2345
2346/// Diagnose the presence of a default template argument on a
2347/// template parameter, which is ill-formed in certain contexts.
2348///
2349/// \returns true if the default template argument should be dropped.
2352 SourceLocation ParamLoc,
2353 SourceRange DefArgRange) {
2354 switch (TPC) {
2355 case Sema::TPC_Other:
2357 return false;
2358
2361 // C++ [temp.param]p9:
2362 // A default template-argument shall not be specified in a
2363 // function template declaration or a function template
2364 // definition [...]
2365 // If a friend function template declaration specifies a default
2366 // template-argument, that declaration shall be a definition and shall be
2367 // the only declaration of the function template in the translation unit.
2368 // (C++98/03 doesn't have this wording; see DR226).
2369 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2370 << DefArgRange;
2371 return false;
2372
2374 // C++0x [temp.param]p9:
2375 // A default template-argument shall not be specified in the
2376 // template-parameter-lists of the definition of a member of a
2377 // class template that appears outside of the member's class.
2378 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2379 << DefArgRange;
2380 return true;
2381
2384 // C++ [temp.param]p9:
2385 // A default template-argument shall not be specified in a
2386 // friend template declaration.
2387 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2388 << DefArgRange;
2389 return true;
2390
2391 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2392 // for friend function templates if there is only a single
2393 // declaration (and it is a definition). Strange!
2394 }
2395
2396 llvm_unreachable("Invalid TemplateParamListContext!");
2397}
2398
2399/// Check for unexpanded parameter packs within the template parameters
2400/// of a template template parameter, recursively.
2403 // A template template parameter which is a parameter pack is also a pack
2404 // expansion.
2405 if (TTP->isParameterPack())
2406 return false;
2407
2409 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2410 NamedDecl *P = Params->getParam(I);
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2412 if (!TTP->isParameterPack())
2413 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2414 if (TC->hasExplicitTemplateArgs())
2415 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2418 return true;
2419 continue;
2420 }
2421
2422 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2423 if (!NTTP->isParameterPack() &&
2424 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2425 NTTP->getTypeSourceInfo(),
2427 return true;
2428
2429 continue;
2430 }
2431
2432 if (TemplateTemplateParmDecl *InnerTTP
2433 = dyn_cast<TemplateTemplateParmDecl>(P))
2434 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2435 return true;
2436 }
2437
2438 return false;
2439}
2440
2442 TemplateParameterList *OldParams,
2444 SkipBodyInfo *SkipBody) {
2445 bool Invalid = false;
2446
2447 // C++ [temp.param]p10:
2448 // The set of default template-arguments available for use with a
2449 // template declaration or definition is obtained by merging the
2450 // default arguments from the definition (if in scope) and all
2451 // declarations in scope in the same way default function
2452 // arguments are (8.3.6).
2453 bool SawDefaultArgument = false;
2454 SourceLocation PreviousDefaultArgLoc;
2455
2456 // Dummy initialization to avoid warnings.
2457 TemplateParameterList::iterator OldParam = NewParams->end();
2458 if (OldParams)
2459 OldParam = OldParams->begin();
2460
2461 bool RemoveDefaultArguments = false;
2462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2463 NewParamEnd = NewParams->end();
2464 NewParam != NewParamEnd; ++NewParam) {
2465 // Whether we've seen a duplicate default argument in the same translation
2466 // unit.
2467 bool RedundantDefaultArg = false;
2468 // Whether we've found inconsis inconsitent default arguments in different
2469 // translation unit.
2470 bool InconsistentDefaultArg = false;
2471 // The name of the module which contains the inconsistent default argument.
2472 std::string PrevModuleName;
2473
2474 SourceLocation OldDefaultLoc;
2475 SourceLocation NewDefaultLoc;
2476
2477 // Variable used to diagnose missing default arguments
2478 bool MissingDefaultArg = false;
2479
2480 // Variable used to diagnose non-final parameter packs
2481 bool SawParameterPack = false;
2482
2483 if (TemplateTypeParmDecl *NewTypeParm
2484 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2485 // Check the presence of a default argument here.
2486 if (NewTypeParm->hasDefaultArgument() &&
2488 *this, TPC, NewTypeParm->getLocation(),
2489 NewTypeParm->getDefaultArgument().getSourceRange()))
2490 NewTypeParm->removeDefaultArgument();
2491
2492 // Merge default arguments for template type parameters.
2493 TemplateTypeParmDecl *OldTypeParm
2494 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2495 if (NewTypeParm->isParameterPack()) {
2496 assert(!NewTypeParm->hasDefaultArgument() &&
2497 "Parameter packs can't have a default argument!");
2498 SawParameterPack = true;
2499 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2500 NewTypeParm->hasDefaultArgument() &&
2501 (!SkipBody || !SkipBody->ShouldSkip)) {
2502 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2503 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2504 SawDefaultArgument = true;
2505
2506 if (!OldTypeParm->getOwningModule())
2507 RedundantDefaultArg = true;
2508 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2509 NewTypeParm)) {
2510 InconsistentDefaultArg = true;
2511 PrevModuleName =
2513 }
2514 PreviousDefaultArgLoc = NewDefaultLoc;
2515 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2516 // Merge the default argument from the old declaration to the
2517 // new declaration.
2518 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2519 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2520 } else if (NewTypeParm->hasDefaultArgument()) {
2521 SawDefaultArgument = true;
2522 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2523 } else if (SawDefaultArgument)
2524 MissingDefaultArg = true;
2525 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2526 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2527 // Check for unexpanded parameter packs, except in a template template
2528 // parameter pack, as in those any unexpanded packs should be expanded
2529 // along with the parameter itself.
2531 !NewNonTypeParm->isParameterPack() &&
2532 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2533 NewNonTypeParm->getTypeSourceInfo(),
2535 Invalid = true;
2536 continue;
2537 }
2538
2539 // Check the presence of a default argument here.
2540 if (NewNonTypeParm->hasDefaultArgument() &&
2542 *this, TPC, NewNonTypeParm->getLocation(),
2543 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2544 NewNonTypeParm->removeDefaultArgument();
2545 }
2546
2547 // Merge default arguments for non-type template parameters
2548 NonTypeTemplateParmDecl *OldNonTypeParm
2549 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2550 if (NewNonTypeParm->isParameterPack()) {
2551 assert(!NewNonTypeParm->hasDefaultArgument() &&
2552 "Parameter packs can't have a default argument!");
2553 if (!NewNonTypeParm->isPackExpansion())
2554 SawParameterPack = true;
2555 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2556 NewNonTypeParm->hasDefaultArgument() &&
2557 (!SkipBody || !SkipBody->ShouldSkip)) {
2558 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2559 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2560 SawDefaultArgument = true;
2561 if (!OldNonTypeParm->getOwningModule())
2562 RedundantDefaultArg = true;
2563 else if (!getASTContext().isSameDefaultTemplateArgument(
2564 OldNonTypeParm, NewNonTypeParm)) {
2565 InconsistentDefaultArg = true;
2566 PrevModuleName =
2567 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2568 }
2569 PreviousDefaultArgLoc = NewDefaultLoc;
2570 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2571 // Merge the default argument from the old declaration to the
2572 // new declaration.
2573 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2574 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2575 } else if (NewNonTypeParm->hasDefaultArgument()) {
2576 SawDefaultArgument = true;
2577 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2578 } else if (SawDefaultArgument)
2579 MissingDefaultArg = true;
2580 } else {
2581 TemplateTemplateParmDecl *NewTemplateParm
2582 = cast<TemplateTemplateParmDecl>(*NewParam);
2583
2584 // Check for unexpanded parameter packs, recursively.
2585 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2586 Invalid = true;
2587 continue;
2588 }
2589
2590 // Check the presence of a default argument here.
2591 if (NewTemplateParm->hasDefaultArgument() &&
2593 NewTemplateParm->getLocation(),
2594 NewTemplateParm->getDefaultArgument().getSourceRange()))
2595 NewTemplateParm->removeDefaultArgument();
2596
2597 // Merge default arguments for template template parameters
2598 TemplateTemplateParmDecl *OldTemplateParm
2599 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2600 if (NewTemplateParm->isParameterPack()) {
2601 assert(!NewTemplateParm->hasDefaultArgument() &&
2602 "Parameter packs can't have a default argument!");
2603 if (!NewTemplateParm->isPackExpansion())
2604 SawParameterPack = true;
2605 } else if (OldTemplateParm &&
2606 hasVisibleDefaultArgument(OldTemplateParm) &&
2607 NewTemplateParm->hasDefaultArgument() &&
2608 (!SkipBody || !SkipBody->ShouldSkip)) {
2609 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2610 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2611 SawDefaultArgument = true;
2612 if (!OldTemplateParm->getOwningModule())
2613 RedundantDefaultArg = true;
2614 else if (!getASTContext().isSameDefaultTemplateArgument(
2615 OldTemplateParm, NewTemplateParm)) {
2616 InconsistentDefaultArg = true;
2617 PrevModuleName =
2618 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2619 }
2620 PreviousDefaultArgLoc = NewDefaultLoc;
2621 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2622 // Merge the default argument from the old declaration to the
2623 // new declaration.
2624 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2625 PreviousDefaultArgLoc
2626 = OldTemplateParm->getDefaultArgument().getLocation();
2627 } else if (NewTemplateParm->hasDefaultArgument()) {
2628 SawDefaultArgument = true;
2629 PreviousDefaultArgLoc
2630 = NewTemplateParm->getDefaultArgument().getLocation();
2631 } else if (SawDefaultArgument)
2632 MissingDefaultArg = true;
2633 }
2634
2635 // C++11 [temp.param]p11:
2636 // If a template parameter of a primary class template or alias template
2637 // is a template parameter pack, it shall be the last template parameter.
2638 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2639 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2640 Diag((*NewParam)->getLocation(),
2641 diag::err_template_param_pack_must_be_last_template_parameter);
2642 Invalid = true;
2643 }
2644
2645 // [basic.def.odr]/13:
2646 // There can be more than one definition of a
2647 // ...
2648 // default template argument
2649 // ...
2650 // in a program provided that each definition appears in a different
2651 // translation unit and the definitions satisfy the [same-meaning
2652 // criteria of the ODR].
2653 //
2654 // Simply, the design of modules allows the definition of template default
2655 // argument to be repeated across translation unit. Note that the ODR is
2656 // checked elsewhere. But it is still not allowed to repeat template default
2657 // argument in the same translation unit.
2658 if (RedundantDefaultArg) {
2659 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2660 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2661 Invalid = true;
2662 } else if (InconsistentDefaultArg) {
2663 // We could only diagnose about the case that the OldParam is imported.
2664 // The case NewParam is imported should be handled in ASTReader.
2665 Diag(NewDefaultLoc,
2666 diag::err_template_param_default_arg_inconsistent_redefinition);
2667 Diag(OldDefaultLoc,
2668 diag::note_template_param_prev_default_arg_in_other_module)
2669 << PrevModuleName;
2670 Invalid = true;
2671 } else if (MissingDefaultArg &&
2672 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2673 TPC == TPC_FriendClassTemplate)) {
2674 // C++ 23[temp.param]p14:
2675 // If a template-parameter of a class template, variable template, or
2676 // alias template has a default template argument, each subsequent
2677 // template-parameter shall either have a default template argument
2678 // supplied or be a template parameter pack.
2679 Diag((*NewParam)->getLocation(),
2680 diag::err_template_param_default_arg_missing);
2681 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2682 Invalid = true;
2683 RemoveDefaultArguments = true;
2684 }
2685
2686 // If we have an old template parameter list that we're merging
2687 // in, move on to the next parameter.
2688 if (OldParams)
2689 ++OldParam;
2690 }
2691
2692 // We were missing some default arguments at the end of the list, so remove
2693 // all of the default arguments.
2694 if (RemoveDefaultArguments) {
2695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2696 NewParamEnd = NewParams->end();
2697 NewParam != NewParamEnd; ++NewParam) {
2698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2699 TTP->removeDefaultArgument();
2700 else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2702 NTTP->removeDefaultArgument();
2703 else
2704 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2705 }
2706 }
2707
2708 return Invalid;
2709}
2710
2711namespace {
2712
2713/// A class which looks for a use of a certain level of template
2714/// parameter.
2715struct DependencyChecker : DynamicRecursiveASTVisitor {
2716 unsigned Depth;
2717
2718 // Whether we're looking for a use of a template parameter that makes the
2719 // overall construct type-dependent / a dependent type. This is strictly
2720 // best-effort for now; we may fail to match at all for a dependent type
2721 // in some cases if this is set.
2722 bool IgnoreNonTypeDependent;
2723
2724 bool Match;
2725 SourceLocation MatchLoc;
2726
2727 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2728 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2729 Match(false) {}
2730
2731 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2732 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2733 NamedDecl *ND = Params->getParam(0);
2734 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2735 Depth = PD->getDepth();
2736 } else if (NonTypeTemplateParmDecl *PD =
2737 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2738 Depth = PD->getDepth();
2739 } else {
2740 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2741 }
2742 }
2743
2744 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2745 if (ParmDepth >= Depth) {
2746 Match = true;
2747 MatchLoc = Loc;
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 bool TraverseStmt(Stmt *S) override {
2754 // Prune out non-type-dependent expressions if requested. This can
2755 // sometimes result in us failing to find a template parameter reference
2756 // (if a value-dependent expression creates a dependent type), but this
2757 // mode is best-effort only.
2758 if (auto *E = dyn_cast_or_null<Expr>(S))
2759 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2760 return true;
2762 }
2763
2764 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2765 if (IgnoreNonTypeDependent && !TL.isNull() &&
2766 !TL.getType()->isDependentType())
2767 return true;
2768 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2769 }
2770
2771 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2772 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2773 }
2774
2775 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2776 // For a best-effort search, keep looking until we find a location.
2777 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2778 }
2779
2780 bool TraverseTemplateName(TemplateName N) override {
2781 if (TemplateTemplateParmDecl *PD =
2782 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2783 if (Matches(PD->getDepth()))
2784 return false;
2786 }
2787
2788 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2789 if (NonTypeTemplateParmDecl *PD =
2790 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2791 if (Matches(PD->getDepth(), E->getExprLoc()))
2792 return false;
2793 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2794 }
2795
2796 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2797 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2798 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2799 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2800 return false;
2801 }
2802 for (auto &TLoc : ULE->template_arguments())
2804 }
2805 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2806 }
2807
2808 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2809 return TraverseType(T->getReplacementType());
2810 }
2811
2812 bool VisitSubstTemplateTypeParmPackType(
2813 SubstTemplateTypeParmPackType *T) override {
2814 return TraverseTemplateArgument(T->getArgumentPack());
2815 }
2816
2817 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2818 bool TraverseQualifier) override {
2819 // An InjectedClassNameType will never have a dependent template name,
2820 // so no need to traverse it.
2821 return TraverseTemplateArguments(
2822 T->getTemplateArgs(T->getDecl()->getASTContext()));
2823 }
2824};
2825} // end anonymous namespace
2826
2827/// Determines whether a given type depends on the given parameter
2828/// list.
2829static bool
2831 if (!Params->size())
2832 return false;
2833
2834 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2835 Checker.TraverseType(T);
2836 return Checker.Match;
2837}
2838
2839// Find the source range corresponding to the named type in the given
2840// nested-name-specifier, if any.
2842 QualType T,
2843 const CXXScopeSpec &SS) {
2845 for (;;) {
2848 break;
2849 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2850 return NNSLoc.castAsTypeLoc().getSourceRange();
2851 // FIXME: This will always be empty.
2852 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2853 }
2854
2855 return SourceRange();
2856}
2857
2859 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2860 TemplateIdAnnotation *TemplateId,
2861 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2862 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2863 IsMemberSpecialization = false;
2864 Invalid = false;
2865
2866 // The sequence of nested types to which we will match up the template
2867 // parameter lists. We first build this list by starting with the type named
2868 // by the nested-name-specifier and walking out until we run out of types.
2869 SmallVector<QualType, 4> NestedTypes;
2870 QualType T;
2871 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2872 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2873 if (CXXRecordDecl *Record =
2874 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2875 T = Context.getCanonicalTagType(Record);
2876 else
2877 T = QualType(Qualifier.getAsType(), 0);
2878 }
2879
2880 // If we found an explicit specialization that prevents us from needing
2881 // 'template<>' headers, this will be set to the location of that
2882 // explicit specialization.
2883 SourceLocation ExplicitSpecLoc;
2884
2885 while (!T.isNull()) {
2886 NestedTypes.push_back(T);
2887
2888 // Retrieve the parent of a record type.
2889 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2890 // If this type is an explicit specialization, we're done.
2892 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2894 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2895 ExplicitSpecLoc = Spec->getLocation();
2896 break;
2897 }
2898 } else if (Record->getTemplateSpecializationKind()
2900 ExplicitSpecLoc = Record->getLocation();
2901 break;
2902 }
2903
2904 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2905 T = Context.getTypeDeclType(Parent);
2906 else
2907 T = QualType();
2908 continue;
2909 }
2910
2911 if (const TemplateSpecializationType *TST
2912 = T->getAs<TemplateSpecializationType>()) {
2913 TemplateName Name = TST->getTemplateName();
2914 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2915 // Look one step prior in a dependent template specialization type.
2916 if (NestedNameSpecifier NNS = DTS->getQualifier();
2918 T = QualType(NNS.getAsType(), 0);
2919 else
2920 T = QualType();
2921 continue;
2922 }
2923 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2924 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2925 T = Context.getTypeDeclType(Parent);
2926 else
2927 T = QualType();
2928 continue;
2929 }
2930 }
2931
2932 // Look one step prior in a dependent name type.
2933 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2934 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2936 T = QualType(NNS.getAsType(), 0);
2937 else
2938 T = QualType();
2939 continue;
2940 }
2941
2942 // Retrieve the parent of an enumeration type.
2943 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2944 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2945 // check here.
2946 EnumDecl *Enum = EnumT->getDecl();
2947
2948 // Get to the parent type.
2949 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2950 T = Context.getCanonicalTypeDeclType(Parent);
2951 else
2952 T = QualType();
2953 continue;
2954 }
2955
2956 T = QualType();
2957 }
2958 // Reverse the nested types list, since we want to traverse from the outermost
2959 // to the innermost while checking template-parameter-lists.
2960 std::reverse(NestedTypes.begin(), NestedTypes.end());
2961
2962 // C++0x [temp.expl.spec]p17:
2963 // A member or a member template may be nested within many
2964 // enclosing class templates. In an explicit specialization for
2965 // such a member, the member declaration shall be preceded by a
2966 // template<> for each enclosing class template that is
2967 // explicitly specialized.
2968 bool SawNonEmptyTemplateParameterList = false;
2969
2970 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2971 if (SawNonEmptyTemplateParameterList) {
2972 if (!SuppressDiagnostic)
2973 Diag(DeclLoc, diag::err_specialize_member_of_template)
2974 << !Recovery << Range;
2975 Invalid = true;
2976 IsMemberSpecialization = false;
2977 return true;
2978 }
2979
2980 return false;
2981 };
2982
2983 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2984 // Check that we can have an explicit specialization here.
2985 if (CheckExplicitSpecialization(Range, true))
2986 return true;
2987
2988 // We don't have a template header, but we should.
2989 SourceLocation ExpectedTemplateLoc;
2990 if (!ParamLists.empty())
2991 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2992 else
2993 ExpectedTemplateLoc = DeclStartLoc;
2994
2995 if (!SuppressDiagnostic)
2996 Diag(DeclLoc, diag::err_template_spec_needs_header)
2997 << Range
2998 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2999 return false;
3000 };
3001
3002 unsigned ParamIdx = 0;
3003 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3004 ++TypeIdx) {
3005 T = NestedTypes[TypeIdx];
3006
3007 // Whether we expect a 'template<>' header.
3008 bool NeedEmptyTemplateHeader = false;
3009
3010 // Whether we expect a template header with parameters.
3011 bool NeedNonemptyTemplateHeader = false;
3012
3013 // For a dependent type, the set of template parameters that we
3014 // expect to see.
3015 TemplateParameterList *ExpectedTemplateParams = nullptr;
3016
3017 // C++0x [temp.expl.spec]p15:
3018 // A member or a member template may be nested within many enclosing
3019 // class templates. In an explicit specialization for such a member, the
3020 // member declaration shall be preceded by a template<> for each
3021 // enclosing class template that is explicitly specialized.
3022 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3024 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3025 ExpectedTemplateParams = Partial->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 } else if (Record->isDependentType()) {
3028 if (Record->getDescribedClassTemplate()) {
3029 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3030 ->getTemplateParameters();
3031 NeedNonemptyTemplateHeader = true;
3032 }
3033 } else if (ClassTemplateSpecializationDecl *Spec
3034 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3035 // C++0x [temp.expl.spec]p4:
3036 // Members of an explicitly specialized class template are defined
3037 // in the same manner as members of normal classes, and not using
3038 // the template<> syntax.
3039 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3040 NeedEmptyTemplateHeader = true;
3041 else
3042 continue;
3043 } else if (Record->getTemplateSpecializationKind()) {
3044 if (Record->getTemplateSpecializationKind()
3046 TypeIdx == NumTypes - 1)
3047 IsMemberSpecialization = true;
3048
3049 continue;
3050 }
3051 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3052 TemplateName Name = TST->getTemplateName();
3053 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3054 ExpectedTemplateParams = Template->getTemplateParameters();
3055 NeedNonemptyTemplateHeader = true;
3056 } else if (Name.getAsDeducedTemplateName()) {
3057 // FIXME: We actually could/should check the template arguments here
3058 // against the corresponding template parameter list.
3059 NeedNonemptyTemplateHeader = false;
3060 }
3061 }
3062
3063 // C++ [temp.expl.spec]p16:
3064 // In an explicit specialization declaration for a member of a class
3065 // template or a member template that appears in namespace scope, the
3066 // member template and some of its enclosing class templates may remain
3067 // unspecialized, except that the declaration shall not explicitly
3068 // specialize a class member template if its enclosing class templates
3069 // are not explicitly specialized as well.
3070 if (ParamIdx < ParamLists.size()) {
3071 if (ParamLists[ParamIdx]->size() == 0) {
3072 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3073 false))
3074 return nullptr;
3075 } else
3076 SawNonEmptyTemplateParameterList = true;
3077 }
3078
3079 if (NeedEmptyTemplateHeader) {
3080 // If we're on the last of the types, and we need a 'template<>' header
3081 // here, then it's a member specialization.
3082 if (TypeIdx == NumTypes - 1)
3083 IsMemberSpecialization = true;
3084
3085 if (ParamIdx < ParamLists.size()) {
3086 if (ParamLists[ParamIdx]->size() > 0) {
3087 // The header has template parameters when it shouldn't. Complain.
3088 if (!SuppressDiagnostic)
3089 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3090 diag::err_template_param_list_matches_nontemplate)
3091 << T
3092 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3093 ParamLists[ParamIdx]->getRAngleLoc())
3095 Invalid = true;
3096 return nullptr;
3097 }
3098
3099 // Consume this template header.
3100 ++ParamIdx;
3101 continue;
3102 }
3103
3104 if (!IsFriend)
3105 if (DiagnoseMissingExplicitSpecialization(
3107 return nullptr;
3108
3109 continue;
3110 }
3111
3112 if (NeedNonemptyTemplateHeader) {
3113 // In friend declarations we can have template-ids which don't
3114 // depend on the corresponding template parameter lists. But
3115 // assume that empty parameter lists are supposed to match this
3116 // template-id.
3117 if (IsFriend && T->isDependentType()) {
3118 if (ParamIdx < ParamLists.size() &&
3120 ExpectedTemplateParams = nullptr;
3121 else
3122 continue;
3123 }
3124
3125 if (ParamIdx < ParamLists.size()) {
3126 // Check the template parameter list, if we can.
3127 if (ExpectedTemplateParams &&
3129 ExpectedTemplateParams,
3130 !SuppressDiagnostic, TPL_TemplateMatch))
3131 Invalid = true;
3132
3133 if (!Invalid &&
3134 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3136 Invalid = true;
3137
3138 ++ParamIdx;
3139 continue;
3140 }
3141
3142 if (!SuppressDiagnostic)
3143 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3144 << T
3146 Invalid = true;
3147 continue;
3148 }
3149 }
3150
3151 // If there were at least as many template-ids as there were template
3152 // parameter lists, then there are no template parameter lists remaining for
3153 // the declaration itself.
3154 if (ParamIdx >= ParamLists.size()) {
3155 if (TemplateId && !IsFriend) {
3156 // We don't have a template header for the declaration itself, but we
3157 // should.
3158 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3159 TemplateId->RAngleLoc));
3160
3161 // Fabricate an empty template parameter list for the invented header.
3163 SourceLocation(), {},
3164 SourceLocation(), nullptr);
3165 }
3166
3167 return nullptr;
3168 }
3169
3170 // If there were too many template parameter lists, complain about that now.
3171 if (ParamIdx < ParamLists.size() - 1) {
3172 bool HasAnyExplicitSpecHeader = false;
3173 bool AllExplicitSpecHeaders = true;
3174 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3175 if (ParamLists[I]->size() == 0)
3176 HasAnyExplicitSpecHeader = true;
3177 else
3178 AllExplicitSpecHeaders = false;
3179 }
3180
3181 if (!SuppressDiagnostic)
3182 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3183 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3184 : diag::err_template_spec_extra_headers)
3185 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3186 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3187
3188 // If there was a specialization somewhere, such that 'template<>' is
3189 // not required, and there were any 'template<>' headers, note where the
3190 // specialization occurred.
3191 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3192 !SuppressDiagnostic)
3193 Diag(ExplicitSpecLoc,
3194 diag::note_explicit_template_spec_does_not_need_header)
3195 << NestedTypes.back();
3196
3197 // We have a template parameter list with no corresponding scope, which
3198 // means that the resulting template declaration can't be instantiated
3199 // properly (we'll end up with dependent nodes when we shouldn't).
3200 if (!AllExplicitSpecHeaders)
3201 Invalid = true;
3202 }
3203
3204 // C++ [temp.expl.spec]p16:
3205 // In an explicit specialization declaration for a member of a class
3206 // template or a member template that ap- pears in namespace scope, the
3207 // member template and some of its enclosing class templates may remain
3208 // unspecialized, except that the declaration shall not explicitly
3209 // specialize a class member template if its en- closing class templates
3210 // are not explicitly specialized as well.
3211 if (ParamLists.back()->size() == 0 &&
3212 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3213 false))
3214 return nullptr;
3215
3216 // Return the last template parameter list, which corresponds to the
3217 // entity being declared.
3218 return ParamLists.back();
3219}
3220
3222 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3223 Diag(Template->getLocation(), diag::note_template_declared_here)
3225 ? 0
3227 ? 1
3229 ? 2
3231 << Template->getDeclName();
3232 return;
3233 }
3234
3236 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3237 IEnd = OST->end();
3238 I != IEnd; ++I)
3239 Diag((*I)->getLocation(), diag::note_template_declared_here)
3240 << 0 << (*I)->getDeclName();
3241
3242 return;
3243 }
3244}
3245
3247 TemplateName BaseTemplate,
3248 SourceLocation TemplateLoc,
3250 auto lookUpCommonType = [&](TemplateArgument T1,
3251 TemplateArgument T2) -> QualType {
3252 // Don't bother looking for other specializations if both types are
3253 // builtins - users aren't allowed to specialize for them
3254 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3255 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3256 {T1, T2});
3257
3261 Args.addArgument(TemplateArgumentLoc(
3262 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3263
3264 EnterExpressionEvaluationContext UnevaluatedContext(
3266 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3268
3269 QualType BaseTemplateInst = S.CheckTemplateIdType(
3270 Keyword, BaseTemplate, TemplateLoc, Args,
3271 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3272
3273 if (SFINAE.hasErrorOccurred())
3274 return QualType();
3275
3276 return BaseTemplateInst;
3277 };
3278
3279 // Note A: For the common_type trait applied to a template parameter pack T of
3280 // types, the member type shall be either defined or not present as follows:
3281 switch (Ts.size()) {
3282
3283 // If sizeof...(T) is zero, there shall be no member type.
3284 case 0:
3285 return QualType();
3286
3287 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3288 // pack T. The member typedef-name type shall denote the same type, if any, as
3289 // common_type_t<T0, T0>; otherwise there shall be no member type.
3290 case 1:
3291 return lookUpCommonType(Ts[0], Ts[0]);
3292
3293 // If sizeof...(T) is two, let the first and second types constituting T be
3294 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3295 // as decay_t<T1> and decay_t<T2>, respectively.
3296 case 2: {
3297 QualType T1 = Ts[0].getAsType();
3298 QualType T2 = Ts[1].getAsType();
3299 QualType D1 = S.BuiltinDecay(T1, {});
3300 QualType D2 = S.BuiltinDecay(T2, {});
3301
3302 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3303 // the same type, if any, as common_type_t<D1, D2>.
3304 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3305 return lookUpCommonType(D1, D2);
3306
3307 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3308 // denotes a valid type, let C denote that type.
3309 {
3310 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3311 EnterExpressionEvaluationContext UnevaluatedContext(
3313 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3315
3316 // false
3318 VK_PRValue);
3319 ExprResult Cond = &CondExpr;
3320
3321 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3322 if (ConstRefQual) {
3323 D1.addConst();
3324 D2.addConst();
3325 }
3326
3327 // declval<D1>()
3328 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3329 ExprResult LHS = &LHSExpr;
3330
3331 // declval<D2>()
3332 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3333 ExprResult RHS = &RHSExpr;
3334
3337
3338 // decltype(false ? declval<D1>() : declval<D2>())
3340 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3341
3342 if (Result.isNull() || SFINAE.hasErrorOccurred())
3343 return QualType();
3344
3345 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3346 return S.BuiltinDecay(Result, TemplateLoc);
3347 };
3348
3349 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3350 return Res;
3351
3352 // Let:
3353 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3354 // COND-RES(X, Y) be
3355 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3356
3357 // C++20 only
3358 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3359 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3360 if (!S.Context.getLangOpts().CPlusPlus20)
3361 return QualType();
3362 return CheckConditionalOperands(true);
3363 }
3364 }
3365
3366 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3367 // denote the first, second, and (pack of) remaining types constituting T. Let
3368 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3369 // a type C, the member typedef-name type shall denote the same type, if any,
3370 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3371 default: {
3372 QualType Result = Ts.front().getAsType();
3373 for (auto T : llvm::drop_begin(Ts)) {
3374 Result = lookUpCommonType(Result, T.getAsType());
3375 if (Result.isNull())
3376 return QualType();
3377 }
3378 return Result;
3379 }
3380 }
3381}
3382
3383static bool isInVkNamespace(const RecordType *RT) {
3384 DeclContext *DC = RT->getDecl()->getDeclContext();
3385 if (!DC)
3386 return false;
3387
3388 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3389 if (!ND)
3390 return false;
3391
3392 return ND->getQualifiedNameAsString() == "hlsl::vk";
3393}
3394
3395static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3396 QualType OperandArg,
3397 SourceLocation Loc) {
3398 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3399 bool Literal = false;
3400 SourceLocation LiteralLoc;
3401 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3402 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3403 assert(SpecDecl);
3404
3405 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3406 QualType ConstantType = LiteralArgs[0].getAsType();
3407 RT = ConstantType->getAsCanonical<RecordType>();
3408 Literal = true;
3409 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3410 }
3411
3412 if (RT && isInVkNamespace(RT) &&
3413 RT->getDecl()->getName() == "integral_constant") {
3414 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3415 assert(SpecDecl);
3416
3417 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3418
3419 QualType ConstantType = ConstantArgs[0].getAsType();
3420 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3421
3422 if (Literal)
3423 return SpirvOperand::createLiteral(Value);
3424 return SpirvOperand::createConstant(ConstantType, Value);
3425 } else if (Literal) {
3426 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3427 return SpirvOperand();
3428 }
3429 }
3430 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3431 diag::err_call_incomplete_argument))
3432 return SpirvOperand();
3433 return SpirvOperand::createType(OperandArg);
3434}
3435
3438 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3439 TemplateArgumentListInfo &TemplateArgs) {
3440 ASTContext &Context = SemaRef.getASTContext();
3441
3442 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3443 "Builtin template arguments do not match its parameters");
3444
3445 switch (BTD->getBuiltinTemplateKind()) {
3446 case BTK__make_integer_seq: {
3447 // Specializations of __make_integer_seq<S, T, N> are treated like
3448 // S<T, 0, ..., N-1>.
3449
3450 QualType OrigType = Converted[1].getAsType();
3451 // C++14 [inteseq.intseq]p1:
3452 // T shall be an integer type.
3453 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3454 SemaRef.Diag(TemplateArgs[1].getLocation(),
3455 diag::err_integer_sequence_integral_element_type);
3456 return QualType();
3457 }
3458
3459 TemplateArgument NumArgsArg = Converted[2];
3460 if (NumArgsArg.isDependent())
3461 return QualType();
3462
3463 TemplateArgumentListInfo SyntheticTemplateArgs;
3464 // The type argument, wrapped in substitution sugar, gets reused as the
3465 // first template argument in the synthetic template argument list.
3466 SyntheticTemplateArgs.addArgument(
3469 OrigType, TemplateArgs[1].getLocation())));
3470
3471 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3472 // Expand N into 0 ... N-1.
3473 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3474 I < NumArgs; ++I) {
3475 TemplateArgument TA(Context, I, OrigType);
3476 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3477 TA, OrigType, TemplateArgs[2].getLocation()));
3478 }
3479 } else {
3480 // C++14 [inteseq.make]p1:
3481 // If N is negative the program is ill-formed.
3482 SemaRef.Diag(TemplateArgs[2].getLocation(),
3483 diag::err_integer_sequence_negative_length);
3484 return QualType();
3485 }
3486
3487 // The first template argument will be reused as the template decl that
3488 // our synthetic template arguments will be applied to.
3489 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3490 TemplateLoc, SyntheticTemplateArgs,
3491 /*Scope=*/nullptr,
3492 /*ForNestedNameSpecifier=*/false);
3493 }
3494
3495 case BTK__type_pack_element: {
3496 // Specializations of
3497 // __type_pack_element<Index, T_1, ..., T_N>
3498 // are treated like T_Index.
3499 assert(Converted.size() == 2 &&
3500 "__type_pack_element should be given an index and a parameter pack");
3501
3502 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3503 if (IndexArg.isDependent() || Ts.isDependent())
3504 return QualType();
3505
3506 llvm::APSInt Index = IndexArg.getAsIntegral();
3507 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3508 "type std::size_t, and hence be non-negative");
3509 // If the Index is out of bounds, the program is ill-formed.
3510 if (Index >= Ts.pack_size()) {
3511 SemaRef.Diag(TemplateArgs[0].getLocation(),
3512 diag::err_type_pack_element_out_of_bounds);
3513 return QualType();
3514 }
3515
3516 // We simply return the type at index `Index`.
3517 int64_t N = Index.getExtValue();
3518 return Ts.getPackAsArray()[N].getAsType();
3519 }
3520
3521 case BTK__builtin_common_type: {
3522 assert(Converted.size() == 4);
3523 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3524 return QualType();
3525
3526 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3527 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3528 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3529 TemplateLoc, Ts);
3530 !CT.isNull()) {
3534 CT, TemplateArgs[1].getLocation())));
3535 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3536 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3537 TAs, /*Scope=*/nullptr,
3538 /*ForNestedNameSpecifier=*/false);
3539 }
3540 QualType HasNoTypeMember = Converted[2].getAsType();
3541 return HasNoTypeMember;
3542 }
3543
3544 case BTK__hlsl_spirv_type: {
3545 assert(Converted.size() == 4);
3546
3547 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3548 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3549 }
3550
3551 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3552 return QualType();
3553
3554 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3555 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3556 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3557
3558 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3559
3561
3562 for (auto &OperandTA : OperandArgs) {
3563 QualType OperandArg = OperandTA.getAsType();
3564 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3565 TemplateArgs[3].getLocation());
3566 if (!Operand.isValid())
3567 return QualType();
3568 Operands.push_back(Operand);
3569 }
3570
3571 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3572 }
3573 case BTK__builtin_dedup_pack: {
3574 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3575 "a parameter pack");
3576 TemplateArgument Ts = Converted[0];
3577 // Delay the computation until we can compute the final result. We choose
3578 // not to remove the duplicates upfront before substitution to keep the code
3579 // simple.
3580 if (Ts.isDependent())
3581 return QualType();
3582 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3584 llvm::SmallDenseSet<QualType> Seen;
3585 // Synthesize a new template argument list, removing duplicates.
3586 for (auto T : Ts.getPackAsArray()) {
3587 assert(T.getKind() == clang::TemplateArgument::Type);
3588 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3589 continue;
3590 OutArgs.push_back(T);
3591 }
3592 return Context.getSubstBuiltinTemplatePack(
3593 TemplateArgument::CreatePackCopy(Context, OutArgs));
3594 }
3595 }
3596 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3597}
3598
3599/// Determine whether this alias template is "enable_if_t".
3600/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3602 return AliasTemplate->getName() == "enable_if_t" ||
3603 AliasTemplate->getName() == "__enable_if_t";
3604}
3605
3606/// Collect all of the separable terms in the given condition, which
3607/// might be a conjunction.
3608///
3609/// FIXME: The right answer is to convert the logical expression into
3610/// disjunctive normal form, so we can find the first failed term
3611/// within each possible clause.
3612static void collectConjunctionTerms(Expr *Clause,
3613 SmallVectorImpl<Expr *> &Terms) {
3614 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3615 if (BinOp->getOpcode() == BO_LAnd) {
3616 collectConjunctionTerms(BinOp->getLHS(), Terms);
3617 collectConjunctionTerms(BinOp->getRHS(), Terms);
3618 return;
3619 }
3620 }
3621
3622 Terms.push_back(Clause);
3623}
3624
3625// The ranges-v3 library uses an odd pattern of a top-level "||" with
3626// a left-hand side that is value-dependent but never true. Identify
3627// the idiom and ignore that term.
3629 // Top-level '||'.
3630 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3631 if (!BinOp) return Cond;
3632
3633 if (BinOp->getOpcode() != BO_LOr) return Cond;
3634
3635 // With an inner '==' that has a literal on the right-hand side.
3636 Expr *LHS = BinOp->getLHS();
3637 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3638 if (!InnerBinOp) return Cond;
3639
3640 if (InnerBinOp->getOpcode() != BO_EQ ||
3641 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3642 return Cond;
3643
3644 // If the inner binary operation came from a macro expansion named
3645 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3646 // of the '||', which is the real, user-provided condition.
3647 SourceLocation Loc = InnerBinOp->getExprLoc();
3648 if (!Loc.isMacroID()) return Cond;
3649
3650 StringRef MacroName = PP.getImmediateMacroName(Loc);
3651 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3652 return BinOp->getRHS();
3653
3654 return Cond;
3655}
3656
3657namespace {
3658
3659// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3660// within failing boolean expression, such as substituting template parameters
3661// for actual types.
3662class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3663public:
3664 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3665 : Policy(P) {}
3666
3667 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3668 const auto *DR = dyn_cast<DeclRefExpr>(E);
3669 if (DR && DR->getQualifier()) {
3670 // If this is a qualified name, expand the template arguments in nested
3671 // qualifiers.
3672 DR->getQualifier().print(OS, Policy, true);
3673 // Then print the decl itself.
3674 const ValueDecl *VD = DR->getDecl();
3675 OS << *VD;
3676 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3677 // This is a template variable, print the expanded template arguments.
3678 printTemplateArgumentList(
3679 OS, IV->getTemplateArgs().asArray(), Policy,
3680 IV->getSpecializedTemplate()->getTemplateParameters());
3681 }
3682 return true;
3683 }
3684 return false;
3685 }
3686
3687private:
3688 const PrintingPolicy Policy;
3689};
3690
3691} // end anonymous namespace
3692
3693std::pair<Expr *, std::string>
3696
3697 // Separate out all of the terms in a conjunction.
3700
3701 // Determine which term failed.
3702 Expr *FailedCond = nullptr;
3703 for (Expr *Term : Terms) {
3704 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3705
3706 // Literals are uninteresting.
3707 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3708 isa<IntegerLiteral>(TermAsWritten))
3709 continue;
3710
3711 // The initialization of the parameter from the argument is
3712 // a constant-evaluated context.
3715
3716 bool Succeeded;
3717 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3718 !Succeeded) {
3719 FailedCond = TermAsWritten;
3720 break;
3721 }
3722 }
3723 if (!FailedCond)
3724 FailedCond = Cond->IgnoreParenImpCasts();
3725
3726 std::string Description;
3727 {
3728 llvm::raw_string_ostream Out(Description);
3730 Policy.PrintAsCanonical = true;
3731 FailedBooleanConditionPrinterHelper Helper(Policy);
3732 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3733 }
3734 return { FailedCond, Description };
3735}
3736
3737static TemplateName
3739 const AssumedTemplateStorage *ATN,
3740 SourceLocation NameLoc) {
3741 // We assumed this undeclared identifier to be an (ADL-only) function
3742 // template name, but it was used in a context where a type was required.
3743 // Try to typo-correct it now.
3744 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3745 struct CandidateCallback : CorrectionCandidateCallback {
3746 bool ValidateCandidate(const TypoCorrection &TC) override {
3747 return TC.getCorrectionDecl() &&
3749 }
3750 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3751 return std::make_unique<CandidateCallback>(*this);
3752 }
3753 } FilterCCC;
3754
3755 TypoCorrection Corrected =
3756 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3757 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3758 if (Corrected && Corrected.getFoundDecl()) {
3759 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3760 << ATN->getDeclName());
3762 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3764 }
3765
3766 return TemplateName();
3767}
3768
3770 TemplateName Name,
3771 SourceLocation TemplateLoc,
3772 TemplateArgumentListInfo &TemplateArgs,
3773 Scope *Scope, bool ForNestedNameSpecifier) {
3774 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3775
3776 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3777 if (!Template) {
3778 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3779 Template = S->getParameterPack();
3780 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3781 if (DTN->getName().getIdentifier())
3782 // When building a template-id where the template-name is dependent,
3783 // assume the template is a type template. Either our assumption is
3784 // correct, or the code is ill-formed and will be diagnosed when the
3785 // dependent name is substituted.
3786 return Context.getTemplateSpecializationType(Keyword, Name,
3787 TemplateArgs.arguments(),
3788 /*CanonicalArgs=*/{});
3789 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3791 *this, Scope, ATN, TemplateLoc);
3792 CorrectedName.isNull()) {
3793 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3794 return QualType();
3795 } else {
3796 Name = CorrectedName;
3797 Template = Name.getAsTemplateDecl();
3798 }
3799 }
3800 }
3801 if (!Template ||
3803 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3804 if (ForNestedNameSpecifier)
3805 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3806 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3807 else
3808 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3810 return QualType();
3811 }
3812
3813 // Check that the template argument list is well-formed for this
3814 // template.
3816 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3817 DefaultArgs, /*PartialTemplateArgs=*/false,
3818 CTAI,
3819 /*UpdateArgsWithConversions=*/true))
3820 return QualType();
3821
3822 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3823 // and there are no diagnsotics currently implemented for TemplateDecls,
3824 // so avoid doing it for now.
3825 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3826
3827 QualType CanonType;
3828
3830 // We might have a substituted template template parameter pack. If so,
3831 // build a template specialization type for it.
3833 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3834
3835 // C++0x [dcl.type.elab]p2:
3836 // If the identifier resolves to a typedef-name or the simple-template-id
3837 // resolves to an alias template specialization, the
3838 // elaborated-type-specifier is ill-formed.
3841 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3844 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3845 }
3846
3847 // Find the canonical type for this type alias template specialization.
3848 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3849
3850 // Diagnose uses of the pattern of this template.
3851 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3852 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3853
3854 if (Pattern->isInvalidDecl())
3855 return QualType();
3856
3857 // Only substitute for the innermost template argument list.
3858 MultiLevelTemplateArgumentList TemplateArgLists;
3860 /*Final=*/true);
3861 TemplateArgLists.addOuterRetainedLevels(
3862 AliasTemplate->getTemplateParameters()->getDepth());
3863
3865
3866 // FIXME: The TemplateArgs passed here are not used for the context note,
3867 // nor they should, because this note will be pointing to the specialization
3868 // anyway. These arguments are needed for a hack for instantiating lambdas
3869 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3870 // arguments will be used for collating the template arguments needed to
3871 // instantiate the lambda.
3872 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3873 /*Entity=*/AliasTemplate,
3874 /*TemplateArgs=*/CTAI.SugaredConverted);
3875 if (Inst.isInvalid())
3876 return QualType();
3877
3878 std::optional<ContextRAII> SavedContext;
3879 if (!AliasTemplate->getDeclContext()->isFileContext())
3880 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3881
3882 CanonType =
3883 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3884 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3885 if (CanonType.isNull()) {
3886 // If this was enable_if and we failed to find the nested type
3887 // within enable_if in a SFINAE context, dig out the specific
3888 // enable_if condition that failed and present that instead.
3890 if (SFINAETrap *Trap = getSFINAEContext();
3891 TemplateDeductionInfo *DeductionInfo =
3892 Trap ? Trap->getDeductionInfo() : nullptr) {
3893 if (DeductionInfo->hasSFINAEDiagnostic() &&
3894 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3895 diag::err_typename_nested_not_found_enable_if &&
3896 TemplateArgs[0].getArgument().getKind() ==
3898 Expr *FailedCond;
3899 std::string FailedDescription;
3900 std::tie(FailedCond, FailedDescription) =
3901 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3902
3903 // Remove the old SFINAE diagnostic.
3904 PartialDiagnosticAt OldDiag =
3906 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3907
3908 // Add a new SFINAE diagnostic specifying which condition
3909 // failed.
3910 DeductionInfo->addSFINAEDiagnostic(
3911 OldDiag.first,
3912 PDiag(diag::err_typename_nested_not_found_requirement)
3913 << FailedDescription << FailedCond->getSourceRange());
3914 }
3915 }
3916 }
3917
3918 return QualType();
3919 }
3920 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3921 CanonType = checkBuiltinTemplateIdType(
3922 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3923 } else if (Name.isDependent() ||
3924 TemplateSpecializationType::anyDependentTemplateArguments(
3925 TemplateArgs, CTAI.CanonicalConverted)) {
3926 // This class template specialization is a dependent
3927 // type. Therefore, its canonical type is another class template
3928 // specialization type that contains all of the converted
3929 // arguments in canonical form. This ensures that, e.g., A<T> and
3930 // A<T, T> have identical types when A is declared as:
3931 //
3932 // template<typename T, typename U = T> struct A;
3933 CanonType = Context.getCanonicalTemplateSpecializationType(
3935 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3936 CTAI.CanonicalConverted);
3937 assert(CanonType->isCanonicalUnqualified());
3938
3939 // This might work out to be a current instantiation, in which
3940 // case the canonical type needs to be the InjectedClassNameType.
3941 //
3942 // TODO: in theory this could be a simple hashtable lookup; most
3943 // changes to CurContext don't change the set of current
3944 // instantiations.
3946 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3947 // If we get out to a namespace, we're done.
3948 if (Ctx->isFileContext()) break;
3949
3950 // If this isn't a record, keep looking.
3951 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3952 if (!Record) continue;
3953
3954 // Look for one of the two cases with InjectedClassNameTypes
3955 // and check whether it's the same template.
3957 !Record->getDescribedClassTemplate())
3958 continue;
3959
3960 // Fetch the injected class name type and check whether its
3961 // injected type is equal to the type we just built.
3962 CanQualType ICNT = Context.getCanonicalTagType(Record);
3963 CanQualType Injected =
3964 Record->getCanonicalTemplateSpecializationType(Context);
3965
3966 if (CanonType != Injected)
3967 continue;
3968
3969 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
3970 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
3971
3972 // If so, the canonical type of this TST is the injected
3973 // class name type of the record we just found.
3974 CanonType = ICNT;
3975 break;
3976 }
3977 }
3978 } else if (ClassTemplateDecl *ClassTemplate =
3979 dyn_cast<ClassTemplateDecl>(Template)) {
3980 // Find the class template specialization declaration that
3981 // corresponds to these arguments.
3982 void *InsertPos = nullptr;
3984 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3985 if (!Decl) {
3986 // This is the first time we have referenced this class template
3987 // specialization. Create the canonical declaration and add it to
3988 // the set of specializations.
3990 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3991 ClassTemplate->getDeclContext(),
3992 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3993 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3994 CTAI.StrictPackMatch, nullptr);
3995 ClassTemplate->AddSpecialization(Decl, InsertPos);
3996 if (ClassTemplate->isOutOfLine())
3997 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3998 }
3999
4000 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4001 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4002 NonSFINAEContext _(*this);
4003 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4004 if (!Inst.isInvalid()) {
4006 CTAI.CanonicalConverted,
4007 /*Final=*/false);
4008 InstantiateAttrsForDecl(TemplateArgLists,
4009 ClassTemplate->getTemplatedDecl(), Decl);
4010 }
4011 }
4012
4013 // Diagnose uses of this specialization.
4014 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4015 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4016
4017 CanonType = Context.getCanonicalTagType(Decl);
4018 assert(isa<RecordType>(CanonType) &&
4019 "type of non-dependent specialization is not a RecordType");
4020 } else {
4021 llvm_unreachable("Unhandled template kind");
4022 }
4023
4024 // Build the fully-sugared type for this class template
4025 // specialization, which refers back to the class template
4026 // specialization we created or found.
4027 return Context.getTemplateSpecializationType(
4028 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4029 CanonType);
4030}
4031
4033 TemplateNameKind &TNK,
4034 SourceLocation NameLoc,
4035 IdentifierInfo *&II) {
4036 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4037
4038 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4039 assert(ATN && "not an assumed template name");
4040 II = ATN->getDeclName().getAsIdentifierInfo();
4041
4042 if (TemplateName Name =
4043 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4044 !Name.isNull()) {
4045 // Resolved to a type template name.
4046 ParsedName = TemplateTy::make(Name);
4047 TNK = TNK_Type_template;
4048 }
4049}
4050
4052 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4053 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4054 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4055 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4056 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4057 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4058 ImplicitTypenameContext AllowImplicitTypename) {
4059 if (SS.isInvalid())
4060 return true;
4061
4062 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4063 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4064
4065 // C++ [temp.res]p3:
4066 // A qualified-id that refers to a type and in which the
4067 // nested-name-specifier depends on a template-parameter (14.6.2)
4068 // shall be prefixed by the keyword typename to indicate that the
4069 // qualified-id denotes a type, forming an
4070 // elaborated-type-specifier (7.1.5.3).
4071 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4072 // C++2a relaxes some of those restrictions in [temp.res]p5.
4073 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4074 SS.getScopeRep(), TemplateII);
4076 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4077 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4078 << NNS;
4079 if (!getLangOpts().CPlusPlus20)
4080 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4081 } else
4082 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4083
4084 // FIXME: This is not quite correct recovery as we don't transform SS
4085 // into the corresponding dependent form (and we don't diagnose missing
4086 // 'template' keywords within SS as a result).
4087 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4088 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4089 TemplateArgsIn, RAngleLoc);
4090 }
4091
4092 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4093 // it's not actually allowed to be used as a type in most cases. Because
4094 // we annotate it before we know whether it's valid, we have to check for
4095 // this case here.
4096 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4097 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4098 Diag(TemplateIILoc,
4099 TemplateKWLoc.isInvalid()
4100 ? diag::err_out_of_line_qualified_id_type_names_constructor
4101 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4102 << TemplateII << 0 /*injected-class-name used as template name*/
4103 << 1 /*if any keyword was present, it was 'template'*/;
4104 }
4105 }
4106
4107 // Translate the parser's template argument list in our AST format.
4108 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4109 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4110
4112 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4113 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4114 if (SpecTy.isNull())
4115 return true;
4116
4117 // Build type-source information.
4118 TypeLocBuilder TLB;
4119 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4120 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4121 TemplateIILoc, TemplateArgs);
4122 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4123}
4124
4126 TypeSpecifierType TagSpec,
4127 SourceLocation TagLoc,
4128 CXXScopeSpec &SS,
4129 SourceLocation TemplateKWLoc,
4130 TemplateTy TemplateD,
4131 SourceLocation TemplateLoc,
4132 SourceLocation LAngleLoc,
4133 ASTTemplateArgsPtr TemplateArgsIn,
4134 SourceLocation RAngleLoc) {
4135 if (SS.isInvalid())
4136 return TypeResult(true);
4137
4138 // Translate the parser's template argument list in our AST format.
4139 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4140 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4141
4142 // Determine the tag kind
4146
4148 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4149 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4150 if (Result.isNull())
4151 return TypeResult(true);
4152
4153 // Check the tag kind
4154 if (const RecordType *RT = Result->getAs<RecordType>()) {
4155 RecordDecl *D = RT->getDecl();
4156
4157 IdentifierInfo *Id = D->getIdentifier();
4158 assert(Id && "templated class must have an identifier");
4159
4161 TagLoc, Id)) {
4162 Diag(TagLoc, diag::err_use_with_wrong_tag)
4163 << Result
4165 Diag(D->getLocation(), diag::note_previous_use);
4166 }
4167 }
4168
4169 // Provide source-location information for the template specialization.
4170 TypeLocBuilder TLB;
4172 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4173 TemplateArgs);
4175}
4176
4177static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4178 NamedDecl *PrevDecl,
4179 SourceLocation Loc,
4181
4183
4185 unsigned Depth,
4186 unsigned Index) {
4187 switch (Arg.getKind()) {
4195 return false;
4196
4198 QualType Type = Arg.getAsType();
4199 const TemplateTypeParmType *TPT =
4200 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4201 return TPT && !Type.hasQualifiers() &&
4202 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4203 }
4204
4206 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4207 if (!DRE || !DRE->getDecl())
4208 return false;
4209 const NonTypeTemplateParmDecl *NTTP =
4210 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4211 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4212 }
4213
4215 const TemplateTemplateParmDecl *TTP =
4216 dyn_cast_or_null<TemplateTemplateParmDecl>(
4218 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4219 }
4220 llvm_unreachable("unexpected kind of template argument");
4221}
4222
4224 TemplateParameterList *SpecParams,
4226 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4227 return false;
4228
4229 unsigned Depth = Params->getDepth();
4230
4231 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4232 TemplateArgument Arg = Args[I];
4233
4234 // If the parameter is a pack expansion, the argument must be a pack
4235 // whose only element is a pack expansion.
4236 if (Params->getParam(I)->isParameterPack()) {
4237 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4238 !Arg.pack_begin()->isPackExpansion())
4239 return false;
4240 Arg = Arg.pack_begin()->getPackExpansionPattern();
4241 }
4242
4243 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4244 return false;
4245
4246 // For NTTPs further specialization is allowed via deduced types, so
4247 // we need to make sure to only reject here if primary template and
4248 // specialization use the same type for the NTTP.
4249 if (auto *SpecNTTP =
4250 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4251 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4252 if (!NTTP || NTTP->getType().getCanonicalType() !=
4253 SpecNTTP->getType().getCanonicalType())
4254 return false;
4255 }
4256 }
4257
4258 return true;
4259}
4260
4261template<typename PartialSpecDecl>
4262static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4263 if (Partial->getDeclContext()->isDependentContext())
4264 return;
4265
4266 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4267 // for non-substitution-failure issues?
4268 TemplateDeductionInfo Info(Partial->getLocation());
4269 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4270 return;
4271
4272 auto *Template = Partial->getSpecializedTemplate();
4273 S.Diag(Partial->getLocation(),
4274 diag::ext_partial_spec_not_more_specialized_than_primary)
4276
4277 if (Info.hasSFINAEDiagnostic()) {
4281 SmallString<128> SFINAEArgString;
4282 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4283 S.Diag(Diag.first,
4284 diag::note_partial_spec_not_more_specialized_than_primary)
4285 << SFINAEArgString;
4286 }
4287
4289 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4290 Template->getAssociatedConstraints(TemplateAC);
4291 Partial->getAssociatedConstraints(PartialAC);
4293 TemplateAC);
4294}
4295
4296static void
4298 const llvm::SmallBitVector &DeducibleParams) {
4299 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4300 if (!DeducibleParams[I]) {
4301 NamedDecl *Param = TemplateParams->getParam(I);
4302 if (Param->getDeclName())
4303 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4304 << Param->getDeclName();
4305 else
4306 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4307 << "(anonymous)";
4308 }
4309 }
4310}
4311
4312
4313template<typename PartialSpecDecl>
4315 PartialSpecDecl *Partial) {
4316 // C++1z [temp.class.spec]p8: (DR1495)
4317 // - The specialization shall be more specialized than the primary
4318 // template (14.5.5.2).
4320
4321 // C++ [temp.class.spec]p8: (DR1315)
4322 // - Each template-parameter shall appear at least once in the
4323 // template-id outside a non-deduced context.
4324 // C++1z [temp.class.spec.match]p3 (P0127R2)
4325 // If the template arguments of a partial specialization cannot be
4326 // deduced because of the structure of its template-parameter-list
4327 // and the template-id, the program is ill-formed.
4328 auto *TemplateParams = Partial->getTemplateParameters();
4329 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4330 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4331 TemplateParams->getDepth(), DeducibleParams);
4332
4333 if (!DeducibleParams.all()) {
4334 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4335 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4337 << (NumNonDeducible > 1)
4338 << SourceRange(Partial->getLocation(),
4339 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4340 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4341 }
4342}
4343
4348
4353
4355 // C++1z [temp.param]p11:
4356 // A template parameter of a deduction guide template that does not have a
4357 // default-argument shall be deducible from the parameter-type-list of the
4358 // deduction guide template.
4359 auto *TemplateParams = TD->getTemplateParameters();
4360 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4361 MarkDeducedTemplateParameters(TD, DeducibleParams);
4362 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4363 // A parameter pack is deducible (to an empty pack).
4364 auto *Param = TemplateParams->getParam(I);
4365 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4366 DeducibleParams[I] = true;
4367 }
4368
4369 if (!DeducibleParams.all()) {
4370 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4371 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4372 << (NumNonDeducible > 1);
4373 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4374 }
4375}
4376
4379 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4381 // D must be variable template id.
4383 "Variable template specialization is declared with a template id.");
4384
4385 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4386 TemplateArgumentListInfo TemplateArgs =
4387 makeTemplateArgumentListInfo(*this, *TemplateId);
4388 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4389 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4390 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4391
4392 TemplateName Name = TemplateId->Template.get();
4393
4394 // The template-id must name a variable template.
4396 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4397 if (!VarTemplate) {
4398 NamedDecl *FnTemplate;
4399 if (auto *OTS = Name.getAsOverloadedTemplate())
4400 FnTemplate = *OTS->begin();
4401 else
4402 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4403 if (FnTemplate)
4404 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4405 << FnTemplate->getDeclName();
4406 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4408 }
4409
4410 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4411 auto Message = DSA->getMessage();
4412 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4413 << VarTemplate << !Message.empty() << Message;
4414 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4415 }
4416
4417 // Check for unexpanded parameter packs in any of the template arguments.
4418 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4419 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4423 return true;
4424
4425 // Check that the template argument list is well-formed for this
4426 // template.
4428 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4429 /*DefaultArgs=*/{},
4430 /*PartialTemplateArgs=*/false, CTAI,
4431 /*UpdateArgsWithConversions=*/true))
4432 return true;
4433
4434 // Find the variable template (partial) specialization declaration that
4435 // corresponds to these arguments.
4438 TemplateArgs.size(),
4439 CTAI.CanonicalConverted))
4440 return true;
4441
4442 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4443 // we also do them during instantiation.
4444 if (!Name.isDependent() &&
4445 !TemplateSpecializationType::anyDependentTemplateArguments(
4446 TemplateArgs, CTAI.CanonicalConverted)) {
4447 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4448 << VarTemplate->getDeclName();
4450 }
4451
4452 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4453 TemplateParams, CTAI.CanonicalConverted) &&
4454 (!Context.getLangOpts().CPlusPlus20 ||
4455 !TemplateParams->hasAssociatedConstraints())) {
4456 // C++ [temp.class.spec]p9b3:
4457 //
4458 // -- The argument list of the specialization shall not be identical
4459 // to the implicit argument list of the primary template.
4460 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4461 << /*variable template*/ 1
4462 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4463 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4464 // FIXME: Recover from this by treating the declaration as a
4465 // redeclaration of the primary template.
4466 return true;
4467 }
4468 }
4469
4470 void *InsertPos = nullptr;
4471 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4472
4474 PrevDecl = VarTemplate->findPartialSpecialization(
4475 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4476 else
4477 PrevDecl =
4478 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4479
4481
4482 // Check whether we can declare a variable template specialization in
4483 // the current scope.
4484 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4485 TemplateNameLoc,
4487 return true;
4488
4489 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4490 // Since the only prior variable template specialization with these
4491 // arguments was referenced but not declared, reuse that
4492 // declaration node as our own, updating its source location and
4493 // the list of outer template parameters to reflect our new declaration.
4494 Specialization = PrevDecl;
4495 Specialization->setLocation(TemplateNameLoc);
4496 PrevDecl = nullptr;
4497 } else if (IsPartialSpecialization) {
4498 // Create a new class template partial specialization declaration node.
4500 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4503 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4504 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4505 SC, CTAI.CanonicalConverted);
4506 Partial->setTemplateArgsAsWritten(TemplateArgs);
4507
4508 if (!PrevPartial)
4509 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4510 Specialization = Partial;
4511
4513 } else {
4514 // Create a new class template specialization declaration node for
4515 // this explicit specialization or friend declaration.
4517 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4518 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4519 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4520
4521 if (!PrevDecl)
4522 VarTemplate->AddSpecialization(Specialization, InsertPos);
4523 }
4524
4525 // C++ [temp.expl.spec]p6:
4526 // If a template, a member template or the member of a class template is
4527 // explicitly specialized then that specialization shall be declared
4528 // before the first use of that specialization that would cause an implicit
4529 // instantiation to take place, in every translation unit in which such a
4530 // use occurs; no diagnostic is required.
4531 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4532 bool Okay = false;
4533 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4534 // Is there any previous explicit specialization declaration?
4536 Okay = true;
4537 break;
4538 }
4539 }
4540
4541 if (!Okay) {
4542 SourceRange Range(TemplateNameLoc, RAngleLoc);
4543 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4544 << Name << Range;
4545
4546 Diag(PrevDecl->getPointOfInstantiation(),
4547 diag::note_instantiation_required_here)
4548 << (PrevDecl->getTemplateSpecializationKind() !=
4550 return true;
4551 }
4552 }
4553
4554 Specialization->setLexicalDeclContext(CurContext);
4555
4556 // Add the specialization into its lexical context, so that it can
4557 // be seen when iterating through the list of declarations in that
4558 // context. However, specializations are not found by name lookup.
4559 CurContext->addDecl(Specialization);
4560
4561 // Note that this is an explicit specialization.
4562 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4563
4564 Previous.clear();
4565 if (PrevDecl)
4566 Previous.addDecl(PrevDecl);
4567 else if (Specialization->isStaticDataMember() &&
4568 Specialization->isOutOfLine())
4569 Specialization->setAccess(VarTemplate->getAccess());
4570
4571 return Specialization;
4572}
4573
4574namespace {
4575/// A partial specialization whose template arguments have matched
4576/// a given template-id.
4577struct PartialSpecMatchResult {
4580};
4581
4582// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4583// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4584static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4585 if (Var->getName() != "format_kind" ||
4586 !Var->getDeclContext()->isStdNamespace())
4587 return false;
4588
4589 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4590 // release in which users can access std::format_kind.
4591 // We can use 20250520 as the final date, see the following commits.
4592 // GCC releases/gcc-15 branch:
4593 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4594 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4595 // GCC master branch:
4596 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4597 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4598 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4599}
4600} // end anonymous namespace
4601
4604 SourceLocation TemplateNameLoc,
4605 const TemplateArgumentListInfo &TemplateArgs,
4606 bool SetWrittenArgs) {
4607 assert(Template && "A variable template id without template?");
4608
4609 // Check that the template argument list is well-formed for this template.
4612 Template, TemplateNameLoc,
4613 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4614 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4615 /*UpdateArgsWithConversions=*/true))
4616 return true;
4617
4618 // Produce a placeholder value if the specialization is dependent.
4619 if (Template->getDeclContext()->isDependentContext() ||
4620 TemplateSpecializationType::anyDependentTemplateArguments(
4621 TemplateArgs, CTAI.CanonicalConverted)) {
4622 if (ParsingInitForAutoVars.empty())
4623 return DeclResult();
4624
4625 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4626 const TemplateArgument &Arg2) {
4627 return Context.isSameTemplateArgument(Arg1, Arg2);
4628 };
4629
4630 if (VarDecl *Var = Template->getTemplatedDecl();
4631 ParsingInitForAutoVars.count(Var) &&
4632 // See comments on this function definition
4633 !IsLibstdcxxStdFormatKind(PP, Var) &&
4634 llvm::equal(
4635 CTAI.CanonicalConverted,
4636 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4637 IsSameTemplateArg)) {
4638 Diag(TemplateNameLoc,
4639 diag::err_auto_variable_cannot_appear_in_own_initializer)
4640 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4641 return true;
4642 }
4643
4645 Template->getPartialSpecializations(PartialSpecs);
4646 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4647 if (ParsingInitForAutoVars.count(Partial) &&
4648 llvm::equal(CTAI.CanonicalConverted,
4649 Partial->getTemplateArgs().asArray(),
4650 IsSameTemplateArg)) {
4651 Diag(TemplateNameLoc,
4652 diag::err_auto_variable_cannot_appear_in_own_initializer)
4653 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4654 << Partial->getType();
4655 return true;
4656 }
4657
4658 return DeclResult();
4659 }
4660
4661 // Find the variable template specialization declaration that
4662 // corresponds to these arguments.
4663 void *InsertPos = nullptr;
4665 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4666 checkSpecializationReachability(TemplateNameLoc, Spec);
4667 if (Spec->getType()->isUndeducedType()) {
4668 if (ParsingInitForAutoVars.count(Spec))
4669 Diag(TemplateNameLoc,
4670 diag::err_auto_variable_cannot_appear_in_own_initializer)
4671 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4672 << Spec->getType();
4673 else
4674 // We are substituting the initializer of this variable template
4675 // specialization.
4676 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4677 << Spec << Spec->getType();
4678
4679 return true;
4680 }
4681 // If we already have a variable template specialization, return it.
4682 return Spec;
4683 }
4684
4685 // This is the first time we have referenced this variable template
4686 // specialization. Create the canonical declaration and add it to
4687 // the set of specializations, based on the closest partial specialization
4688 // that it represents. That is,
4689 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4690 const TemplateArgumentList *PartialSpecArgs = nullptr;
4691 bool AmbiguousPartialSpec = false;
4692 typedef PartialSpecMatchResult MatchResult;
4694 SourceLocation PointOfInstantiation = TemplateNameLoc;
4695 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4696 /*ForTakingAddress=*/false);
4697
4698 // 1. Attempt to find the closest partial specialization that this
4699 // specializes, if any.
4700 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4701 // Perhaps better after unification of DeduceTemplateArguments() and
4702 // getMoreSpecializedPartialSpecialization().
4704 Template->getPartialSpecializations(PartialSpecs);
4705
4706 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4707 // C++ [temp.spec.partial.member]p2:
4708 // If the primary member template is explicitly specialized for a given
4709 // (implicit) specialization of the enclosing class template, the partial
4710 // specializations of the member template are ignored for this
4711 // specialization of the enclosing class template. If a partial
4712 // specialization of the member template is explicitly specialized for a
4713 // given (implicit) specialization of the enclosing class template, the
4714 // primary member template and its other partial specializations are still
4715 // considered for this specialization of the enclosing class template.
4716 if (Template->isMemberSpecialization() &&
4717 !Partial->isMemberSpecialization())
4718 continue;
4719
4720 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4721
4723 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4725 // Store the failed-deduction information for use in diagnostics, later.
4726 // TODO: Actually use the failed-deduction info?
4727 FailedCandidates.addCandidate().set(
4730 (void)Result;
4731 } else {
4732 Matched.push_back(PartialSpecMatchResult());
4733 Matched.back().Partial = Partial;
4734 Matched.back().Args = Info.takeSugared();
4735 }
4736 }
4737
4738 if (Matched.size() >= 1) {
4739 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4740 if (Matched.size() == 1) {
4741 // -- If exactly one matching specialization is found, the
4742 // instantiation is generated from that specialization.
4743 // We don't need to do anything for this.
4744 } else {
4745 // -- If more than one matching specialization is found, the
4746 // partial order rules (14.5.4.2) are used to determine
4747 // whether one of the specializations is more specialized
4748 // than the others. If none of the specializations is more
4749 // specialized than all of the other matching
4750 // specializations, then the use of the variable template is
4751 // ambiguous and the program is ill-formed.
4752 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4753 PEnd = Matched.end();
4754 P != PEnd; ++P) {
4755 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4756 PointOfInstantiation) ==
4757 P->Partial)
4758 Best = P;
4759 }
4760
4761 // Determine if the best partial specialization is more specialized than
4762 // the others.
4763 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4764 PEnd = Matched.end();
4765 P != PEnd; ++P) {
4767 P->Partial, Best->Partial,
4768 PointOfInstantiation) != Best->Partial) {
4769 AmbiguousPartialSpec = true;
4770 break;
4771 }
4772 }
4773 }
4774
4775 // Instantiate using the best variable template partial specialization.
4776 InstantiationPattern = Best->Partial;
4777 PartialSpecArgs = Best->Args;
4778 } else {
4779 // -- If no match is found, the instantiation is generated
4780 // from the primary template.
4781 // InstantiationPattern = Template->getTemplatedDecl();
4782 }
4783
4784 // 2. Create the canonical declaration.
4785 // Note that we do not instantiate a definition until we see an odr-use
4786 // in DoMarkVarDeclReferenced().
4787 // FIXME: LateAttrs et al.?
4788 if (AmbiguousPartialSpec) {
4789 // Partial ordering did not produce a clear winner. Complain.
4790 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4791 << Template;
4792 // Print the matching partial specializations.
4793 for (MatchResult P : Matched)
4794 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4795 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4796 *P.Args);
4797 return true;
4798 }
4799
4801 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4802 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4803 if (!Decl)
4804 return true;
4805 if (SetWrittenArgs)
4806 Decl->setTemplateArgsAsWritten(TemplateArgs);
4807
4809 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4810 Decl->setInstantiationOf(D, PartialSpecArgs);
4811
4812 checkSpecializationReachability(TemplateNameLoc, Decl);
4813
4814 assert(Decl && "No variable template specialization?");
4815 return Decl;
4816}
4817
4819 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4820 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4821 const TemplateArgumentListInfo *TemplateArgs) {
4822
4823 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4824 *TemplateArgs, /*SetWrittenArgs=*/false);
4825 if (Decl.isInvalid())
4826 return ExprError();
4827
4828 if (!Decl.get())
4829 return ExprResult();
4830
4831 VarDecl *Var = cast<VarDecl>(Decl.get());
4834 NameInfo.getLoc());
4835
4836 // Build an ordinary singleton decl ref.
4837 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4838}
4839
4841 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4843 const TemplateArgumentListInfo *TemplateArgs) {
4844 assert(Template && "A variable template id without template?");
4845
4846 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4847 Template->templateParameterKind() !=
4849 return ExprResult();
4850
4851 // Check that the template argument list is well-formed for this template.
4854 Template, TemplateLoc,
4855 // FIXME: TemplateArgs will not be modified because
4856 // UpdateArgsWithConversions is false, however, we should
4857 // CheckTemplateArgumentList to be const-correct.
4858 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4859 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4860 /*UpdateArgsWithConversions=*/false))
4861 return true;
4862
4864 R.addDecl(Template);
4865
4866 // FIXME: We model references to variable template and concept parameters
4867 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4868 // data, can generally be used in the same places and work the same way.
4869 // However, it might be cleaner to use a dedicated AST node in the long run.
4872 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4873 /*KnownDependent=*/false,
4874 /*KnownInstantiationDependent=*/false);
4875}
4876
4878 SourceLocation Loc) {
4879 Diag(Loc, diag::err_template_missing_args)
4880 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4881 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4882 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4883 }
4884}
4885
4887 bool TemplateKeyword,
4888 TemplateDecl *TD,
4889 SourceLocation Loc) {
4890 TemplateName Name = Context.getQualifiedTemplateName(
4891 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4893}
4894
4896 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4897 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4898 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4899 bool DoCheckConstraintSatisfaction) {
4900 assert(NamedConcept && "A concept template id without a template?");
4901
4902 if (NamedConcept->isInvalidDecl())
4903 return ExprError();
4904
4907 NamedConcept, ConceptNameInfo.getLoc(),
4908 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4909 /*DefaultArgs=*/{},
4910 /*PartialTemplateArgs=*/false, CTAI,
4911 /*UpdateArgsWithConversions=*/false))
4912 return ExprError();
4913
4914 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4915
4916 // There's a bug with CTAI.CanonicalConverted.
4917 // If the template argument contains a DependentDecltypeType that includes a
4918 // TypeAliasType, and the same written type had occurred previously in the
4919 // source, then the DependentDecltypeType would be canonicalized to that
4920 // previous type which would mess up the substitution.
4921 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4923 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4924 CTAI.SugaredConverted);
4925 ConstraintSatisfaction Satisfaction;
4926 bool AreArgsDependent =
4927 TemplateSpecializationType::anyDependentTemplateArguments(
4928 *TemplateArgs, CTAI.SugaredConverted);
4929 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4930 /*Final=*/false);
4932 Context,
4934 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4936
4937 bool Error = false;
4938 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4939 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4940 DoCheckConstraintSatisfaction) {
4941
4943
4946
4948 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4949 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4950 TemplateArgs->getRAngleLoc()),
4951 Satisfaction, CL);
4952 Satisfaction.ContainsErrors = Error;
4953 }
4954
4955 if (Error)
4956 return ExprError();
4957
4959 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4960}
4961
4963 SourceLocation TemplateKWLoc,
4964 LookupResult &R,
4965 bool RequiresADL,
4966 const TemplateArgumentListInfo *TemplateArgs) {
4967 // FIXME: Can we do any checking at this point? I guess we could check the
4968 // template arguments that we have against the template name, if the template
4969 // name refers to a single template. That's not a terribly common case,
4970 // though.
4971 // foo<int> could identify a single function unambiguously
4972 // This approach does NOT work, since f<int>(1);
4973 // gets resolved prior to resorting to overload resolution
4974 // i.e., template<class T> void f(double);
4975 // vs template<class T, class U> void f(U);
4976
4977 // These should be filtered out by our callers.
4978 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4979
4980 // Non-function templates require a template argument list.
4981 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4982 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4984 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4985 return ExprError();
4986 }
4987 }
4988 bool KnownDependent = false;
4989 // In C++1y, check variable template ids.
4990 if (R.getAsSingle<VarTemplateDecl>()) {
4992 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4993 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4994 if (Res.isInvalid() || Res.isUsable())
4995 return Res;
4996 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4997 KnownDependent = true;
4998 }
4999
5000 // We don't want lookup warnings at this point.
5001 R.suppressDiagnostics();
5002
5003 if (R.getAsSingle<ConceptDecl>()) {
5004 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5005 R.getRepresentativeDecl(),
5006 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5007 }
5008
5009 // Check variable template ids (C++17) and concept template parameters
5010 // (C++26).
5012 if (R.getAsSingle<TemplateTemplateParmDecl>())
5014 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),
5015 TemplateKWLoc, TemplateArgs);
5016
5017 // Function templates
5019 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5020 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5021 R.begin(), R.end(), KnownDependent,
5022 /*KnownInstantiationDependent=*/false);
5023 // Model the templates with UnresolvedTemplateTy. The expression should then
5024 // either be transformed in an instantiation or be diagnosed in
5025 // CheckPlaceholderExpr.
5026 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5027 !R.getFoundDecl()->getAsFunction())
5028 ULE->setType(Context.UnresolvedTemplateTy);
5029
5030 return ULE;
5031}
5032
5034 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5035 const DeclarationNameInfo &NameInfo,
5036 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5037 assert(TemplateArgs || TemplateKWLoc.isValid());
5038
5039 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5040 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5041 /*EnteringContext=*/false, TemplateKWLoc))
5042 return ExprError();
5043
5044 if (R.isAmbiguous())
5045 return ExprError();
5046
5047 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5048 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5049
5050 if (R.empty()) {
5052 Diag(NameInfo.getLoc(), diag::err_no_member)
5053 << NameInfo.getName() << DC << SS.getRange();
5054 return ExprError();
5055 }
5056
5057 // If necessary, build an implicit class member access.
5058 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5059 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5060 /*S=*/nullptr);
5061
5062 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5063}
5064
5066 CXXScopeSpec &SS,
5067 SourceLocation TemplateKWLoc,
5068 const UnqualifiedId &Name,
5069 ParsedType ObjectType,
5070 bool EnteringContext,
5072 bool AllowInjectedClassName) {
5073 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5074 Diag(TemplateKWLoc,
5076 diag::warn_cxx98_compat_template_outside_of_template :
5077 diag::ext_template_outside_of_template)
5078 << FixItHint::CreateRemoval(TemplateKWLoc);
5079
5080 if (SS.isInvalid())
5081 return TNK_Non_template;
5082
5083 // Figure out where isTemplateName is going to look.
5084 DeclContext *LookupCtx = nullptr;
5085 if (SS.isNotEmpty())
5086 LookupCtx = computeDeclContext(SS, EnteringContext);
5087 else if (ObjectType)
5088 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5089
5090 // C++0x [temp.names]p5:
5091 // If a name prefixed by the keyword template is not the name of
5092 // a template, the program is ill-formed. [Note: the keyword
5093 // template may not be applied to non-template members of class
5094 // templates. -end note ] [ Note: as is the case with the
5095 // typename prefix, the template prefix is allowed in cases
5096 // where it is not strictly necessary; i.e., when the
5097 // nested-name-specifier or the expression on the left of the ->
5098 // or . is not dependent on a template-parameter, or the use
5099 // does not appear in the scope of a template. -end note]
5100 //
5101 // Note: C++03 was more strict here, because it banned the use of
5102 // the "template" keyword prior to a template-name that was not a
5103 // dependent name. C++ DR468 relaxed this requirement (the
5104 // "template" keyword is now permitted). We follow the C++0x
5105 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5106 bool MemberOfUnknownSpecialization;
5107 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5108 ObjectType, EnteringContext, Result,
5109 MemberOfUnknownSpecialization);
5110 if (TNK != TNK_Non_template) {
5111 // We resolved this to a (non-dependent) template name. Return it.
5112 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5113 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5115 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5116 // C++14 [class.qual]p2:
5117 // In a lookup in which function names are not ignored and the
5118 // nested-name-specifier nominates a class C, if the name specified
5119 // [...] is the injected-class-name of C, [...] the name is instead
5120 // considered to name the constructor
5121 //
5122 // We don't get here if naming the constructor would be valid, so we
5123 // just reject immediately and recover by treating the
5124 // injected-class-name as naming the template.
5125 Diag(Name.getBeginLoc(),
5126 diag::ext_out_of_line_qualified_id_type_names_constructor)
5127 << Name.Identifier
5128 << 0 /*injected-class-name used as template name*/
5129 << TemplateKWLoc.isValid();
5130 }
5131 return TNK;
5132 }
5133
5134 if (!MemberOfUnknownSpecialization) {
5135 // Didn't find a template name, and the lookup wasn't dependent.
5136 // Do the lookup again to determine if this is a "nothing found" case or
5137 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5138 // need to do this.
5140 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5142 // Tell LookupTemplateName that we require a template so that it diagnoses
5143 // cases where it finds a non-template.
5144 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5145 ? RequiredTemplateKind(TemplateKWLoc)
5147 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5148 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5149 !R.isAmbiguous()) {
5150 if (LookupCtx)
5151 Diag(Name.getBeginLoc(), diag::err_no_member)
5152 << DNI.getName() << LookupCtx << SS.getRange();
5153 else
5154 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5155 << DNI.getName() << SS.getRange();
5156 }
5157 return TNK_Non_template;
5158 }
5159
5160 NestedNameSpecifier Qualifier = SS.getScopeRep();
5161
5162 switch (Name.getKind()) {
5164 Result = TemplateTy::make(Context.getDependentTemplateName(
5165 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5167
5169 Result = TemplateTy::make(Context.getDependentTemplateName(
5170 {Qualifier, Name.OperatorFunctionId.Operator,
5171 TemplateKWLoc.isValid()}));
5172 return TNK_Function_template;
5173
5175 // This is a kind of template name, but can never occur in a dependent
5176 // scope (literal operators can only be declared at namespace scope).
5177 break;
5178
5179 default:
5180 break;
5181 }
5182
5183 // This name cannot possibly name a dependent template. Diagnose this now
5184 // rather than building a dependent template name that can never be valid.
5185 Diag(Name.getBeginLoc(),
5186 diag::err_template_kw_refers_to_dependent_non_template)
5188 << TemplateKWLoc.isValid() << TemplateKWLoc;
5189 return TNK_Non_template;
5190}
5191
5194 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5195 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5196 const TemplateArgument &Arg = AL.getArgument();
5198 TypeSourceInfo *TSI = nullptr;
5199
5200 // Check template type parameter.
5201 switch(Arg.getKind()) {
5203 // C++ [temp.arg.type]p1:
5204 // A template-argument for a template-parameter which is a
5205 // type shall be a type-id.
5206 ArgType = Arg.getAsType();
5207 TSI = AL.getTypeSourceInfo();
5208 break;
5211 // We have a template type parameter but the template argument
5212 // is a template without any arguments.
5213 SourceRange SR = AL.getSourceRange();
5216 return true;
5217 }
5219 // We have a template type parameter but the template argument is an
5220 // expression; see if maybe it is missing the "typename" keyword.
5221 CXXScopeSpec SS;
5222 DeclarationNameInfo NameInfo;
5223
5224 if (DependentScopeDeclRefExpr *ArgExpr =
5225 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5226 SS.Adopt(ArgExpr->getQualifierLoc());
5227 NameInfo = ArgExpr->getNameInfo();
5228 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5229 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5230 if (ArgExpr->isImplicitAccess()) {
5231 SS.Adopt(ArgExpr->getQualifierLoc());
5232 NameInfo = ArgExpr->getMemberNameInfo();
5233 }
5234 }
5235
5236 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5237 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5238 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5239
5240 if (Result.getAsSingle<TypeDecl>() ||
5241 Result.wasNotFoundInCurrentInstantiation()) {
5242 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5243 // Suggest that the user add 'typename' before the NNS.
5245 Diag(Loc, getLangOpts().MSVCCompat
5246 ? diag::ext_ms_template_type_arg_missing_typename
5247 : diag::err_template_arg_must_be_type_suggest)
5248 << FixItHint::CreateInsertion(Loc, "typename ");
5250
5251 // Recover by synthesizing a type using the location information that we
5252 // already have.
5253 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5254 SS.getScopeRep(), II);
5255 TypeLocBuilder TLB;
5257 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5259 TL.setNameLoc(NameInfo.getLoc());
5260 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5261
5262 // Overwrite our input TemplateArgumentLoc so that we can recover
5263 // properly.
5266
5267 break;
5268 }
5269 }
5270 // fallthrough
5271 [[fallthrough]];
5272 }
5273 default: {
5274 // We allow instantiating a template with template argument packs when
5275 // building deduction guides or mapping constraint template parameters.
5276 if (Arg.getKind() == TemplateArgument::Pack &&
5277 (CodeSynthesisContexts.back().Kind ==
5280 SugaredConverted.push_back(Arg);
5281 CanonicalConverted.push_back(Arg);
5282 return false;
5283 }
5284 // We have a template type parameter but the template argument
5285 // is not a type.
5286 SourceRange SR = AL.getSourceRange();
5287 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5289
5290 return true;
5291 }
5292 }
5293
5294 if (CheckTemplateArgument(TSI))
5295 return true;
5296
5297 // Objective-C ARC:
5298 // If an explicitly-specified template argument type is a lifetime type
5299 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5300 if (getLangOpts().ObjCAutoRefCount &&
5301 ArgType->isObjCLifetimeType() &&
5302 !ArgType.getObjCLifetime()) {
5303 Qualifiers Qs;
5305 ArgType = Context.getQualifiedType(ArgType, Qs);
5306 }
5307
5308 SugaredConverted.push_back(TemplateArgument(ArgType));
5309 CanonicalConverted.push_back(
5310 TemplateArgument(Context.getCanonicalType(ArgType)));
5311 return false;
5312}
5313
5314/// Substitute template arguments into the default template argument for
5315/// the given template type parameter.
5316///
5317/// \param SemaRef the semantic analysis object for which we are performing
5318/// the substitution.
5319///
5320/// \param Template the template that we are synthesizing template arguments
5321/// for.
5322///
5323/// \param TemplateLoc the location of the template name that started the
5324/// template-id we are checking.
5325///
5326/// \param RAngleLoc the location of the right angle bracket ('>') that
5327/// terminates the template-id.
5328///
5329/// \param Param the template template parameter whose default we are
5330/// substituting into.
5331///
5332/// \param Converted the list of template arguments provided for template
5333/// parameters that precede \p Param in the template parameter list.
5334///
5335/// \param Output the resulting substituted template argument.
5336///
5337/// \returns true if an error occurred.
5339 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5340 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5341 ArrayRef<TemplateArgument> SugaredConverted,
5342 ArrayRef<TemplateArgument> CanonicalConverted,
5343 TemplateArgumentLoc &Output) {
5344 Output = Param->getDefaultArgument();
5345
5346 // If the argument type is dependent, instantiate it now based
5347 // on the previously-computed template arguments.
5348 if (Output.getArgument().isInstantiationDependent()) {
5349 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5350 SugaredConverted,
5351 SourceRange(TemplateLoc, RAngleLoc));
5352 if (Inst.isInvalid())
5353 return true;
5354
5355 // Only substitute for the innermost template argument list.
5356 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5357 /*Final=*/true);
5358 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5359 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5360
5361 bool ForLambdaCallOperator = false;
5362 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5363 ForLambdaCallOperator = Rec->isLambda();
5364 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5365 !ForLambdaCallOperator);
5366
5367 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5368 Param->getDefaultArgumentLoc(),
5369 Param->getDeclName()))
5370 return true;
5371 }
5372
5373 return false;
5374}
5375
5376/// Substitute template arguments into the default template argument for
5377/// the given non-type template parameter.
5378///
5379/// \param SemaRef the semantic analysis object for which we are performing
5380/// the substitution.
5381///
5382/// \param Template the template that we are synthesizing template arguments
5383/// for.
5384///
5385/// \param TemplateLoc the location of the template name that started the
5386/// template-id we are checking.
5387///
5388/// \param RAngleLoc the location of the right angle bracket ('>') that
5389/// terminates the template-id.
5390///
5391/// \param Param the non-type template parameter whose default we are
5392/// substituting into.
5393///
5394/// \param Converted the list of template arguments provided for template
5395/// parameters that precede \p Param in the template parameter list.
5396///
5397/// \returns the substituted template argument, or NULL if an error occurred.
5399 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5400 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5401 ArrayRef<TemplateArgument> SugaredConverted,
5402 ArrayRef<TemplateArgument> CanonicalConverted,
5403 TemplateArgumentLoc &Output) {
5404 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5405 SugaredConverted,
5406 SourceRange(TemplateLoc, RAngleLoc));
5407 if (Inst.isInvalid())
5408 return true;
5409
5410 // Only substitute for the innermost template argument list.
5411 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5412 /*Final=*/true);
5413 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5414 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5415
5416 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5417 EnterExpressionEvaluationContext ConstantEvaluated(
5419 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5420 TemplateArgLists, Output);
5421}
5422
5423/// Substitute template arguments into the default template argument for
5424/// the given template template parameter.
5425///
5426/// \param SemaRef the semantic analysis object for which we are performing
5427/// the substitution.
5428///
5429/// \param Template the template that we are synthesizing template arguments
5430/// for.
5431///
5432/// \param TemplateLoc the location of the template name that started the
5433/// template-id we are checking.
5434///
5435/// \param RAngleLoc the location of the right angle bracket ('>') that
5436/// terminates the template-id.
5437///
5438/// \param Param the template template parameter whose default we are
5439/// substituting into.
5440///
5441/// \param Converted the list of template arguments provided for template
5442/// parameters that precede \p Param in the template parameter list.
5443///
5444/// \param QualifierLoc Will be set to the nested-name-specifier (with
5445/// source-location information) that precedes the template name.
5446///
5447/// \returns the substituted template argument, or NULL if an error occurred.
5449 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5450 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5452 ArrayRef<TemplateArgument> SugaredConverted,
5453 ArrayRef<TemplateArgument> CanonicalConverted,
5454 NestedNameSpecifierLoc &QualifierLoc) {
5456 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5457 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5458 if (Inst.isInvalid())
5459 return TemplateName();
5460
5461 // Only substitute for the innermost template argument list.
5462 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5463 /*Final=*/true);
5464 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5465 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5466
5467 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5468
5469 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5470 QualifierLoc = A.getTemplateQualifierLoc();
5471 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5473 A.getTemplateNameLoc(), TemplateArgLists);
5474}
5475
5477 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5478 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5479 ArrayRef<TemplateArgument> SugaredConverted,
5480 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5481 HasDefaultArg = false;
5482
5483 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5484 if (!hasReachableDefaultArgument(TypeParm))
5485 return TemplateArgumentLoc();
5486
5487 HasDefaultArg = true;
5488 TemplateArgumentLoc Output;
5489 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5490 RAngleLoc, TypeParm, SugaredConverted,
5491 CanonicalConverted, Output))
5492 return TemplateArgumentLoc();
5493 return Output;
5494 }
5495
5496 if (NonTypeTemplateParmDecl *NonTypeParm
5497 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5498 if (!hasReachableDefaultArgument(NonTypeParm))
5499 return TemplateArgumentLoc();
5500
5501 HasDefaultArg = true;
5502 TemplateArgumentLoc Output;
5503 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5504 RAngleLoc, NonTypeParm, SugaredConverted,
5505 CanonicalConverted, Output))
5506 return TemplateArgumentLoc();
5507 return Output;
5508 }
5509
5510 TemplateTemplateParmDecl *TempTempParm
5512 if (!hasReachableDefaultArgument(TempTempParm))
5513 return TemplateArgumentLoc();
5514
5515 HasDefaultArg = true;
5516 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5517 NestedNameSpecifierLoc QualifierLoc;
5519 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5520 SugaredConverted, CanonicalConverted, QualifierLoc);
5521 if (TName.isNull())
5522 return TemplateArgumentLoc();
5523
5524 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5525 QualifierLoc, A.getTemplateNameLoc());
5526}
5527
5528/// Convert a template-argument that we parsed as a type into a template, if
5529/// possible. C++ permits injected-class-names to perform dual service as
5530/// template template arguments and as template type arguments.
5533 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5534 if (!TagLoc)
5535 return TemplateArgumentLoc();
5536
5537 // If this type was written as an injected-class-name, it can be used as a
5538 // template template argument.
5539 // If this type was written as an injected-class-name, it may have been
5540 // converted to a RecordType during instantiation. If the RecordType is
5541 // *not* wrapped in a TemplateSpecializationType and denotes a class
5542 // template specialization, it must have come from an injected-class-name.
5543
5544 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5545 if (Name.isNull())
5546 return TemplateArgumentLoc();
5547
5548 return TemplateArgumentLoc(Context, Name,
5549 /*TemplateKWLoc=*/SourceLocation(),
5550 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5551}
5552
5555 SourceLocation TemplateLoc,
5556 SourceLocation RAngleLoc,
5557 unsigned ArgumentPackIndex,
5560 // Check template type parameters.
5561 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5562 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5563 CTAI.CanonicalConverted);
5564
5565 const TemplateArgument &Arg = ArgLoc.getArgument();
5566 // Check non-type template parameters.
5567 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5568 // Do substitution on the type of the non-type template parameter
5569 // with the template arguments we've seen thus far. But if the
5570 // template has a dependent context then we cannot substitute yet.
5571 QualType NTTPType = NTTP->getType();
5572 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5573 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5574
5575 if (NTTPType->isInstantiationDependentType()) {
5576 // Do substitution on the type of the non-type template parameter.
5577 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5578 CTAI.SugaredConverted,
5579 SourceRange(TemplateLoc, RAngleLoc));
5580 if (Inst.isInvalid())
5581 return true;
5582
5584 /*Final=*/true);
5585 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5586 // If the parameter is a pack expansion, expand this slice of the pack.
5587 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5588 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5589 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5590 NTTP->getDeclName());
5591 } else {
5592 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5593 NTTP->getDeclName());
5594 }
5595
5596 // If that worked, check the non-type template parameter type
5597 // for validity.
5598 if (!NTTPType.isNull())
5599 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5600 NTTP->getLocation());
5601 if (NTTPType.isNull())
5602 return true;
5603 }
5604
5605 auto checkExpr = [&](Expr *E) -> Expr * {
5606 TemplateArgument SugaredResult, CanonicalResult;
5608 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5609 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5610 // If the current template argument causes an error, give up now.
5611 if (Res.isInvalid())
5612 return nullptr;
5613 CTAI.SugaredConverted.push_back(SugaredResult);
5614 CTAI.CanonicalConverted.push_back(CanonicalResult);
5615 return Res.get();
5616 };
5617
5618 switch (Arg.getKind()) {
5620 llvm_unreachable("Should never see a NULL template argument here");
5621
5623 Expr *E = Arg.getAsExpr();
5624 Expr *R = checkExpr(E);
5625 if (!R)
5626 return true;
5627 // If the resulting expression is new, then use it in place of the
5628 // old expression in the template argument.
5629 if (R != E) {
5630 TemplateArgument TA(R, /*IsCanonical=*/false);
5631 ArgLoc = TemplateArgumentLoc(TA, R);
5632 }
5633 break;
5634 }
5635
5636 // As for the converted NTTP kinds, they still might need another
5637 // conversion, as the new corresponding parameter might be different.
5638 // Ideally, we would always perform substitution starting with sugared types
5639 // and never need these, as we would still have expressions. Since these are
5640 // needed so rarely, it's probably a better tradeoff to just convert them
5641 // back to expressions.
5646 // FIXME: StructuralValue is untested here.
5647 ExprResult R =
5649 assert(R.isUsable());
5650 if (!checkExpr(R.get()))
5651 return true;
5652 break;
5653 }
5654
5657 // We were given a template template argument. It may not be ill-formed;
5658 // see below.
5661 // We have a template argument such as \c T::template X, which we
5662 // parsed as a template template argument. However, since we now
5663 // know that we need a non-type template argument, convert this
5664 // template name into an expression.
5665
5666 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5667 ArgLoc.getTemplateNameLoc());
5668
5669 CXXScopeSpec SS;
5670 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5671 // FIXME: the template-template arg was a DependentTemplateName,
5672 // so it was provided with a template keyword. However, its source
5673 // location is not stored in the template argument structure.
5674 SourceLocation TemplateKWLoc;
5676 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5677 nullptr);
5678
5679 // If we parsed the template argument as a pack expansion, create a
5680 // pack expansion expression.
5683 if (E.isInvalid())
5684 return true;
5685 }
5686
5687 TemplateArgument SugaredResult, CanonicalResult;
5689 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5690 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5691 if (E.isInvalid())
5692 return true;
5693
5694 CTAI.SugaredConverted.push_back(SugaredResult);
5695 CTAI.CanonicalConverted.push_back(CanonicalResult);
5696 break;
5697 }
5698
5699 // We have a template argument that actually does refer to a class
5700 // template, alias template, or template template parameter, and
5701 // therefore cannot be a non-type template argument.
5702 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5703 << ArgLoc.getSourceRange();
5705
5706 return true;
5707
5709 // We have a non-type template parameter but the template
5710 // argument is a type.
5711
5712 // C++ [temp.arg]p2:
5713 // In a template-argument, an ambiguity between a type-id and
5714 // an expression is resolved to a type-id, regardless of the
5715 // form of the corresponding template-parameter.
5716 //
5717 // We warn specifically about this case, since it can be rather
5718 // confusing for users.
5719 QualType T = Arg.getAsType();
5720 SourceRange SR = ArgLoc.getSourceRange();
5721 if (T->isFunctionType())
5722 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5723 else
5724 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5726 return true;
5727 }
5728
5730 llvm_unreachable("Caller must expand template argument packs");
5731 }
5732
5733 return false;
5734 }
5735
5736
5737 // Check template template parameters.
5739
5740 TemplateParameterList *Params = TempParm->getTemplateParameters();
5741 if (TempParm->isExpandedParameterPack())
5742 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5743
5744 // Substitute into the template parameter list of the template
5745 // template parameter, since previously-supplied template arguments
5746 // may appear within the template template parameter.
5747 //
5748 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5749 {
5750 // Set up a template instantiation context.
5752 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5753 CTAI.SugaredConverted,
5754 SourceRange(TemplateLoc, RAngleLoc));
5755 if (Inst.isInvalid())
5756 return true;
5757
5758 Params = SubstTemplateParams(
5759 Params, CurContext,
5761 /*Final=*/true),
5762 /*EvaluateConstraints=*/false);
5763 if (!Params)
5764 return true;
5765 }
5766
5767 // C++1z [temp.local]p1: (DR1004)
5768 // When [the injected-class-name] is used [...] as a template-argument for
5769 // a template template-parameter [...] it refers to the class template
5770 // itself.
5771 if (Arg.getKind() == TemplateArgument::Type) {
5773 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5774 if (!ConvertedArg.getArgument().isNull())
5775 ArgLoc = ConvertedArg;
5776 }
5777
5778 switch (Arg.getKind()) {
5780 llvm_unreachable("Should never see a NULL template argument here");
5781
5784 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5785 CTAI.PartialOrdering,
5786 &CTAI.StrictPackMatch))
5787 return true;
5788
5789 CTAI.SugaredConverted.push_back(Arg);
5790 CTAI.CanonicalConverted.push_back(
5791 Context.getCanonicalTemplateArgument(Arg));
5792 break;
5793
5796 auto Kind = 0;
5797 switch (TempParm->templateParameterKind()) {
5799 Kind = 1;
5800 break;
5802 Kind = 2;
5803 break;
5804 default:
5805 break;
5806 }
5807
5808 // We have a template template parameter but the template
5809 // argument does not refer to a template.
5810 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5811 << Kind << getLangOpts().CPlusPlus11;
5812 return true;
5813 }
5814
5819 llvm_unreachable("non-type argument with template template parameter");
5820
5822 llvm_unreachable("Caller must expand template argument packs");
5823 }
5824
5825 return false;
5826}
5827
5828/// Diagnose a missing template argument.
5829template<typename TemplateParmDecl>
5831 TemplateDecl *TD,
5832 const TemplateParmDecl *D,
5834 // Dig out the most recent declaration of the template parameter; there may be
5835 // declarations of the template that are more recent than TD.
5837 ->getTemplateParameters()
5838 ->getParam(D->getIndex()));
5839
5840 // If there's a default argument that's not reachable, diagnose that we're
5841 // missing a module import.
5843 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5845 D->getDefaultArgumentLoc(), Modules,
5847 /*Recover*/true);
5848 return true;
5849 }
5850
5851 // FIXME: If there's a more recent default argument that *is* visible,
5852 // diagnose that it was declared too late.
5853
5855
5856 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5857 << /*not enough args*/0
5859 << TD;
5860 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5861 return true;
5862}
5863
5864/// Check that the given template argument list is well-formed
5865/// for specializing the given template.
5867 TemplateDecl *Template, SourceLocation TemplateLoc,
5868 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5869 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5870 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5872 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5873 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5875}
5876
5877/// Check that the given template argument list is well-formed
5878/// for specializing the given template.
5881 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5882 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5883 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5885
5887 *ConstraintsNotSatisfied = false;
5888
5889 // Make a copy of the template arguments for processing. Only make the
5890 // changes at the end when successful in matching the arguments to the
5891 // template.
5892 TemplateArgumentListInfo NewArgs = TemplateArgs;
5893
5894 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5895
5896 // C++23 [temp.arg.general]p1:
5897 // [...] The type and form of each template-argument specified in
5898 // a template-id shall match the type and form specified for the
5899 // corresponding parameter declared by the template in its
5900 // template-parameter-list.
5901 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5902 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5903 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5904 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5905 LocalInstantiationScope InstScope(*this, true);
5906 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5907 ParamEnd = Params->end(),
5908 Param = ParamBegin;
5909 Param != ParamEnd;
5910 /* increment in loop */) {
5911 if (size_t ParamIdx = Param - ParamBegin;
5912 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5913 // All written arguments should have been consumed by this point.
5914 assert(ArgIdx == NumArgs && "bad default argument deduction");
5915 if (ParamIdx == DefaultArgs.StartPos) {
5916 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5917 // Default arguments from a DeducedTemplateName are already converted.
5918 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5919 CTAI.SugaredConverted.push_back(DefArg);
5920 CTAI.CanonicalConverted.push_back(
5921 Context.getCanonicalTemplateArgument(DefArg));
5922 ++Param;
5923 }
5924 continue;
5925 }
5926 }
5927
5928 // If we have an expanded parameter pack, make sure we don't have too
5929 // many arguments.
5930 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5931 if (*Expansions == SugaredArgumentPack.size()) {
5932 // We're done with this parameter pack. Pack up its arguments and add
5933 // them to the list.
5934 CTAI.SugaredConverted.push_back(
5935 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5936 SugaredArgumentPack.clear();
5937
5938 CTAI.CanonicalConverted.push_back(
5939 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5940 CanonicalArgumentPack.clear();
5941
5942 // This argument is assigned to the next parameter.
5943 ++Param;
5944 continue;
5945 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5946 // Not enough arguments for this parameter pack.
5947 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5948 << /*not enough args*/0
5950 << Template;
5952 return true;
5953 }
5954 }
5955
5956 // Check for builtins producing template packs in this context, we do not
5957 // support them yet.
5958 if (const NonTypeTemplateParmDecl *NTTP =
5959 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5960 NTTP && NTTP->isPackExpansion()) {
5961 auto TL = NTTP->getTypeSourceInfo()
5962 ->getTypeLoc()
5965 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5966 for (const auto &UPP : Unexpanded) {
5967 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5968 if (!TST)
5969 continue;
5970 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5971 // Expanding a built-in pack in this context is not yet supported.
5972 Diag(TL.getEllipsisLoc(),
5973 diag::err_unsupported_builtin_template_pack_expansion)
5974 << TST->getTemplateName();
5975 return true;
5976 }
5977 }
5978
5979 if (ArgIdx < NumArgs) {
5980 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5981 bool NonPackParameter =
5982 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5983 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5984
5985 if (ArgIsExpansion && CTAI.MatchingTTP) {
5986 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5987 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5988 ++Param) {
5989 TemplateArgument &Arg = Args[Param - First];
5990 Arg = ArgLoc.getArgument();
5991 if (!(*Param)->isTemplateParameterPack() ||
5992 getExpandedPackSize(*Param))
5993 Arg = Arg.getPackExpansionPattern();
5994 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5995 SaveAndRestore _1(CTAI.PartialOrdering, false);
5996 SaveAndRestore _2(CTAI.MatchingTTP, true);
5997 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5998 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6000 return true;
6001 Arg = NewArgLoc.getArgument();
6002 CTAI.CanonicalConverted.back().setIsDefaulted(
6003 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6004 CTAI.CanonicalConverted,
6005 Params->getDepth()));
6006 }
6007 ArgLoc = TemplateArgumentLoc(
6010 } else {
6011 SaveAndRestore _1(CTAI.PartialOrdering, false);
6012 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6013 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6015 return true;
6016 CTAI.CanonicalConverted.back().setIsDefaulted(
6017 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6018 *Param, CTAI.CanonicalConverted,
6019 Params->getDepth()));
6020 if (ArgIsExpansion && NonPackParameter) {
6021 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6022 // alias template, builtin template, or concept, and it's not part of
6023 // a parameter pack. This can't be canonicalized, so reject it now.
6025 Template)) {
6026 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6028 : 0;
6029 Diag(ArgLoc.getLocation(),
6030 diag::err_template_expansion_into_fixed_list)
6031 << DiagSelect << ArgLoc.getSourceRange();
6033 return true;
6034 }
6035 }
6036 }
6037
6038 // We're now done with this argument.
6039 ++ArgIdx;
6040
6041 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6042 // Directly convert the remaining arguments, because we don't know what
6043 // parameters they'll match up with.
6044
6045 if (!SugaredArgumentPack.empty()) {
6046 // If we were part way through filling in an expanded parameter pack,
6047 // fall back to just producing individual arguments.
6048 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6049 SugaredArgumentPack.begin(),
6050 SugaredArgumentPack.end());
6051 SugaredArgumentPack.clear();
6052
6053 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6054 CanonicalArgumentPack.begin(),
6055 CanonicalArgumentPack.end());
6056 CanonicalArgumentPack.clear();
6057 }
6058
6059 while (ArgIdx < NumArgs) {
6060 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6061 CTAI.SugaredConverted.push_back(Arg);
6062 CTAI.CanonicalConverted.push_back(
6063 Context.getCanonicalTemplateArgument(Arg));
6064 ++ArgIdx;
6065 }
6066
6067 return false;
6068 }
6069
6070 if ((*Param)->isTemplateParameterPack()) {
6071 // The template parameter was a template parameter pack, so take the
6072 // deduced argument and place it on the argument pack. Note that we
6073 // stay on the same template parameter so that we can deduce more
6074 // arguments.
6075 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6076 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6077 } else {
6078 // Move to the next template parameter.
6079 ++Param;
6080 }
6081 continue;
6082 }
6083
6084 // If we're checking a partial template argument list, we're done.
6085 if (PartialTemplateArgs) {
6086 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6087 CTAI.SugaredConverted.push_back(
6088 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6089 CTAI.CanonicalConverted.push_back(
6090 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6091 }
6092 return false;
6093 }
6094
6095 // If we have a template parameter pack with no more corresponding
6096 // arguments, just break out now and we'll fill in the argument pack below.
6097 if ((*Param)->isTemplateParameterPack()) {
6098 assert(!getExpandedPackSize(*Param) &&
6099 "Should have dealt with this already");
6100
6101 // A non-expanded parameter pack before the end of the parameter list
6102 // only occurs for an ill-formed template parameter list, unless we've
6103 // got a partial argument list for a function template, so just bail out.
6104 if (Param + 1 != ParamEnd) {
6105 assert(
6106 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6107 "Concept templates must have parameter packs at the end.");
6108 return true;
6109 }
6110
6111 CTAI.SugaredConverted.push_back(
6112 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6113 SugaredArgumentPack.clear();
6114
6115 CTAI.CanonicalConverted.push_back(
6116 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6117 CanonicalArgumentPack.clear();
6118
6119 ++Param;
6120 continue;
6121 }
6122
6123 // Check whether we have a default argument.
6124 bool HasDefaultArg;
6125
6126 // Retrieve the default template argument from the template
6127 // parameter. For each kind of template parameter, we substitute the
6128 // template arguments provided thus far and any "outer" template arguments
6129 // (when the template parameter was part of a nested template) into
6130 // the default argument.
6132 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6133 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6134
6135 if (Arg.getArgument().isNull()) {
6136 if (!HasDefaultArg) {
6137 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6138 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6139 NewArgs);
6140 if (NonTypeTemplateParmDecl *NTTP =
6141 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6142 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6143 NewArgs);
6144 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6146 NewArgs);
6147 }
6148 return true;
6149 }
6150
6151 // Introduce an instantiation record that describes where we are using
6152 // the default template argument. We're not actually instantiating a
6153 // template here, we just create this object to put a note into the
6154 // context stack.
6155 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6156 CTAI.SugaredConverted,
6157 SourceRange(TemplateLoc, RAngleLoc));
6158 if (Inst.isInvalid())
6159 return true;
6160
6161 SaveAndRestore _1(CTAI.PartialOrdering, false);
6162 SaveAndRestore _2(CTAI.MatchingTTP, false);
6163 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6164 // Check the default template argument.
6165 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6166 CTAI, CTAK_Specified))
6167 return true;
6168
6169 CTAI.SugaredConverted.back().setIsDefaulted(true);
6170 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6171
6172 // Core issue 150 (assumed resolution): if this is a template template
6173 // parameter, keep track of the default template arguments from the
6174 // template definition.
6175 if (isTemplateTemplateParameter)
6176 NewArgs.addArgument(Arg);
6177
6178 // Move to the next template parameter and argument.
6179 ++Param;
6180 ++ArgIdx;
6181 }
6182
6183 // If we're performing a partial argument substitution, allow any trailing
6184 // pack expansions; they might be empty. This can happen even if
6185 // PartialTemplateArgs is false (the list of arguments is complete but
6186 // still dependent).
6187 if (CTAI.MatchingTTP ||
6189 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6190 while (ArgIdx < NumArgs &&
6191 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6192 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6193 CTAI.SugaredConverted.push_back(Arg);
6194 CTAI.CanonicalConverted.push_back(
6195 Context.getCanonicalTemplateArgument(Arg));
6196 }
6197 }
6198
6199 // If we have any leftover arguments, then there were too many arguments.
6200 // Complain and fail.
6201 if (ArgIdx < NumArgs) {
6202 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6203 << /*too many args*/1
6205 << Template
6206 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6208 return true;
6209 }
6210
6211 // No problems found with the new argument list, propagate changes back
6212 // to caller.
6213 if (UpdateArgsWithConversions)
6214 TemplateArgs = std::move(NewArgs);
6215
6216 if (!PartialTemplateArgs) {
6217 // Setup the context/ThisScope for the case where we are needing to
6218 // re-instantiate constraints outside of normal instantiation.
6219 DeclContext *NewContext = Template->getDeclContext();
6220
6221 // If this template is in a template, make sure we extract the templated
6222 // decl.
6223 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6224 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6225 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6226
6227 Qualifiers ThisQuals;
6228 if (const auto *Method =
6229 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6230 ThisQuals = Method->getMethodQualifiers();
6231
6232 ContextRAII Context(*this, NewContext);
6233 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6234
6236 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6237 /*RelativeToPrimary=*/true,
6238 /*Pattern=*/nullptr,
6239 /*ForConceptInstantiation=*/true);
6240 if (!isa<ConceptDecl>(Template) &&
6242 Template, MLTAL,
6243 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6246 return true;
6247 }
6248 }
6249
6250 return false;
6251}
6252
6253namespace {
6254 class UnnamedLocalNoLinkageFinder
6255 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6256 {
6257 Sema &S;
6258 SourceRange SR;
6259
6261
6262 public:
6263 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6264
6265 bool Visit(QualType T) {
6266 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6267 }
6268
6269#define TYPE(Class, Parent) \
6270 bool Visit##Class##Type(const Class##Type *);
6271#define ABSTRACT_TYPE(Class, Parent) \
6272 bool Visit##Class##Type(const Class##Type *) { return false; }
6273#define NON_CANONICAL_TYPE(Class, Parent) \
6274 bool Visit##Class##Type(const Class##Type *) { return false; }
6275#include "clang/AST/TypeNodes.inc"
6276
6277 bool VisitTagDecl(const TagDecl *Tag);
6278 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6279 };
6280} // end anonymous namespace
6281
6282bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6283 return false;
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6287 return Visit(T->getElementType());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6291 return Visit(T->getPointeeType());
6292}
6293
6294bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6295 const BlockPointerType* T) {
6296 return Visit(T->getPointeeType());
6297}
6298
6299bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6300 const LValueReferenceType* T) {
6301 return Visit(T->getPointeeType());
6302}
6303
6304bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6305 const RValueReferenceType* T) {
6306 return Visit(T->getPointeeType());
6307}
6308
6309bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6310 const MemberPointerType *T) {
6311 if (Visit(T->getPointeeType()))
6312 return true;
6313 if (auto *RD = T->getMostRecentCXXRecordDecl())
6314 return VisitTagDecl(RD);
6315 return VisitNestedNameSpecifier(T->getQualifier());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6319 const ConstantArrayType* T) {
6320 return Visit(T->getElementType());
6321}
6322
6323bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6324 const IncompleteArrayType* T) {
6325 return Visit(T->getElementType());
6326}
6327
6328bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6329 const VariableArrayType* T) {
6330 return Visit(T->getElementType());
6331}
6332
6333bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6334 const DependentSizedArrayType* T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6340 return Visit(T->getElementType());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6344 const DependentSizedMatrixType *T) {
6345 return Visit(T->getElementType());
6346}
6347
6348bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6350 return Visit(T->getPointeeType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6354 return Visit(T->getElementType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6358 const DependentVectorType *T) {
6359 return Visit(T->getElementType());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6363 return Visit(T->getElementType());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6367 const ConstantMatrixType *T) {
6368 return Visit(T->getElementType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6372 const FunctionProtoType* T) {
6373 for (const auto &A : T->param_types()) {
6374 if (Visit(A))
6375 return true;
6376 }
6377
6378 return Visit(T->getReturnType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6382 const FunctionNoProtoType* T) {
6383 return Visit(T->getReturnType());
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6387 const UnresolvedUsingType*) {
6388 return false;
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6392 return false;
6393}
6394
6395bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6396 return Visit(T->getUnmodifiedType());
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6404 const PackIndexingType *) {
6405 return false;
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6409 const UnaryTransformType*) {
6410 return false;
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6414 return Visit(T->getDeducedType());
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6418 const DeducedTemplateSpecializationType *T) {
6419 return Visit(T->getDeducedType());
6420}
6421
6422bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6423 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6424}
6425
6426bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6427 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6428}
6429
6430bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6431 const TemplateTypeParmType*) {
6432 return false;
6433}
6434
6435bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6436 const SubstTemplateTypeParmPackType *) {
6437 return false;
6438}
6439
6440bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6441 const SubstBuiltinTemplatePackType *) {
6442 return false;
6443}
6444
6445bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6446 const TemplateSpecializationType*) {
6447 return false;
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6451 const InjectedClassNameType* T) {
6452 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6456 const DependentNameType* T) {
6457 return VisitNestedNameSpecifier(T->getQualifier());
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6461 const PackExpansionType* T) {
6462 return Visit(T->getPattern());
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6466 return false;
6467}
6468
6469bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6470 const ObjCInterfaceType *) {
6471 return false;
6472}
6473
6474bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6475 const ObjCObjectPointerType *) {
6476 return false;
6477}
6478
6479bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6480 return Visit(T->getValueType());
6481}
6482
6483bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6484 const OverflowBehaviorType *T) {
6485 return Visit(T->getUnderlyingType());
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6489 return false;
6490}
6491
6492bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6493 return false;
6494}
6495
6496bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6497 const ArrayParameterType *T) {
6498 return VisitConstantArrayType(T);
6499}
6500
6501bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6502 const DependentBitIntType *T) {
6503 return false;
6504}
6505
6506bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6507 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6508 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6509 ? diag::warn_cxx98_compat_template_arg_local_type
6510 : diag::ext_template_arg_local_type)
6511 << S.Context.getCanonicalTagType(Tag) << SR;
6512 return true;
6513 }
6514
6515 if (!Tag->hasNameForLinkage()) {
6516 S.Diag(SR.getBegin(),
6517 S.getLangOpts().CPlusPlus11 ?
6518 diag::warn_cxx98_compat_template_arg_unnamed_type :
6519 diag::ext_template_arg_unnamed_type) << SR;
6520 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6521 return true;
6522 }
6523
6524 return false;
6525}
6526
6527bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6528 NestedNameSpecifier NNS) {
6529 switch (NNS.getKind()) {
6534 return false;
6536 return Visit(QualType(NNS.getAsType(), 0));
6537 }
6538 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6539}
6540
6541bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6542 const HLSLAttributedResourceType *T) {
6543 if (T->hasContainedType() && Visit(T->getContainedType()))
6544 return true;
6545 return Visit(T->getWrappedType());
6546}
6547
6548bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6549 const HLSLInlineSpirvType *T) {
6550 for (auto &Operand : T->getOperands())
6551 if (Operand.isConstant() && Operand.isLiteral())
6552 if (Visit(Operand.getResultType()))
6553 return true;
6554 return false;
6555}
6556
6558 assert(ArgInfo && "invalid TypeSourceInfo");
6559 QualType Arg = ArgInfo->getType();
6560 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6561 QualType CanonArg = Context.getCanonicalType(Arg);
6562
6563 if (CanonArg->isVariablyModifiedType()) {
6564 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6565 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6566 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6567 }
6568
6569 // C++03 [temp.arg.type]p2:
6570 // A local type, a type with no linkage, an unnamed type or a type
6571 // compounded from any of these types shall not be used as a
6572 // template-argument for a template type-parameter.
6573 //
6574 // C++11 allows these, and even in C++03 we allow them as an extension with
6575 // a warning.
6576 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6577 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6578 (void)Finder.Visit(CanonArg);
6579 }
6580
6581 return false;
6582}
6583
6589
6590/// Determine whether the given template argument is a null pointer
6591/// value of the appropriate type.
6594 QualType ParamType, Expr *Arg,
6595 Decl *Entity = nullptr) {
6596 if (Arg->isValueDependent() || Arg->isTypeDependent())
6597 return NPV_NotNullPointer;
6598
6599 // dllimport'd entities aren't constant but are available inside of template
6600 // arguments.
6601 if (Entity && Entity->hasAttr<DLLImportAttr>())
6602 return NPV_NotNullPointer;
6603
6604 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6605 llvm_unreachable(
6606 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6607
6608 if (!S.getLangOpts().CPlusPlus11)
6609 return NPV_NotNullPointer;
6610
6611 // Determine whether we have a constant expression.
6613 if (ArgRV.isInvalid())
6614 return NPV_Error;
6615 Arg = ArgRV.get();
6616
6617 Expr::EvalResult EvalResult;
6619 EvalResult.Diag = &Notes;
6620 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6621 EvalResult.HasSideEffects) {
6622 SourceLocation DiagLoc = Arg->getExprLoc();
6623
6624 // If our only note is the usual "invalid subexpression" note, just point
6625 // the caret at its location rather than producing an essentially
6626 // redundant note.
6627 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6628 diag::note_invalid_subexpr_in_const_expr) {
6629 DiagLoc = Notes[0].first;
6630 Notes.clear();
6631 }
6632
6633 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6634 << Arg->getType() << Arg->getSourceRange();
6635 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6636 S.Diag(Notes[I].first, Notes[I].second);
6637
6639 return NPV_Error;
6640 }
6641
6642 // C++11 [temp.arg.nontype]p1:
6643 // - an address constant expression of type std::nullptr_t
6644 if (Arg->getType()->isNullPtrType())
6645 return NPV_NullPointer;
6646
6647 // - a constant expression that evaluates to a null pointer value (4.10); or
6648 // - a constant expression that evaluates to a null member pointer value
6649 // (4.11); or
6650 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6651 (EvalResult.Val.isMemberPointer() &&
6652 !EvalResult.Val.getMemberPointerDecl())) {
6653 // If our expression has an appropriate type, we've succeeded.
6654 bool ObjCLifetimeConversion;
6655 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6656 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6657 ObjCLifetimeConversion))
6658 return NPV_NullPointer;
6659
6660 // The types didn't match, but we know we got a null pointer; complain,
6661 // then recover as if the types were correct.
6662 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6663 << Arg->getType() << ParamType << Arg->getSourceRange();
6665 return NPV_NullPointer;
6666 }
6667
6668 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6669 // We found a pointer that isn't null, but doesn't refer to an object.
6670 // We could just return NPV_NotNullPointer, but we can print a better
6671 // message with the information we have here.
6672 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6673 << EvalResult.Val.getAsString(S.Context, ParamType);
6675 return NPV_Error;
6676 }
6677
6678 // If we don't have a null pointer value, but we do have a NULL pointer
6679 // constant, suggest a cast to the appropriate type.
6681 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6682 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6683 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6685 ")");
6687 return NPV_NullPointer;
6688 }
6689
6690 // FIXME: If we ever want to support general, address-constant expressions
6691 // as non-type template arguments, we should return the ExprResult here to
6692 // be interpreted by the caller.
6693 return NPV_NotNullPointer;
6694}
6695
6696/// Checks whether the given template argument is compatible with its
6697/// template parameter.
6698static bool
6700 QualType ParamType, Expr *ArgIn,
6701 Expr *Arg, QualType ArgType) {
6702 bool ObjCLifetimeConversion;
6703 if (ParamType->isPointerType() &&
6704 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6705 S.IsQualificationConversion(ArgType, ParamType, false,
6706 ObjCLifetimeConversion)) {
6707 // For pointer-to-object types, qualification conversions are
6708 // permitted.
6709 } else {
6710 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6711 if (!ParamRef->getPointeeType()->isFunctionType()) {
6712 // C++ [temp.arg.nontype]p5b3:
6713 // For a non-type template-parameter of type reference to
6714 // object, no conversions apply. The type referred to by the
6715 // reference may be more cv-qualified than the (otherwise
6716 // identical) type of the template- argument. The
6717 // template-parameter is bound directly to the
6718 // template-argument, which shall be an lvalue.
6719
6720 // FIXME: Other qualifiers?
6721 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6722 unsigned ArgQuals = ArgType.getCVRQualifiers();
6723
6724 if ((ParamQuals | ArgQuals) != ParamQuals) {
6725 S.Diag(Arg->getBeginLoc(),
6726 diag::err_template_arg_ref_bind_ignores_quals)
6727 << ParamType << Arg->getType() << Arg->getSourceRange();
6729 return true;
6730 }
6731 }
6732 }
6733
6734 // At this point, the template argument refers to an object or
6735 // function with external linkage. We now need to check whether the
6736 // argument and parameter types are compatible.
6737 if (!S.Context.hasSameUnqualifiedType(ArgType,
6738 ParamType.getNonReferenceType())) {
6739 // We can't perform this conversion or binding.
6740 if (ParamType->isReferenceType())
6741 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6742 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6743 else
6744 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6745 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6747 return true;
6748 }
6749 }
6750
6751 return false;
6752}
6753
6754/// Checks whether the given template argument is the address
6755/// of an object or function according to C++ [temp.arg.nontype]p1.
6757 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6758 bool IsSpecified, TemplateArgument &SugaredConverted,
6759 TemplateArgument &CanonicalConverted) {
6760 Expr *Arg = ArgIn;
6761 QualType ArgType = Arg->getType();
6762
6763 bool AddressTaken = false;
6764 SourceLocation AddrOpLoc;
6765 if (S.getLangOpts().MicrosoftExt) {
6766 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6767 // dereference and address-of operators.
6768 Arg = Arg->IgnoreParenCasts();
6769
6770 bool ExtWarnMSTemplateArg = false;
6771 UnaryOperatorKind FirstOpKind;
6772 SourceLocation FirstOpLoc;
6773 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6774 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6775 if (UnOpKind == UO_Deref)
6776 ExtWarnMSTemplateArg = true;
6777 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6778 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6779 if (!AddrOpLoc.isValid()) {
6780 FirstOpKind = UnOpKind;
6781 FirstOpLoc = UnOp->getOperatorLoc();
6782 }
6783 } else
6784 break;
6785 }
6786 if (FirstOpLoc.isValid()) {
6787 if (ExtWarnMSTemplateArg)
6788 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6789 << ArgIn->getSourceRange();
6790
6791 if (FirstOpKind == UO_AddrOf)
6792 AddressTaken = true;
6793 else if (Arg->getType()->isPointerType()) {
6794 // We cannot let pointers get dereferenced here, that is obviously not a
6795 // constant expression.
6796 assert(FirstOpKind == UO_Deref);
6797 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6798 << Arg->getSourceRange();
6799 }
6800 }
6801 } else {
6802 // See through any implicit casts we added to fix the type.
6803 // Also ignore parentheses for deduced template arguments.
6804 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6805
6806 // C++ [temp.arg.nontype]p1:
6807 //
6808 // A template-argument for a non-type, non-template
6809 // template-parameter shall be one of: [...]
6810 //
6811 // -- the address of an object or function with external
6812 // linkage, including function templates and function
6813 // template-ids but excluding non-static class members,
6814 // expressed as & id-expression where the & is optional if
6815 // the name refers to a function or array, or if the
6816 // corresponding template-parameter is a reference; or
6817
6818 // In C++98/03 mode, give an extension warning on any extra parentheses.
6819 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6820 if (IsSpecified) {
6821 bool ExtraParens = false;
6822 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6823 if (!ExtraParens) {
6824 S.DiagCompat(Arg->getBeginLoc(),
6825 diag_compat::template_arg_extra_parens)
6826 << Arg->getSourceRange();
6827 ExtraParens = true;
6828 }
6829
6830 Arg = Parens->getSubExpr();
6831 }
6832 }
6833
6834 while (SubstNonTypeTemplateParmExpr *subst =
6835 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6836 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6837
6838 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6839 if (UnOp->getOpcode() == UO_AddrOf) {
6840 Arg = UnOp->getSubExpr();
6841 AddressTaken = true;
6842 AddrOpLoc = UnOp->getOperatorLoc();
6843 }
6844 }
6845
6846 while (SubstNonTypeTemplateParmExpr *subst =
6847 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6848 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6849 }
6850
6851 ValueDecl *Entity = nullptr;
6852 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6853 Entity = DRE->getDecl();
6854 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6855 Entity = CUE->getGuidDecl();
6856
6857 // If our parameter has pointer type, check for a null template value.
6858 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6859 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6860 Entity)) {
6861 case NPV_NullPointer:
6862 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6863 SugaredConverted = TemplateArgument(ParamType,
6864 /*isNullPtr=*/true);
6865 CanonicalConverted =
6867 /*isNullPtr=*/true);
6868 return false;
6869
6870 case NPV_Error:
6871 return true;
6872
6873 case NPV_NotNullPointer:
6874 break;
6875 }
6876 }
6877
6878 // Stop checking the precise nature of the argument if it is value dependent,
6879 // it should be checked when instantiated.
6880 if (Arg->isValueDependent()) {
6881 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6882 CanonicalConverted =
6883 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6884 return false;
6885 }
6886
6887 if (!Entity) {
6888 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6889 << Arg->getSourceRange();
6891 return true;
6892 }
6893
6894 // Cannot refer to non-static data members
6895 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6896 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6897 << Entity << Arg->getSourceRange();
6899 return true;
6900 }
6901
6902 // Cannot refer to non-static member functions
6903 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6904 if (!Method->isStatic()) {
6905 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6906 << Method << Arg->getSourceRange();
6908 return true;
6909 }
6910 }
6911
6912 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6913 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6914 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6915
6916 // A non-type template argument must refer to an object or function.
6917 if (!Func && !Var && !Guid) {
6918 // We found something, but we don't know specifically what it is.
6919 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6920 << Arg->getSourceRange();
6921 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6922 return true;
6923 }
6924
6925 // Address / reference template args must have external linkage in C++98.
6926 if (Entity->getFormalLinkage() == Linkage::Internal) {
6927 S.Diag(Arg->getBeginLoc(),
6928 S.getLangOpts().CPlusPlus11
6929 ? diag::warn_cxx98_compat_template_arg_object_internal
6930 : diag::ext_template_arg_object_internal)
6931 << !Func << Entity << Arg->getSourceRange();
6932 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6933 << !Func;
6934 } else if (!Entity->hasLinkage()) {
6935 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6936 << !Func << Entity << Arg->getSourceRange();
6937 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6938 << !Func;
6939 return true;
6940 }
6941
6942 if (Var) {
6943 // A value of reference type is not an object.
6944 if (Var->getType()->isReferenceType()) {
6945 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6946 << Var->getType() << Arg->getSourceRange();
6948 return true;
6949 }
6950
6951 // A template argument must have static storage duration.
6952 if (Var->getTLSKind()) {
6953 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6954 << Arg->getSourceRange();
6955 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6956 return true;
6957 }
6958 }
6959
6960 if (AddressTaken && ParamType->isReferenceType()) {
6961 // If we originally had an address-of operator, but the
6962 // parameter has reference type, complain and (if things look
6963 // like they will work) drop the address-of operator.
6964 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6965 ParamType.getNonReferenceType())) {
6966 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6967 << ParamType;
6969 return true;
6970 }
6971
6972 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6973 << ParamType
6974 << FixItHint::CreateRemoval(AddrOpLoc);
6976
6977 ArgType = Entity->getType();
6978 }
6979
6980 // If the template parameter has pointer type, either we must have taken the
6981 // address or the argument must decay to a pointer.
6982 if (!AddressTaken && ParamType->isPointerType()) {
6983 if (Func) {
6984 // Function-to-pointer decay.
6985 ArgType = S.Context.getPointerType(Func->getType());
6986 } else if (Entity->getType()->isArrayType()) {
6987 // Array-to-pointer decay.
6988 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6989 } else {
6990 // If the template parameter has pointer type but the address of
6991 // this object was not taken, complain and (possibly) recover by
6992 // taking the address of the entity.
6993 ArgType = S.Context.getPointerType(Entity->getType());
6994 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6995 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6996 << ParamType;
6998 return true;
6999 }
7000
7001 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7002 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7003
7005 }
7006 }
7007
7008 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7009 Arg, ArgType))
7010 return true;
7011
7012 // Create the template argument.
7013 SugaredConverted = TemplateArgument(Entity, ParamType);
7014 CanonicalConverted =
7016 S.Context.getCanonicalType(ParamType));
7017 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7018 return false;
7019}
7020
7021/// Checks whether the given template argument is a pointer to
7022/// member constant according to C++ [temp.arg.nontype]p1.
7024 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7025 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7026 bool Invalid = false;
7027
7028 Expr *Arg = ResultArg;
7029 bool ObjCLifetimeConversion;
7030
7031 // C++ [temp.arg.nontype]p1:
7032 //
7033 // A template-argument for a non-type, non-template
7034 // template-parameter shall be one of: [...]
7035 //
7036 // -- a pointer to member expressed as described in 5.3.1.
7037 DeclRefExpr *DRE = nullptr;
7038
7039 // In C++98/03 mode, give an extension warning on any extra parentheses.
7040 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7041 bool ExtraParens = false;
7042 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7043 if (!Invalid && !ExtraParens) {
7044 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7045 << Arg->getSourceRange();
7046 ExtraParens = true;
7047 }
7048
7049 Arg = Parens->getSubExpr();
7050 }
7051
7052 while (SubstNonTypeTemplateParmExpr *subst =
7053 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7054 Arg = subst->getReplacement()->IgnoreImpCasts();
7055
7056 // A pointer-to-member constant written &Class::member.
7057 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7058 if (UnOp->getOpcode() == UO_AddrOf) {
7059 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7060 if (DRE && !DRE->getQualifier())
7061 DRE = nullptr;
7062 }
7063 }
7064 // A constant of pointer-to-member type.
7065 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7066 ValueDecl *VD = DRE->getDecl();
7067 if (VD->getType()->isMemberPointerType()) {
7069 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7070 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7071 CanonicalConverted =
7072 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7073 } else {
7074 SugaredConverted = TemplateArgument(VD, ParamType);
7075 CanonicalConverted =
7077 S.Context.getCanonicalType(ParamType));
7078 }
7079 return Invalid;
7080 }
7081 }
7082
7083 DRE = nullptr;
7084 }
7085
7086 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7087
7088 // Check for a null pointer value.
7089 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7090 Entity)) {
7091 case NPV_Error:
7092 return true;
7093 case NPV_NullPointer:
7094 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7095 SugaredConverted = TemplateArgument(ParamType,
7096 /*isNullPtr*/ true);
7097 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7098 /*isNullPtr*/ true);
7099 return false;
7100 case NPV_NotNullPointer:
7101 break;
7102 }
7103
7104 if (S.IsQualificationConversion(ResultArg->getType(),
7105 ParamType.getNonReferenceType(), false,
7106 ObjCLifetimeConversion)) {
7107 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7108 ResultArg->getValueKind())
7109 .get();
7110 } else if (!S.Context.hasSameUnqualifiedType(
7111 ResultArg->getType(), ParamType.getNonReferenceType())) {
7112 // We can't perform this conversion.
7113 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7114 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7116 return true;
7117 }
7118
7119 if (!DRE)
7120 return S.Diag(Arg->getBeginLoc(),
7121 diag::err_template_arg_not_pointer_to_member_form)
7122 << Arg->getSourceRange();
7123
7124 if (isa<FieldDecl>(DRE->getDecl()) ||
7126 isa<CXXMethodDecl>(DRE->getDecl())) {
7127 assert((isa<FieldDecl>(DRE->getDecl()) ||
7130 ->isImplicitObjectMemberFunction()) &&
7131 "Only non-static member pointers can make it here");
7132
7133 // Okay: this is the address of a non-static member, and therefore
7134 // a member pointer constant.
7135 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7136 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7137 CanonicalConverted =
7138 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7139 } else {
7140 ValueDecl *D = DRE->getDecl();
7141 SugaredConverted = TemplateArgument(D, ParamType);
7142 CanonicalConverted =
7144 S.Context.getCanonicalType(ParamType));
7145 }
7146 return Invalid;
7147 }
7148
7149 // We found something else, but we don't know specifically what it is.
7150 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7151 << Arg->getSourceRange();
7152 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7153 return true;
7154}
7155
7156/// Check a template argument against its corresponding
7157/// non-type template parameter.
7158///
7159/// This routine implements the semantics of C++ [temp.arg.nontype].
7160/// If an error occurred, it returns ExprError(); otherwise, it
7161/// returns the converted template argument. \p ParamType is the
7162/// type of the non-type template parameter after it has been instantiated.
7164 Expr *Arg,
7165 TemplateArgument &SugaredConverted,
7166 TemplateArgument &CanonicalConverted,
7167 bool StrictCheck,
7169 SourceLocation StartLoc = Arg->getBeginLoc();
7170 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7171 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7172 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7173 DeductionArg = NewDeductionArg;
7174 if (ArgPE) {
7175 // Recreate a pack expansion if we unwrapped one.
7176 Arg = new (Context) PackExpansionExpr(
7177 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7178 } else {
7179 Arg = DeductionArg;
7180 }
7181 };
7182
7183 // If the parameter type somehow involves auto, deduce the type now.
7184 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7185 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7186 if (IsDeduced) {
7187 // When checking a deduced template argument, deduce from its type even if
7188 // the type is dependent, in order to check the types of non-type template
7189 // arguments line up properly in partial ordering.
7190 TypeSourceInfo *TSI =
7191 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7193 InitializedEntity Entity =
7196 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7197 Expr *Inits[1] = {DeductionArg};
7198 ParamType =
7200 if (ParamType.isNull())
7201 return ExprError();
7202 } else {
7203 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7204 Param->getTemplateDepth() + 1);
7205 ParamType = QualType();
7207 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7208 /*DependentDeduction=*/true,
7209 // We do not check constraints right now because the
7210 // immediately-declared constraint of the auto type is
7211 // also an associated constraint, and will be checked
7212 // along with the other associated constraints after
7213 // checking the template argument list.
7214 /*IgnoreConstraints=*/true);
7216 ParamType = TSI->getType();
7217 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7219 return ExprError();
7220 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7221 Diag(Arg->getExprLoc(),
7222 diag::err_non_type_template_parm_type_deduction_failure)
7223 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7224 << Arg->getSourceRange();
7226 return ExprError();
7227 }
7228 ParamType = SubstAutoTypeDependent(ParamType);
7229 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7230 }
7231 }
7232 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7233 // an error. The error message normally references the parameter
7234 // declaration, but here we'll pass the argument location because that's
7235 // where the parameter type is deduced.
7236 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7237 if (ParamType.isNull()) {
7239 return ExprError();
7240 }
7241 }
7242
7243 // We should have already dropped all cv-qualifiers by now.
7244 assert(!ParamType.hasQualifiers() &&
7245 "non-type template parameter type cannot be qualified");
7246
7247 // If either the parameter has a dependent type or the argument is
7248 // type-dependent, there's nothing we can check now.
7249 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7250 // Force the argument to the type of the parameter to maintain invariants.
7251 if (!IsDeduced) {
7253 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7254 ParamType->isLValueReferenceType() ? VK_LValue
7255 : ParamType->isRValueReferenceType() ? VK_XValue
7256 : VK_PRValue);
7257 if (E.isInvalid())
7258 return ExprError();
7259 setDeductionArg(E.get());
7260 }
7261 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7262 CanonicalConverted = TemplateArgument(
7263 Context.getCanonicalTemplateArgument(SugaredConverted));
7264 return Arg;
7265 }
7266
7267 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7268 if (CTAK == CTAK_Deduced && !StrictCheck &&
7269 (ParamType->isReferenceType()
7270 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7271 DeductionArg->getType())
7272 : !Context.hasSameUnqualifiedType(ParamType,
7273 DeductionArg->getType()))) {
7274 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7275 // we should actually be checking the type of the template argument in P,
7276 // not the type of the template argument deduced from A, against the
7277 // template parameter type.
7278 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7279 << Arg->getType() << ParamType.getUnqualifiedType();
7281 return ExprError();
7282 }
7283
7284 // If the argument is a pack expansion, we don't know how many times it would
7285 // expand. If we continue checking the argument, this will make the template
7286 // definition ill-formed if it would be ill-formed for any number of
7287 // expansions during instantiation time. When partial ordering or matching
7288 // template template parameters, this is exactly what we want. Otherwise, the
7289 // normal template rules apply: we accept the template if it would be valid
7290 // for any number of expansions (i.e. none).
7291 if (ArgPE && !StrictCheck) {
7292 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7293 CanonicalConverted = TemplateArgument(
7294 Context.getCanonicalTemplateArgument(SugaredConverted));
7295 return Arg;
7296 }
7297
7298 // Avoid making a copy when initializing a template parameter of class type
7299 // from a template parameter object of the same type. This is going beyond
7300 // the standard, but is required for soundness: in
7301 // template<A a> struct X { X *p; X<a> *q; };
7302 // ... we need p and q to have the same type.
7303 //
7304 // Similarly, don't inject a call to a copy constructor when initializing
7305 // from a template parameter of the same type.
7306 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7307 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7308 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7309 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7310 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7311
7312 SugaredConverted = TemplateArgument(TPO, ParamType);
7313 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7314 ParamType.getCanonicalType());
7315 return Arg;
7316 }
7318 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7319 CanonicalConverted =
7320 Context.getCanonicalTemplateArgument(SugaredConverted);
7321 return Arg;
7322 }
7323 }
7324
7325 // The initialization of the parameter from the argument is
7326 // a constant-evaluated context.
7329
7330 bool IsConvertedConstantExpression = true;
7331 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7333 StartLoc, /*DirectInit=*/false, DeductionArg);
7334 Expr *Inits[1] = {DeductionArg};
7335 InitializedEntity Entity =
7337 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7338 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7339 if (Result.isInvalid() || !Result.get())
7340 return ExprError();
7342 if (Result.isInvalid() || !Result.get())
7343 return ExprError();
7344 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7345 /*DiscardedValue=*/false,
7346 /*IsConstexpr=*/true,
7347 /*IsTemplateArgument=*/true)
7348 .get());
7349 IsConvertedConstantExpression = false;
7350 }
7351
7352 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7353 // C++17 [temp.arg.nontype]p1:
7354 // A template-argument for a non-type template parameter shall be
7355 // a converted constant expression of the type of the template-parameter.
7356 APValue Value;
7357 ExprResult ArgResult;
7358 if (IsConvertedConstantExpression) {
7360 DeductionArg, ParamType,
7361 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7362 assert(!ArgResult.isUnset());
7363 if (ArgResult.isInvalid()) {
7365 return ExprError();
7366 }
7367 } else {
7368 ArgResult = DeductionArg;
7369 }
7370
7371 // For a value-dependent argument, CheckConvertedConstantExpression is
7372 // permitted (and expected) to be unable to determine a value.
7373 if (ArgResult.get()->isValueDependent()) {
7374 setDeductionArg(ArgResult.get());
7375 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7376 CanonicalConverted =
7377 Context.getCanonicalTemplateArgument(SugaredConverted);
7378 return Arg;
7379 }
7380
7381 APValue PreNarrowingValue;
7383 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7384 false, PreNarrowingValue);
7385 if (ArgResult.isInvalid())
7386 return ExprError();
7387 setDeductionArg(ArgResult.get());
7388
7389 if (Value.isLValue()) {
7390 APValue::LValueBase Base = Value.getLValueBase();
7391 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7392 // For a non-type template-parameter of pointer or reference type,
7393 // the value of the constant expression shall not refer to
7394 assert(ParamType->isPointerOrReferenceType() ||
7395 ParamType->isNullPtrType());
7396 // -- a temporary object
7397 // -- a string literal
7398 // -- the result of a typeid expression, or
7399 // -- a predefined __func__ variable
7400 if (Base &&
7401 (!VD ||
7403 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7404 << Arg->getSourceRange();
7405 return ExprError();
7406 }
7407
7408 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7409 VD->getType()->isArrayType() &&
7410 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7411 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7412 if (ArgPE) {
7413 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7414 CanonicalConverted =
7415 Context.getCanonicalTemplateArgument(SugaredConverted);
7416 } else {
7417 SugaredConverted = TemplateArgument(VD, ParamType);
7418 CanonicalConverted =
7419 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7420 ParamType.getCanonicalType());
7421 }
7422 return Arg;
7423 }
7424
7425 // -- a subobject [until C++20]
7426 if (!getLangOpts().CPlusPlus20) {
7427 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7428 Value.isLValueOnePastTheEnd()) {
7429 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7430 << Value.getAsString(Context, ParamType);
7431 return ExprError();
7432 }
7433 assert((VD || !ParamType->isReferenceType()) &&
7434 "null reference should not be a constant expression");
7435 assert((!VD || !ParamType->isNullPtrType()) &&
7436 "non-null value of type nullptr_t?");
7437 }
7438 }
7439
7440 if (Value.isAddrLabelDiff())
7441 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7442
7443 if (ArgPE) {
7444 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7445 CanonicalConverted =
7446 Context.getCanonicalTemplateArgument(SugaredConverted);
7447 } else {
7448 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7449 CanonicalConverted =
7451 }
7452 return Arg;
7453 }
7454
7455 // These should have all been handled above using the C++17 rules.
7456 assert(!ArgPE && !StrictCheck);
7457
7458 // C++ [temp.arg.nontype]p5:
7459 // The following conversions are performed on each expression used
7460 // as a non-type template-argument. If a non-type
7461 // template-argument cannot be converted to the type of the
7462 // corresponding template-parameter then the program is
7463 // ill-formed.
7464 if (ParamType->isIntegralOrEnumerationType()) {
7465 // C++11:
7466 // -- for a non-type template-parameter of integral or
7467 // enumeration type, conversions permitted in a converted
7468 // constant expression are applied.
7469 //
7470 // C++98:
7471 // -- for a non-type template-parameter of integral or
7472 // enumeration type, integral promotions (4.5) and integral
7473 // conversions (4.7) are applied.
7474
7475 if (getLangOpts().CPlusPlus11) {
7476 // C++ [temp.arg.nontype]p1:
7477 // A template-argument for a non-type, non-template template-parameter
7478 // shall be one of:
7479 //
7480 // -- for a non-type template-parameter of integral or enumeration
7481 // type, a converted constant expression of the type of the
7482 // template-parameter; or
7483 llvm::APSInt Value;
7485 Arg, ParamType, Value, CCEKind::TemplateArg);
7486 if (ArgResult.isInvalid())
7487 return ExprError();
7488 Arg = ArgResult.get();
7489
7490 // We can't check arbitrary value-dependent arguments.
7491 if (Arg->isValueDependent()) {
7492 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7493 CanonicalConverted =
7494 Context.getCanonicalTemplateArgument(SugaredConverted);
7495 return Arg;
7496 }
7497
7498 // Widen the argument value to sizeof(parameter type). This is almost
7499 // always a no-op, except when the parameter type is bool. In
7500 // that case, this may extend the argument from 1 bit to 8 bits.
7501 QualType IntegerType = ParamType;
7502 if (const auto *ED = IntegerType->getAsEnumDecl())
7503 IntegerType = ED->getIntegerType();
7504 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7505 ? Context.getIntWidth(IntegerType)
7506 : Context.getTypeSize(IntegerType));
7507
7508 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7509 CanonicalConverted =
7510 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7511 return Arg;
7512 }
7513
7514 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7515 if (ArgResult.isInvalid())
7516 return ExprError();
7517 Arg = ArgResult.get();
7518
7519 QualType ArgType = Arg->getType();
7520
7521 // C++ [temp.arg.nontype]p1:
7522 // A template-argument for a non-type, non-template
7523 // template-parameter shall be one of:
7524 //
7525 // -- an integral constant-expression of integral or enumeration
7526 // type; or
7527 // -- the name of a non-type template-parameter; or
7528 llvm::APSInt Value;
7529 if (!ArgType->isIntegralOrEnumerationType()) {
7530 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7531 << ArgType << Arg->getSourceRange();
7533 return ExprError();
7534 }
7535 if (!Arg->isValueDependent()) {
7536 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7537 QualType T;
7538
7539 public:
7540 TmplArgICEDiagnoser(QualType T) : T(T) { }
7541
7542 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7543 SourceLocation Loc) override {
7544 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7545 }
7546 } Diagnoser(ArgType);
7547
7548 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7549 if (!Arg)
7550 return ExprError();
7551 }
7552
7553 // From here on out, all we care about is the unqualified form
7554 // of the argument type.
7555 ArgType = ArgType.getUnqualifiedType();
7556
7557 // Try to convert the argument to the parameter's type.
7558 if (Context.hasSameType(ParamType, ArgType)) {
7559 // Okay: no conversion necessary
7560 } else if (ParamType->isBooleanType()) {
7561 // This is an integral-to-boolean conversion.
7562 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7563 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7564 !ParamType->isEnumeralType()) {
7565 // This is an integral promotion or conversion.
7566 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7567 } else {
7568 // We can't perform this conversion.
7569 Diag(StartLoc, diag::err_template_arg_not_convertible)
7570 << Arg->getType() << ParamType << Arg->getSourceRange();
7572 return ExprError();
7573 }
7574
7575 // Add the value of this argument to the list of converted
7576 // arguments. We use the bitwidth and signedness of the template
7577 // parameter.
7578 if (Arg->isValueDependent()) {
7579 // The argument is value-dependent. Create a new
7580 // TemplateArgument with the converted expression.
7581 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7582 CanonicalConverted =
7583 Context.getCanonicalTemplateArgument(SugaredConverted);
7584 return Arg;
7585 }
7586
7587 QualType IntegerType = ParamType;
7588 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7589 IntegerType = ED->getIntegerType();
7590 }
7591
7592 if (ParamType->isBooleanType()) {
7593 // Value must be zero or one.
7594 Value = Value != 0;
7595 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7596 if (Value.getBitWidth() != AllowedBits)
7597 Value = Value.extOrTrunc(AllowedBits);
7598 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7599 } else {
7600 llvm::APSInt OldValue = Value;
7601
7602 // Coerce the template argument's value to the value it will have
7603 // based on the template parameter's type.
7604 unsigned AllowedBits = IntegerType->isBitIntType()
7605 ? Context.getIntWidth(IntegerType)
7606 : Context.getTypeSize(IntegerType);
7607 if (Value.getBitWidth() != AllowedBits)
7608 Value = Value.extOrTrunc(AllowedBits);
7609 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7610
7611 // Complain if an unsigned parameter received a negative value.
7612 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7613 (OldValue.isSigned() && OldValue.isNegative())) {
7614 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7615 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7616 << Arg->getSourceRange();
7618 }
7619
7620 // Complain if we overflowed the template parameter's type.
7621 unsigned RequiredBits;
7622 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7623 RequiredBits = OldValue.getActiveBits();
7624 else if (OldValue.isUnsigned())
7625 RequiredBits = OldValue.getActiveBits() + 1;
7626 else
7627 RequiredBits = OldValue.getSignificantBits();
7628 if (RequiredBits > AllowedBits) {
7629 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7630 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7631 << Arg->getSourceRange();
7633 }
7634 }
7635
7636 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7637 SugaredConverted = TemplateArgument(Context, Value, T);
7638 CanonicalConverted =
7639 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7640 return Arg;
7641 }
7642
7643 QualType ArgType = Arg->getType();
7644 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7645 bool IsSpecified = CTAK == CTAK_Specified;
7646
7647 // Handle pointer-to-function, reference-to-function, and
7648 // pointer-to-member-function all in (roughly) the same way.
7649 if (// -- For a non-type template-parameter of type pointer to
7650 // function, only the function-to-pointer conversion (4.3) is
7651 // applied. If the template-argument represents a set of
7652 // overloaded functions (or a pointer to such), the matching
7653 // function is selected from the set (13.4).
7654 (ParamType->isPointerType() &&
7655 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7656 // -- For a non-type template-parameter of type reference to
7657 // function, no conversions apply. If the template-argument
7658 // represents a set of overloaded functions, the matching
7659 // function is selected from the set (13.4).
7660 (ParamType->isReferenceType() &&
7661 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7662 // -- For a non-type template-parameter of type pointer to
7663 // member function, no conversions apply. If the
7664 // template-argument represents a set of overloaded member
7665 // functions, the matching member function is selected from
7666 // the set (13.4).
7667 (ParamType->isMemberPointerType() &&
7668 ParamType->castAs<MemberPointerType>()->getPointeeType()
7669 ->isFunctionType())) {
7670
7671 if (Arg->getType() == Context.OverloadTy) {
7672 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7673 true,
7674 FoundResult)) {
7675 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7676 return ExprError();
7677
7678 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7679 if (Res.isInvalid())
7680 return ExprError();
7681 Arg = Res.get();
7682 ArgType = Arg->getType();
7683 } else
7684 return ExprError();
7685 }
7686
7687 if (!ParamType->isMemberPointerType()) {
7689 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7690 CanonicalConverted))
7691 return ExprError();
7692 return Arg;
7693 }
7694
7696 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7697 return ExprError();
7698 return Arg;
7699 }
7700
7701 if (ParamType->isPointerType()) {
7702 // -- for a non-type template-parameter of type pointer to
7703 // object, qualification conversions (4.4) and the
7704 // array-to-pointer conversion (4.2) are applied.
7705 // C++0x also allows a value of std::nullptr_t.
7706 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7707 "Only object pointers allowed here");
7708
7710 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7711 CanonicalConverted))
7712 return ExprError();
7713 return Arg;
7714 }
7715
7716 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7717 // -- For a non-type template-parameter of type reference to
7718 // object, no conversions apply. The type referred to by the
7719 // reference may be more cv-qualified than the (otherwise
7720 // identical) type of the template-argument. The
7721 // template-parameter is bound directly to the
7722 // template-argument, which must be an lvalue.
7723 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7724 "Only object references allowed here");
7725
7726 if (Arg->getType() == Context.OverloadTy) {
7728 ParamRefType->getPointeeType(),
7729 true,
7730 FoundResult)) {
7731 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7732 return ExprError();
7733 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7734 if (Res.isInvalid())
7735 return ExprError();
7736 Arg = Res.get();
7737 ArgType = Arg->getType();
7738 } else
7739 return ExprError();
7740 }
7741
7743 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7744 CanonicalConverted))
7745 return ExprError();
7746 return Arg;
7747 }
7748
7749 // Deal with parameters of type std::nullptr_t.
7750 if (ParamType->isNullPtrType()) {
7751 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7752 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7753 CanonicalConverted =
7754 Context.getCanonicalTemplateArgument(SugaredConverted);
7755 return Arg;
7756 }
7757
7758 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7759 case NPV_NotNullPointer:
7760 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7761 << Arg->getType() << ParamType;
7763 return ExprError();
7764
7765 case NPV_Error:
7766 return ExprError();
7767
7768 case NPV_NullPointer:
7769 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7770 SugaredConverted = TemplateArgument(ParamType,
7771 /*isNullPtr=*/true);
7772 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7773 /*isNullPtr=*/true);
7774 return Arg;
7775 }
7776 }
7777
7778 // -- For a non-type template-parameter of type pointer to data
7779 // member, qualification conversions (4.4) are applied.
7780 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7781
7783 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7784 return ExprError();
7785 return Arg;
7786}
7787
7791
7794 const TemplateArgumentLoc &Arg) {
7795 // C++0x [temp.arg.template]p1:
7796 // A template-argument for a template template-parameter shall be
7797 // the name of a class template or an alias template, expressed as an
7798 // id-expression. When the template-argument names a class template, only
7799 // primary class templates are considered when matching the
7800 // template template argument with the corresponding parameter;
7801 // partial specializations are not considered even if their
7802 // parameter lists match that of the template template parameter.
7803 //
7804
7806 unsigned DiagFoundKind = 0;
7807
7808 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7809 switch (TTP->templateParameterKind()) {
7811 DiagFoundKind = 3;
7812 break;
7814 DiagFoundKind = 2;
7815 break;
7816 default:
7817 DiagFoundKind = 1;
7818 break;
7819 }
7820 Kind = TTP->templateParameterKind();
7821 } else if (isa<ConceptDecl>(Template)) {
7823 DiagFoundKind = 3;
7824 } else if (isa<FunctionTemplateDecl>(Template)) {
7826 DiagFoundKind = 0;
7827 } else if (isa<VarTemplateDecl>(Template)) {
7829 DiagFoundKind = 2;
7830 } else if (isa<ClassTemplateDecl>(Template) ||
7834 DiagFoundKind = 1;
7835 } else {
7836 assert(false && "Unexpected Decl");
7837 }
7838
7839 if (Kind == Param->templateParameterKind()) {
7840 return true;
7841 }
7842
7843 unsigned DiagKind = 0;
7844 switch (Param->templateParameterKind()) {
7846 DiagKind = 2;
7847 break;
7849 DiagKind = 1;
7850 break;
7851 default:
7852 DiagKind = 0;
7853 break;
7854 }
7855 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7856 << DiagKind;
7857 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7858 << DiagFoundKind << Template;
7859 return false;
7860}
7861
7862/// Check a template argument against its corresponding
7863/// template template parameter.
7864///
7865/// This routine implements the semantics of C++ [temp.arg.template].
7866/// It returns true if an error occurred, and false otherwise.
7868 TemplateParameterList *Params,
7870 bool PartialOrdering,
7871 bool *StrictPackMatch) {
7873 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7874 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7875 if (!Template) {
7876 // FIXME: Handle AssumedTemplateNames
7877 // Any dependent template name is fine.
7878 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7879 return false;
7880 }
7881
7882 if (Template->isInvalidDecl())
7883 return true;
7884
7886 return true;
7887 }
7888
7889 // C++1z [temp.arg.template]p3: (DR 150)
7890 // A template-argument matches a template template-parameter P when P
7891 // is at least as specialized as the template-argument A.
7893 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7894 PartialOrdering, StrictPackMatch))
7895 return true;
7896 // P2113
7897 // C++20[temp.func.order]p2
7898 // [...] If both deductions succeed, the partial ordering selects the
7899 // more constrained template (if one exists) as determined below.
7900 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7901 Params->getAssociatedConstraints(ParamsAC);
7902 // C++20[temp.arg.template]p3
7903 // [...] In this comparison, if P is unconstrained, the constraints on A
7904 // are not considered.
7905 if (ParamsAC.empty())
7906 return false;
7907
7908 Template->getAssociatedConstraints(TemplateAC);
7909
7910 bool IsParamAtLeastAsConstrained;
7911 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7912 IsParamAtLeastAsConstrained))
7913 return true;
7914 if (!IsParamAtLeastAsConstrained) {
7915 Diag(Arg.getLocation(),
7916 diag::err_template_template_parameter_not_at_least_as_constrained)
7917 << Template << Param << Arg.getSourceRange();
7918 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7919 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7921 TemplateAC);
7922 return true;
7923 }
7924 return false;
7925}
7926
7928 unsigned HereDiagID,
7929 unsigned ExternalDiagID) {
7930 if (Decl.getLocation().isValid())
7931 return S.Diag(Decl.getLocation(), HereDiagID);
7932
7933 SmallString<128> Str;
7934 llvm::raw_svector_ostream Out(Str);
7936 PP.TerseOutput = 1;
7937 Decl.print(Out, PP);
7938 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7939}
7940
7942 std::optional<SourceRange> ParamRange) {
7944 noteLocation(*this, Decl, diag::note_template_decl_here,
7945 diag::note_template_decl_external);
7946 if (ParamRange && ParamRange->isValid()) {
7947 assert(Decl.getLocation().isValid() &&
7948 "Parameter range has location when Decl does not");
7949 DB << *ParamRange;
7950 }
7951}
7952
7954 noteLocation(*this, Decl, diag::note_template_param_here,
7955 diag::note_template_param_external);
7956}
7957
7958/// Given a non-type template argument that refers to a
7959/// declaration and the type of its corresponding non-type template
7960/// parameter, produce an expression that properly refers to that
7961/// declaration.
7963 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7964 // C++ [temp.param]p8:
7965 //
7966 // A non-type template-parameter of type "array of T" or
7967 // "function returning T" is adjusted to be of type "pointer to
7968 // T" or "pointer to function returning T", respectively.
7969 if (ParamType->isArrayType())
7970 ParamType = Context.getArrayDecayedType(ParamType);
7971 else if (ParamType->isFunctionType())
7972 ParamType = Context.getPointerType(ParamType);
7973
7974 // For a NULL non-type template argument, return nullptr casted to the
7975 // parameter's type.
7976 if (Arg.getKind() == TemplateArgument::NullPtr) {
7977 return ImpCastExprToType(
7978 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7979 ParamType,
7980 ParamType->getAs<MemberPointerType>()
7981 ? CK_NullToMemberPointer
7982 : CK_NullToPointer);
7983 }
7984 assert(Arg.getKind() == TemplateArgument::Declaration &&
7985 "Only declaration template arguments permitted here");
7986
7987 ValueDecl *VD = Arg.getAsDecl();
7988
7989 CXXScopeSpec SS;
7990 if (ParamType->isMemberPointerType()) {
7991 // If this is a pointer to member, we need to use a qualified name to
7992 // form a suitable pointer-to-member constant.
7993 assert(VD->getDeclContext()->isRecord() &&
7994 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7996 CanQualType ClassType =
7997 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7998 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7999 SS.MakeTrivial(Context, Qualifier, Loc);
8000 }
8001
8003 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8004 if (RefExpr.isInvalid())
8005 return ExprError();
8006
8007 // For a pointer, the argument declaration is the pointee. Take its address.
8008 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8009 if (ParamType->isPointerType() && !ElemT.isNull() &&
8010 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8011 // Decay an array argument if we want a pointer to its first element.
8012 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8013 if (RefExpr.isInvalid())
8014 return ExprError();
8015 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8016 // For any other pointer, take the address (or form a pointer-to-member).
8017 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8018 if (RefExpr.isInvalid())
8019 return ExprError();
8020 } else if (ParamType->isRecordType()) {
8021 assert(isa<TemplateParamObjectDecl>(VD) &&
8022 "arg for class template param not a template parameter object");
8023 // No conversions apply in this case.
8024 return RefExpr;
8025 } else {
8026 assert(ParamType->isReferenceType() &&
8027 "unexpected type for decl template argument");
8028 // If the parameter has reference type, wrap it in paretheses so that this
8029 // expression will have the correct type under `decltype`.
8030 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8031 }
8032
8033 // At this point we should have the right value category.
8034 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8035 "value kind mismatch for non-type template argument");
8036
8037 // The type of the template parameter can differ from the type of the
8038 // argument in various ways; convert it now if necessary.
8039 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8040 QualType SrcExprType = RefExpr.get()->getType();
8041 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8042 CastKind CK;
8043 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8044 IsFunctionConversion(SrcExprType, DestExprType)) {
8045 CK = CK_NoOp;
8046 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8047 CK = CK_BitCast;
8048 } else {
8049 // FIXME: Pointers to members can need conversion derived-to-base or
8050 // base-to-derived conversions. We currently don't retain enough
8051 // information to convert properly (we need to track a cast path or
8052 // subobject number in the template argument).
8053 llvm_unreachable(
8054 "unexpected conversion required for non-type template argument");
8055 }
8056 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8057 RefExpr.get()->getValueKind());
8058 }
8059
8060 return RefExpr;
8061}
8062
8063/// Construct a new expression that refers to the given
8064/// integral template argument with the given source-location
8065/// information.
8066///
8067/// This routine takes care of the mapping from an integral template
8068/// argument (which may have any integral type) to the appropriate
8069/// literal value.
8071 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8072 assert(OrigT->isIntegralOrEnumerationType());
8073
8074 // If this is an enum type that we're instantiating, we need to use an integer
8075 // type the same size as the enumerator. We don't want to build an
8076 // IntegerLiteral with enum type. The integer type of an enum type can be of
8077 // any integral type with C++11 enum classes, make sure we create the right
8078 // type of literal for it.
8079 QualType T = OrigT;
8080 if (const auto *ED = OrigT->getAsEnumDecl())
8081 T = ED->getIntegerType();
8082
8083 Expr *E;
8084 if (T->isAnyCharacterType()) {
8086 if (T->isWideCharType())
8088 else if (T->isChar8Type() && S.getLangOpts().Char8)
8090 else if (T->isChar16Type())
8092 else if (T->isChar32Type())
8094 else
8096
8097 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8098 } else if (T->isBooleanType()) {
8099 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8100 } else {
8101 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8102 }
8103
8104 if (OrigT->isEnumeralType()) {
8105 // FIXME: This is a hack. We need a better way to handle substituted
8106 // non-type template parameters.
8107 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8108 nullptr, S.CurFPFeatureOverrides(),
8109 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8110 Loc, Loc);
8111 }
8112
8113 return E;
8114}
8115
8117 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8118 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8119 auto *ILE = new (S.Context)
8120 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8121 ILE->setType(T);
8122 return ILE;
8123 };
8124
8125 switch (Val.getKind()) {
8127 // This cannot occur in a template argument at all.
8128 case APValue::Array:
8129 case APValue::Struct:
8130 case APValue::Union:
8131 // These can only occur within a template parameter object, which is
8132 // represented as a TemplateArgument::Declaration.
8133 llvm_unreachable("unexpected template argument value");
8134
8135 case APValue::Int:
8137 Loc);
8138
8139 case APValue::Float:
8140 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8141 T, Loc);
8142
8145 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8146 Val.getFixedPoint().getScale());
8147
8148 case APValue::ComplexInt: {
8149 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8151 S, ElemT, Val.getComplexIntReal(), Loc),
8153 S, ElemT, Val.getComplexIntImag(), Loc)});
8154 }
8155
8156 case APValue::ComplexFloat: {
8157 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8158 return MakeInitList(
8160 ElemT, Loc),
8162 ElemT, Loc)});
8163 }
8164
8165 case APValue::Vector: {
8166 QualType ElemT = T->castAs<VectorType>()->getElementType();
8168 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8170 S, ElemT, Val.getVectorElt(I), Loc));
8171 return MakeInitList(Elts);
8172 }
8173
8174 case APValue::Matrix:
8175 llvm_unreachable("Matrix template argument expression not yet supported");
8176
8177 case APValue::None:
8179 llvm_unreachable("Unexpected APValue kind.");
8180 case APValue::LValue:
8182 // There isn't necessarily a valid equivalent source-level syntax for
8183 // these; in particular, a naive lowering might violate access control.
8184 // So for now we lower to a ConstantExpr holding the value, wrapped around
8185 // an OpaqueValueExpr.
8186 // FIXME: We should have a better representation for this.
8188 if (T->isReferenceType()) {
8189 T = T->getPointeeType();
8190 VK = VK_LValue;
8191 }
8192 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8193 return ConstantExpr::Create(S.Context, OVE, Val);
8194 }
8195 llvm_unreachable("Unhandled APValue::ValueKind enum");
8196}
8197
8200 SourceLocation Loc) {
8201 switch (Arg.getKind()) {
8207 llvm_unreachable("not a non-type template argument");
8208
8210 return Arg.getAsExpr();
8211
8215 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8216
8219 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8220
8223 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8224 }
8225 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8226}
8227
8228/// Match two template parameters within template parameter lists.
8230 Sema &S, NamedDecl *New,
8231 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8232 const NamedDecl *OldInstFrom, bool Complain,
8234 // Check the actual kind (type, non-type, template).
8235 if (Old->getKind() != New->getKind()) {
8236 if (Complain) {
8237 unsigned NextDiag = diag::err_template_param_different_kind;
8238 if (TemplateArgLoc.isValid()) {
8239 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8240 NextDiag = diag::note_template_param_different_kind;
8241 }
8242 S.Diag(New->getLocation(), NextDiag)
8243 << (Kind != Sema::TPL_TemplateMatch);
8244 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8245 << (Kind != Sema::TPL_TemplateMatch);
8246 }
8247
8248 return false;
8249 }
8250
8251 // Check that both are parameter packs or neither are parameter packs.
8252 // However, if we are matching a template template argument to a
8253 // template template parameter, the template template parameter can have
8254 // a parameter pack where the template template argument does not.
8255 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8256 if (Complain) {
8257 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8258 if (TemplateArgLoc.isValid()) {
8259 S.Diag(TemplateArgLoc,
8260 diag::err_template_arg_template_params_mismatch);
8261 NextDiag = diag::note_template_parameter_pack_non_pack;
8262 }
8263
8264 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8266 : 2;
8267 S.Diag(New->getLocation(), NextDiag)
8268 << ParamKind << New->isParameterPack();
8269 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8270 << ParamKind << Old->isParameterPack();
8271 }
8272
8273 return false;
8274 }
8275 // For non-type template parameters, check the type of the parameter.
8276 if (NonTypeTemplateParmDecl *OldNTTP =
8277 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8279
8280 // If we are matching a template template argument to a template
8281 // template parameter and one of the non-type template parameter types
8282 // is dependent, then we must wait until template instantiation time
8283 // to actually compare the arguments.
8285 (!OldNTTP->getType()->isDependentType() &&
8286 !NewNTTP->getType()->isDependentType())) {
8287 // C++20 [temp.over.link]p6:
8288 // Two [non-type] template-parameters are equivalent [if] they have
8289 // equivalent types ignoring the use of type-constraints for
8290 // placeholder types
8291 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8292 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8293 if (!S.Context.hasSameType(OldType, NewType)) {
8294 if (Complain) {
8295 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8296 if (TemplateArgLoc.isValid()) {
8297 S.Diag(TemplateArgLoc,
8298 diag::err_template_arg_template_params_mismatch);
8299 NextDiag = diag::note_template_nontype_parm_different_type;
8300 }
8301 S.Diag(NewNTTP->getLocation(), NextDiag)
8302 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8303 S.Diag(OldNTTP->getLocation(),
8304 diag::note_template_nontype_parm_prev_declaration)
8305 << OldNTTP->getType();
8306 }
8307 return false;
8308 }
8309 }
8310 }
8311 // For template template parameters, check the template parameter types.
8312 // The template parameter lists of template template
8313 // parameters must agree.
8314 else if (TemplateTemplateParmDecl *OldTTP =
8315 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8317 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8318 return false;
8320 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8321 OldTTP->getTemplateParameters(), Complain,
8324 : Kind),
8325 TemplateArgLoc))
8326 return false;
8327 }
8328
8332 const Expr *NewC = nullptr, *OldC = nullptr;
8333
8335 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8336 NewC = TC->getImmediatelyDeclaredConstraint();
8337 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8338 OldC = TC->getImmediatelyDeclaredConstraint();
8339 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8340 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8341 ->getPlaceholderTypeConstraint())
8342 NewC = E;
8343 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8344 ->getPlaceholderTypeConstraint())
8345 OldC = E;
8346 } else
8347 llvm_unreachable("unexpected template parameter type");
8348
8349 auto Diagnose = [&] {
8350 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8351 diag::err_template_different_type_constraint);
8352 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8353 diag::note_template_prev_declaration) << /*declaration*/0;
8354 };
8355
8356 if (!NewC != !OldC) {
8357 if (Complain)
8358 Diagnose();
8359 return false;
8360 }
8361
8362 if (NewC) {
8363 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8364 NewC)) {
8365 if (Complain)
8366 Diagnose();
8367 return false;
8368 }
8369 }
8370 }
8371
8372 return true;
8373}
8374
8375/// Diagnose a known arity mismatch when comparing template argument
8376/// lists.
8377static
8382 SourceLocation TemplateArgLoc) {
8383 unsigned NextDiag = diag::err_template_param_list_different_arity;
8384 if (TemplateArgLoc.isValid()) {
8385 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8386 NextDiag = diag::note_template_param_list_different_arity;
8387 }
8388 S.Diag(New->getTemplateLoc(), NextDiag)
8389 << (New->size() > Old->size())
8390 << (Kind != Sema::TPL_TemplateMatch)
8391 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8392 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8393 << (Kind != Sema::TPL_TemplateMatch)
8394 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8395}
8396
8399 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8400 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8401 if (Old->size() != New->size()) {
8402 if (Complain)
8404 TemplateArgLoc);
8405
8406 return false;
8407 }
8408
8409 // C++0x [temp.arg.template]p3:
8410 // A template-argument matches a template template-parameter (call it P)
8411 // when each of the template parameters in the template-parameter-list of
8412 // the template-argument's corresponding class template or alias template
8413 // (call it A) matches the corresponding template parameter in the
8414 // template-parameter-list of P. [...]
8415 TemplateParameterList::iterator NewParm = New->begin();
8416 TemplateParameterList::iterator NewParmEnd = New->end();
8417 for (TemplateParameterList::iterator OldParm = Old->begin(),
8418 OldParmEnd = Old->end();
8419 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8420 if (NewParm == NewParmEnd) {
8421 if (Complain)
8423 TemplateArgLoc);
8424 return false;
8425 }
8426 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8427 OldInstFrom, Complain, Kind,
8428 TemplateArgLoc))
8429 return false;
8430 }
8431
8432 // Make sure we exhausted all of the arguments.
8433 if (NewParm != NewParmEnd) {
8434 if (Complain)
8436 TemplateArgLoc);
8437
8438 return false;
8439 }
8440
8441 if (Kind != TPL_TemplateParamsEquivalent) {
8442 const Expr *NewRC = New->getRequiresClause();
8443 const Expr *OldRC = Old->getRequiresClause();
8444
8445 auto Diagnose = [&] {
8446 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8447 diag::err_template_different_requires_clause);
8448 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8449 diag::note_template_prev_declaration) << /*declaration*/0;
8450 };
8451
8452 if (!NewRC != !OldRC) {
8453 if (Complain)
8454 Diagnose();
8455 return false;
8456 }
8457
8458 if (NewRC) {
8459 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8460 NewRC)) {
8461 if (Complain)
8462 Diagnose();
8463 return false;
8464 }
8465 }
8466 }
8467
8468 return true;
8469}
8470
8471bool
8473 if (!S)
8474 return false;
8475
8476 // Find the nearest enclosing declaration scope.
8477 S = S->getDeclParent();
8478
8479 // C++ [temp.pre]p6: [P2096]
8480 // A template, explicit specialization, or partial specialization shall not
8481 // have C linkage.
8482 DeclContext *Ctx = S->getEntity();
8483 if (Ctx && Ctx->isExternCContext()) {
8484 SourceRange Range =
8485 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8486 ? TemplateParams->getParam(0)->getSourceRange()
8487 : TemplateParams->getSourceRange();
8488 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8489 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8490 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8491 return true;
8492 }
8493 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8494
8495 // C++ [temp]p2:
8496 // A template-declaration can appear only as a namespace scope or
8497 // class scope declaration.
8498 // C++ [temp.expl.spec]p3:
8499 // An explicit specialization may be declared in any scope in which the
8500 // corresponding primary template may be defined.
8501 // C++ [temp.class.spec]p6: [P2096]
8502 // A partial specialization may be declared in any scope in which the
8503 // corresponding primary template may be defined.
8504 if (Ctx) {
8505 if (Ctx->isFileContext())
8506 return false;
8507 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8508 // C++ [temp.mem]p2:
8509 // A local class shall not have member templates.
8510 if (RD->isLocalClass())
8511 return Diag(TemplateParams->getTemplateLoc(),
8512 diag::err_template_inside_local_class)
8513 << TemplateParams->getSourceRange();
8514 else
8515 return false;
8516 }
8517 }
8518
8519 return Diag(TemplateParams->getTemplateLoc(),
8520 diag::err_template_outside_namespace_or_class_scope)
8521 << TemplateParams->getSourceRange();
8522}
8523
8524/// Determine what kind of template specialization the given declaration
8525/// is.
8527 if (!D)
8528 return TSK_Undeclared;
8529
8530 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8531 return Record->getTemplateSpecializationKind();
8532 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8533 return Function->getTemplateSpecializationKind();
8534 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8535 return Var->getTemplateSpecializationKind();
8536
8537 return TSK_Undeclared;
8538}
8539
8540/// Check whether a specialization is well-formed in the current
8541/// context.
8542///
8543/// This routine determines whether a template specialization can be declared
8544/// in the current context (C++ [temp.expl.spec]p2).
8545///
8546/// \param S the semantic analysis object for which this check is being
8547/// performed.
8548///
8549/// \param Specialized the entity being specialized or instantiated, which
8550/// may be a kind of template (class template, function template, etc.) or
8551/// a member of a class template (member function, static data member,
8552/// member class).
8553///
8554/// \param PrevDecl the previous declaration of this entity, if any.
8555///
8556/// \param Loc the location of the explicit specialization or instantiation of
8557/// this entity.
8558///
8559/// \param IsPartialSpecialization whether this is a partial specialization of
8560/// a class template.
8561///
8562/// \returns true if there was an error that we cannot recover from, false
8563/// otherwise.
8565 NamedDecl *Specialized,
8566 NamedDecl *PrevDecl,
8567 SourceLocation Loc,
8569 // Keep these "kind" numbers in sync with the %select statements in the
8570 // various diagnostics emitted by this routine.
8571 int EntityKind = 0;
8572 if (isa<ClassTemplateDecl>(Specialized))
8573 EntityKind = IsPartialSpecialization? 1 : 0;
8574 else if (isa<VarTemplateDecl>(Specialized))
8575 EntityKind = IsPartialSpecialization ? 3 : 2;
8576 else if (isa<FunctionTemplateDecl>(Specialized))
8577 EntityKind = 4;
8578 else if (isa<CXXMethodDecl>(Specialized))
8579 EntityKind = 5;
8580 else if (isa<VarDecl>(Specialized))
8581 EntityKind = 6;
8582 else if (isa<RecordDecl>(Specialized))
8583 EntityKind = 7;
8584 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8585 EntityKind = 8;
8586 else {
8587 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8588 << S.getLangOpts().CPlusPlus11;
8589 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8590 return true;
8591 }
8592
8593 // C++ [temp.expl.spec]p2:
8594 // An explicit specialization may be declared in any scope in which
8595 // the corresponding primary template may be defined.
8597 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8598 << Specialized;
8599 return true;
8600 }
8601
8602 // C++ [temp.class.spec]p6:
8603 // A class template partial specialization may be declared in any
8604 // scope in which the primary template may be defined.
8605 DeclContext *SpecializedContext =
8606 Specialized->getDeclContext()->getRedeclContext();
8608
8609 // Make sure that this redeclaration (or definition) occurs in the same
8610 // scope or an enclosing namespace.
8611 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8612 : DC->Equals(SpecializedContext))) {
8613 if (isa<TranslationUnitDecl>(SpecializedContext))
8614 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8615 << EntityKind << Specialized;
8616 else {
8617 auto *ND = cast<NamedDecl>(SpecializedContext);
8618 int Diag = diag::err_template_spec_redecl_out_of_scope;
8619 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8620 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8621 S.Diag(Loc, Diag) << EntityKind << Specialized
8622 << ND << isa<CXXRecordDecl>(ND);
8623 }
8624
8625 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8626
8627 // Don't allow specializing in the wrong class during error recovery.
8628 // Otherwise, things can go horribly wrong.
8629 if (DC->isRecord())
8630 return true;
8631 }
8632
8633 return false;
8634}
8635
8637 if (!E->isTypeDependent())
8638 return SourceLocation();
8639 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8640 Checker.TraverseStmt(E);
8641 if (Checker.MatchLoc.isInvalid())
8642 return E->getSourceRange();
8643 return Checker.MatchLoc;
8644}
8645
8646static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8647 if (!TL.getType()->isDependentType())
8648 return SourceLocation();
8649 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8650 Checker.TraverseTypeLoc(TL);
8651 if (Checker.MatchLoc.isInvalid())
8652 return TL.getSourceRange();
8653 return Checker.MatchLoc;
8654}
8655
8656/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8657/// that checks non-type template partial specialization arguments.
8659 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8660 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8661 bool HasError = false;
8662 for (unsigned I = 0; I != NumArgs; ++I) {
8663 if (Args[I].getKind() == TemplateArgument::Pack) {
8665 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8666 Args[I].pack_size(), IsDefaultArgument))
8667 return true;
8668
8669 continue;
8670 }
8671
8672 if (Args[I].getKind() != TemplateArgument::Expression)
8673 continue;
8674
8675 Expr *ArgExpr = Args[I].getAsExpr();
8676 if (ArgExpr->containsErrors()) {
8677 HasError = true;
8678 continue;
8679 }
8680
8681 // We can have a pack expansion of any of the bullets below.
8682 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8683 ArgExpr = Expansion->getPattern();
8684
8685 // Strip off any implicit casts we added as part of type checking.
8686 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8687 ArgExpr = ICE->getSubExpr();
8688
8689 // C++ [temp.class.spec]p8:
8690 // A non-type argument is non-specialized if it is the name of a
8691 // non-type parameter. All other non-type arguments are
8692 // specialized.
8693 //
8694 // Below, we check the two conditions that only apply to
8695 // specialized non-type arguments, so skip any non-specialized
8696 // arguments.
8697 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8698 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8699 continue;
8700
8701 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8702 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8703 continue;
8704 }
8705
8706 // C++ [temp.class.spec]p9:
8707 // Within the argument list of a class template partial
8708 // specialization, the following restrictions apply:
8709 // -- A partially specialized non-type argument expression
8710 // shall not involve a template parameter of the partial
8711 // specialization except when the argument expression is a
8712 // simple identifier.
8713 // -- The type of a template parameter corresponding to a
8714 // specialized non-type argument shall not be dependent on a
8715 // parameter of the specialization.
8716 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8717 // We implement a compromise between the original rules and DR1315:
8718 // -- A specialized non-type template argument shall not be
8719 // type-dependent and the corresponding template parameter
8720 // shall have a non-dependent type.
8721 SourceRange ParamUseRange =
8722 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8723 if (ParamUseRange.isValid()) {
8724 if (IsDefaultArgument) {
8725 S.Diag(TemplateNameLoc,
8726 diag::err_dependent_non_type_arg_in_partial_spec);
8727 S.Diag(ParamUseRange.getBegin(),
8728 diag::note_dependent_non_type_default_arg_in_partial_spec)
8729 << ParamUseRange;
8730 } else {
8731 S.Diag(ParamUseRange.getBegin(),
8732 diag::err_dependent_non_type_arg_in_partial_spec)
8733 << ParamUseRange;
8734 }
8735 return true;
8736 }
8737
8738 ParamUseRange = findTemplateParameter(
8739 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8740 if (ParamUseRange.isValid()) {
8741 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8742 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8743 << Param->getType();
8745 return true;
8746 }
8747 }
8748
8749 return HasError;
8750}
8751
8753 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8754 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8755 // We have to be conservative when checking a template in a dependent
8756 // context.
8757 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8758 return false;
8759
8760 TemplateParameterList *TemplateParams =
8761 PrimaryTemplate->getTemplateParameters();
8762 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8764 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8765 if (!Param)
8766 continue;
8767
8768 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8769 Param, &TemplateArgs[I],
8770 1, I >= NumExplicit))
8771 return true;
8772 }
8773
8774 return false;
8775}
8776
8778 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8779 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8781 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8782 assert(TUK != TagUseKind::Reference && "References are not specializations");
8783
8784 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8785 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8786 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8787
8788 // Find the class template we're specializing
8789 TemplateName Name = TemplateId.Template.get();
8791 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8792
8793 if (!ClassTemplate) {
8794 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8795 << (Name.getAsTemplateDecl() &&
8797 return true;
8798 }
8799
8800 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8801 auto Message = DSA->getMessage();
8802 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8803 << ClassTemplate << !Message.empty() << Message;
8804 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8805 }
8806
8807 if (S->isTemplateParamScope())
8808 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8809
8810 DeclContext *DC = ClassTemplate->getDeclContext();
8811
8812 bool isMemberSpecialization = false;
8813 bool isPartialSpecialization = false;
8814
8815 if (SS.isSet()) {
8816 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8817 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8818 TemplateNameLoc, &TemplateId,
8819 /*IsMemberSpecialization=*/false))
8820 return true;
8821 }
8822
8823 // Check the validity of the template headers that introduce this
8824 // template.
8825 // FIXME: We probably shouldn't complain about these headers for
8826 // friend declarations.
8827 bool Invalid = false;
8828 TemplateParameterList *TemplateParams =
8830 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8831 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8832 if (Invalid)
8833 return true;
8834
8835 // Check that we can declare a template specialization here.
8836 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8837 return true;
8838
8839 if (TemplateParams && DC->isDependentContext()) {
8840 ContextRAII SavedContext(*this, DC);
8842 return true;
8843 }
8844
8845 if (TemplateParams && TemplateParams->size() > 0) {
8846 isPartialSpecialization = true;
8847
8848 if (TUK == TagUseKind::Friend) {
8849 Diag(KWLoc, diag::err_partial_specialization_friend)
8850 << SourceRange(LAngleLoc, RAngleLoc);
8851 return true;
8852 }
8853
8854 // C++ [temp.class.spec]p10:
8855 // The template parameter list of a specialization shall not
8856 // contain default template argument values.
8857 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8858 Decl *Param = TemplateParams->getParam(I);
8859 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8860 if (TTP->hasDefaultArgument()) {
8861 Diag(TTP->getDefaultArgumentLoc(),
8862 diag::err_default_arg_in_partial_spec);
8863 TTP->removeDefaultArgument();
8864 }
8865 } else if (NonTypeTemplateParmDecl *NTTP
8866 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8867 if (NTTP->hasDefaultArgument()) {
8868 Diag(NTTP->getDefaultArgumentLoc(),
8869 diag::err_default_arg_in_partial_spec)
8870 << NTTP->getDefaultArgument().getSourceRange();
8871 NTTP->removeDefaultArgument();
8872 }
8873 } else {
8875 if (TTP->hasDefaultArgument()) {
8877 diag::err_default_arg_in_partial_spec)
8879 TTP->removeDefaultArgument();
8880 }
8881 }
8882 }
8883 } else if (TemplateParams) {
8884 if (TUK == TagUseKind::Friend)
8885 Diag(KWLoc, diag::err_template_spec_friend)
8887 SourceRange(TemplateParams->getTemplateLoc(),
8888 TemplateParams->getRAngleLoc()))
8889 << SourceRange(LAngleLoc, RAngleLoc);
8890 } else {
8891 assert(TUK == TagUseKind::Friend &&
8892 "should have a 'template<>' for this decl");
8893 }
8894
8895 // Check that the specialization uses the same tag kind as the
8896 // original template.
8898 assert(Kind != TagTypeKind::Enum &&
8899 "Invalid enum tag in class template spec!");
8900 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8901 TUK == TagUseKind::Definition, KWLoc,
8902 ClassTemplate->getIdentifier())) {
8903 Diag(KWLoc, diag::err_use_with_wrong_tag)
8904 << ClassTemplate
8906 ClassTemplate->getTemplatedDecl()->getKindName());
8907 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8908 diag::note_previous_use);
8909 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8910 }
8911
8912 // Translate the parser's template argument list in our AST format.
8913 TemplateArgumentListInfo TemplateArgs =
8914 makeTemplateArgumentListInfo(*this, TemplateId);
8915
8916 // Check for unexpanded parameter packs in any of the template arguments.
8917 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8918 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8919 isPartialSpecialization
8922 return true;
8923
8924 // Check that the template argument list is well-formed for this
8925 // template.
8927 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8928 /*DefaultArgs=*/{},
8929 /*PartialTemplateArgs=*/false, CTAI,
8930 /*UpdateArgsWithConversions=*/true))
8931 return true;
8932
8933 // Find the class template (partial) specialization declaration that
8934 // corresponds to these arguments.
8935 if (isPartialSpecialization) {
8937 TemplateArgs.size(),
8938 CTAI.CanonicalConverted))
8939 return true;
8940
8941 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8942 // also do it during instantiation.
8943 if (!Name.isDependent() &&
8944 !TemplateSpecializationType::anyDependentTemplateArguments(
8945 TemplateArgs, CTAI.CanonicalConverted)) {
8946 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8947 << ClassTemplate->getDeclName();
8948 isPartialSpecialization = false;
8949 Invalid = true;
8950 }
8951 }
8952
8953 void *InsertPos = nullptr;
8954 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8955
8956 if (isPartialSpecialization)
8957 PrevDecl = ClassTemplate->findPartialSpecialization(
8958 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8959 else
8960 PrevDecl =
8961 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8962
8964
8965 // Check whether we can declare a class template specialization in
8966 // the current scope.
8967 if (TUK != TagUseKind::Friend &&
8969 TemplateNameLoc,
8970 isPartialSpecialization))
8971 return true;
8972
8973 if (!isPartialSpecialization) {
8974 // Create a new class template specialization declaration node for
8975 // this explicit specialization or friend declaration.
8977 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8978 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8979 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8981 if (TemplateParameterLists.size() > 0) {
8982 Specialization->setTemplateParameterListsInfo(Context,
8983 TemplateParameterLists);
8984 }
8985
8986 if (!PrevDecl)
8987 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8988 } else {
8990 Context.getCanonicalTemplateSpecializationType(
8992 TemplateName(ClassTemplate->getCanonicalDecl()),
8993 CTAI.CanonicalConverted));
8994 if (Context.hasSameType(
8995 CanonType,
8996 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8997 (!Context.getLangOpts().CPlusPlus20 ||
8998 !TemplateParams->hasAssociatedConstraints())) {
8999 // C++ [temp.class.spec]p9b3:
9000 //
9001 // -- The argument list of the specialization shall not be identical
9002 // to the implicit argument list of the primary template.
9003 //
9004 // This rule has since been removed, because it's redundant given DR1495,
9005 // but we keep it because it produces better diagnostics and recovery.
9006 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9007 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9008 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9009 return CheckClassTemplate(
9010 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9011 TemplateNameLoc, Attr, TemplateParams, AS_none,
9012 /*ModulePrivateLoc=*/SourceLocation(),
9013 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9014 TemplateParameterLists.data(), isMemberSpecialization);
9015 }
9016
9017 // Create a new class template partial specialization declaration node.
9019 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9022 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9023 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9024 Partial->setTemplateArgsAsWritten(TemplateArgs);
9025 SetNestedNameSpecifier(*this, Partial, SS);
9026 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9028 Context, TemplateParameterLists.drop_back(1));
9029 }
9030
9031 if (!PrevPartial)
9032 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9033 Specialization = Partial;
9034
9035 // If we are providing an explicit specialization of a member class
9036 // template specialization, make a note of that.
9037 if (isMemberSpecialization)
9038 Partial->setMemberSpecialization();
9039
9041 }
9042
9043 // C++ [temp.expl.spec]p6:
9044 // If a template, a member template or the member of a class template is
9045 // explicitly specialized then that specialization shall be declared
9046 // before the first use of that specialization that would cause an implicit
9047 // instantiation to take place, in every translation unit in which such a
9048 // use occurs; no diagnostic is required.
9049 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9050 bool Okay = false;
9051 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9052 // Is there any previous explicit specialization declaration?
9054 Okay = true;
9055 break;
9056 }
9057 }
9058
9059 if (!Okay) {
9060 SourceRange Range(TemplateNameLoc, RAngleLoc);
9061 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9062 << Context.getCanonicalTagType(Specialization) << Range;
9063
9064 Diag(PrevDecl->getPointOfInstantiation(),
9065 diag::note_instantiation_required_here)
9066 << (PrevDecl->getTemplateSpecializationKind()
9068 return true;
9069 }
9070 }
9071
9072 // If this is not a friend, note that this is an explicit specialization.
9073 if (TUK != TagUseKind::Friend)
9074 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9075
9076 // Check that this isn't a redefinition of this specialization.
9077 if (TUK == TagUseKind::Definition) {
9078 RecordDecl *Def = Specialization->getDefinition();
9079 NamedDecl *Hidden = nullptr;
9080 bool HiddenDefVisible = false;
9081 if (Def && SkipBody &&
9082 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9083 SkipBody->ShouldSkip = true;
9084 SkipBody->Previous = Def;
9085 if (!HiddenDefVisible && Hidden)
9087 } else if (Def) {
9088 SourceRange Range(TemplateNameLoc, RAngleLoc);
9089 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9090 Diag(Def->getLocation(), diag::note_previous_definition);
9091 Specialization->setInvalidDecl();
9092 return true;
9093 }
9094 }
9095
9098
9099 // Add alignment attributes if necessary; these attributes are checked when
9100 // the ASTContext lays out the structure.
9101 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9102 if (LangOpts.HLSL)
9103 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9106 }
9107
9108 if (ModulePrivateLoc.isValid())
9109 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9110 << (isPartialSpecialization? 1 : 0)
9111 << FixItHint::CreateRemoval(ModulePrivateLoc);
9112
9113 // C++ [temp.expl.spec]p9:
9114 // A template explicit specialization is in the scope of the
9115 // namespace in which the template was defined.
9116 //
9117 // We actually implement this paragraph where we set the semantic
9118 // context (in the creation of the ClassTemplateSpecializationDecl),
9119 // but we also maintain the lexical context where the actual
9120 // definition occurs.
9121 Specialization->setLexicalDeclContext(CurContext);
9122
9123 // We may be starting the definition of this specialization.
9124 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9125 Specialization->startDefinition();
9126
9127 if (TUK == TagUseKind::Friend) {
9128 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9129 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9130 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9132 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9133 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9134
9135 // Build the fully-sugared type for this class template
9136 // specialization as the user wrote in the specialization
9137 // itself. This means that we'll pretty-print the type retrieved
9138 // from the specialization's declaration the way that the user
9139 // actually wrote the specialization, rather than formatting the
9140 // name based on the "canonical" representation used to store the
9141 // template arguments in the specialization.
9143 TemplateNameLoc,
9144 WrittenTy,
9145 /*FIXME:*/KWLoc);
9146 Friend->setAccess(AS_public);
9147 CurContext->addDecl(Friend);
9148 } else {
9149 // Add the specialization into its lexical context, so that it can
9150 // be seen when iterating through the list of declarations in that
9151 // context. However, specializations are not found by name lookup.
9152 CurContext->addDecl(Specialization);
9153 }
9154
9155 if (SkipBody && SkipBody->ShouldSkip)
9156 return SkipBody->Previous;
9157
9158 Specialization->setInvalidDecl(Invalid);
9160 return Specialization;
9161}
9162
9164 MultiTemplateParamsArg TemplateParameterLists,
9165 Declarator &D) {
9166 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9167 ActOnDocumentableDecl(NewDecl);
9168 return NewDecl;
9169}
9170
9172 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9173 const IdentifierInfo *Name, SourceLocation NameLoc) {
9174 DeclContext *DC = CurContext;
9175
9176 if (!DC->getRedeclContext()->isFileContext()) {
9177 Diag(NameLoc,
9178 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9179 return nullptr;
9180 }
9181
9182 if (TemplateParameterLists.size() > 1) {
9183 Diag(NameLoc, diag::err_concept_extra_headers);
9184 return nullptr;
9185 }
9186
9187 TemplateParameterList *Params = TemplateParameterLists.front();
9188
9189 if (Params->size() == 0) {
9190 Diag(NameLoc, diag::err_concept_no_parameters);
9191 return nullptr;
9192 }
9193
9194 // Ensure that the parameter pack, if present, is the last parameter in the
9195 // template.
9196 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9197 ParamEnd = Params->end();
9198 ParamIt != ParamEnd; ++ParamIt) {
9199 Decl const *Param = *ParamIt;
9200 if (Param->isParameterPack()) {
9201 if (++ParamIt == ParamEnd)
9202 break;
9203 Diag(Param->getLocation(),
9204 diag::err_template_param_pack_must_be_last_template_parameter);
9205 return nullptr;
9206 }
9207 }
9208
9209 ConceptDecl *NewDecl =
9210 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9211
9212 if (NewDecl->hasAssociatedConstraints()) {
9213 // C++2a [temp.concept]p4:
9214 // A concept shall not have associated constraints.
9215 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9216 NewDecl->setInvalidDecl();
9217 }
9218
9219 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9220 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9222 LookupName(Previous, S);
9223 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9224 /*AllowInlineNamespace*/ false);
9225
9226 // We cannot properly handle redeclarations until we parse the constraint
9227 // expression, so only inject the name if we are sure we are not redeclaring a
9228 // symbol
9229 if (Previous.empty())
9230 PushOnScopeChains(NewDecl, S, true);
9231
9232 return NewDecl;
9233}
9234
9236 bool Found = false;
9237 LookupResult::Filter F = R.makeFilter();
9238 while (F.hasNext()) {
9239 NamedDecl *D = F.next();
9240 if (D == C) {
9241 F.erase();
9242 Found = true;
9243 break;
9244 }
9245 }
9246 F.done();
9247 return Found;
9248}
9249
9252 Expr *ConstraintExpr,
9253 const ParsedAttributesView &Attrs) {
9254 assert(!C->hasDefinition() && "Concept already defined");
9255 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9256 C->setInvalidDecl();
9257 return nullptr;
9258 }
9259 C->setDefinition(ConstraintExpr);
9260 ProcessDeclAttributeList(S, C, Attrs);
9261
9262 // Check for conflicting previous declaration.
9263 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9264 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9266 LookupName(Previous, S);
9267 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9268 /*AllowInlineNamespace*/ false);
9269 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9270 bool AddToScope = true;
9271 CheckConceptRedefinition(C, Previous, AddToScope);
9272
9274 if (!WasAlreadyAdded && AddToScope)
9275 PushOnScopeChains(C, S);
9276
9277 return C;
9278}
9279
9281 LookupResult &Previous, bool &AddToScope) {
9282 AddToScope = true;
9283
9284 if (Previous.empty())
9285 return;
9286
9287 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9288 if (!OldConcept) {
9289 auto *Old = Previous.getRepresentativeDecl();
9290 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9291 << NewDecl->getDeclName();
9292 notePreviousDefinition(Old, NewDecl->getLocation());
9293 AddToScope = false;
9294 return;
9295 }
9296 // Check if we can merge with a concept declaration.
9297 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9298 if (!IsSame) {
9299 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9300 << NewDecl->getDeclName();
9301 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9302 AddToScope = false;
9303 return;
9304 }
9305 if (hasReachableDefinition(OldConcept) &&
9306 IsRedefinitionInModule(NewDecl, OldConcept)) {
9307 Diag(NewDecl->getLocation(), diag::err_redefinition)
9308 << NewDecl->getDeclName();
9309 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9310 AddToScope = false;
9311 return;
9312 }
9313 if (!Previous.isSingleResult()) {
9314 // FIXME: we should produce an error in case of ambig and failed lookups.
9315 // Other decls (e.g. namespaces) also have this shortcoming.
9316 return;
9317 }
9318 // We unwrap canonical decl late to check for module visibility.
9319 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9320}
9321
9323 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9324 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9325 Diag(Loc, diag::err_recursive_concept) << CE;
9326 Diag(CE->getLocation(), diag::note_declared_at);
9327 CE->setInvalidDecl();
9328 return true;
9329 }
9330 // Concept template parameters don't have a definition and can't
9331 // be defined recursively.
9332 return false;
9333}
9334
9335/// \brief Strips various properties off an implicit instantiation
9336/// that has just been explicitly specialized.
9337static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9338 if (MinGW || (isa<FunctionDecl>(D) &&
9339 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9340 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9341
9342 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9343 FD->setInlineSpecified(false);
9344}
9345
9346/// Create an ExplicitInstantiationDecl to record source-location info for an
9347/// explicit template instantiation statement, and add it to \p CurContext.
9348///
9349/// For class templates / nested classes, the caller should build a
9350/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9351/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9352///
9353/// For function / variable templates, the caller should pass TypeAsWritten for
9354/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9356 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9357 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9358 NestedNameSpecifierLoc QualifierLoc,
9359 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9360 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9362 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9363 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9364 Context.addExplicitInstantiationDecl(Spec, EID);
9365 CurContext->addDecl(EID);
9366}
9367
9368/// Compute the diagnostic location for an explicit instantiation
9369// declaration or definition.
9370static SourceLocation
9372 SourceLocation PointOfInstantiation) {
9373 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9374 if (EID->getTemplateSpecializationKind() ==
9376 return EID->getTemplateLoc();
9377
9378 // Explicit instantiations following a specialization have no effect and
9379 // hence no PointOfInstantiation. In that case, walk decl backwards
9380 // until a valid name loc is found.
9381 SourceLocation PrevDiagLoc = PointOfInstantiation;
9382 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9383 Prev = Prev->getPreviousDecl()) {
9384 PrevDiagLoc = Prev->getLocation();
9385 }
9386 assert(PrevDiagLoc.isValid() &&
9387 "Explicit instantiation without point of instantiation?");
9388 return PrevDiagLoc;
9389}
9390
9391bool
9394 NamedDecl *PrevDecl,
9396 SourceLocation PrevPointOfInstantiation,
9397 bool &HasNoEffect) {
9398 HasNoEffect = false;
9399
9400 switch (NewTSK) {
9401 case TSK_Undeclared:
9403 assert(
9404 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9405 "previous declaration must be implicit!");
9406 return false;
9407
9409 switch (PrevTSK) {
9410 case TSK_Undeclared:
9412 // Okay, we're just specializing something that is either already
9413 // explicitly specialized or has merely been mentioned without any
9414 // instantiation.
9415 return false;
9416
9418 if (PrevPointOfInstantiation.isInvalid()) {
9419 // The declaration itself has not actually been instantiated, so it is
9420 // still okay to specialize it.
9422 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9423 return false;
9424 }
9425 // Fall through
9426 [[fallthrough]];
9427
9430 assert((PrevTSK == TSK_ImplicitInstantiation ||
9431 PrevPointOfInstantiation.isValid()) &&
9432 "Explicit instantiation without point of instantiation?");
9433
9434 // C++ [temp.expl.spec]p6:
9435 // If a template, a member template or the member of a class template
9436 // is explicitly specialized then that specialization shall be declared
9437 // before the first use of that specialization that would cause an
9438 // implicit instantiation to take place, in every translation unit in
9439 // which such a use occurs; no diagnostic is required.
9440 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9441 // Is there any previous explicit specialization declaration?
9443 return false;
9444 }
9445
9446 Diag(NewLoc, diag::err_specialization_after_instantiation)
9447 << PrevDecl;
9448 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9449 << (PrevTSK != TSK_ImplicitInstantiation);
9450
9451 return true;
9452 }
9453 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9454
9456 switch (PrevTSK) {
9458 // This explicit instantiation declaration is redundant (that's okay).
9459 HasNoEffect = true;
9460 return false;
9461
9462 case TSK_Undeclared:
9464 // We're explicitly instantiating something that may have already been
9465 // implicitly instantiated; that's fine.
9466 return false;
9467
9469 // C++0x [temp.explicit]p4:
9470 // For a given set of template parameters, if an explicit instantiation
9471 // of a template appears after a declaration of an explicit
9472 // specialization for that template, the explicit instantiation has no
9473 // effect.
9474 HasNoEffect = true;
9475 return false;
9476
9478 // C++0x [temp.explicit]p10:
9479 // If an entity is the subject of both an explicit instantiation
9480 // declaration and an explicit instantiation definition in the same
9481 // translation unit, the definition shall follow the declaration.
9482 Diag(NewLoc,
9483 diag::err_explicit_instantiation_declaration_after_definition);
9484
9485 // Explicit instantiations following a specialization have no effect and
9486 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9487 // until a valid name loc is found.
9488 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9489 diag::note_explicit_instantiation_definition_here);
9490 HasNoEffect = true;
9491 return false;
9492 }
9493 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9494
9496 switch (PrevTSK) {
9497 case TSK_Undeclared:
9499 // We're explicitly instantiating something that may have already been
9500 // implicitly instantiated; that's fine.
9501 return false;
9502
9504 // C++ DR 259, C++0x [temp.explicit]p4:
9505 // For a given set of template parameters, if an explicit
9506 // instantiation of a template appears after a declaration of
9507 // an explicit specialization for that template, the explicit
9508 // instantiation has no effect.
9509 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9510 << PrevDecl;
9511 Diag(PrevDecl->getLocation(),
9512 diag::note_previous_template_specialization);
9513 HasNoEffect = true;
9514 return false;
9515
9517 // We're explicitly instantiating a definition for something for which we
9518 // were previously asked to suppress instantiations. That's fine.
9519
9520 // C++0x [temp.explicit]p4:
9521 // For a given set of template parameters, if an explicit instantiation
9522 // of a template appears after a declaration of an explicit
9523 // specialization for that template, the explicit instantiation has no
9524 // effect.
9525 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9526 // Is there any previous explicit specialization declaration?
9528 HasNoEffect = true;
9529 break;
9530 }
9531 }
9532
9533 return false;
9534
9536 // C++0x [temp.spec]p5:
9537 // For a given template and a given set of template-arguments,
9538 // - an explicit instantiation definition shall appear at most once
9539 // in a program,
9540
9541 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9542 Diag(NewLoc, (getLangOpts().MSVCCompat)
9543 ? diag::ext_explicit_instantiation_duplicate
9544 : diag::err_explicit_instantiation_duplicate)
9545 << PrevDecl;
9546 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9547 diag::note_previous_explicit_instantiation);
9548 HasNoEffect = true;
9549 return false;
9550 }
9551 }
9552
9553 llvm_unreachable("Missing specialization/instantiation case?");
9554}
9555
9557 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9559 // Remove anything from Previous that isn't a function template in
9560 // the correct context.
9561 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9562 LookupResult::Filter F = Previous.makeFilter();
9563 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9564 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9565 while (F.hasNext()) {
9566 NamedDecl *D = F.next()->getUnderlyingDecl();
9567 if (!isa<FunctionTemplateDecl>(D)) {
9568 F.erase();
9569 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9570 continue;
9571 }
9572
9573 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9575 F.erase();
9576 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9577 continue;
9578 }
9579 }
9580 F.done();
9581
9582 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9583 if (Previous.empty()) {
9584 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9585 << IsFriend;
9586 for (auto &P : DiscardedCandidates)
9587 Diag(P.second->getLocation(),
9588 diag::note_dependent_function_template_spec_discard_reason)
9589 << P.first << IsFriend;
9590 return true;
9591 }
9592
9594 ExplicitTemplateArgs);
9595 return false;
9596}
9597
9599 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9600 LookupResult &Previous, bool QualifiedFriend) {
9601 // The set of function template specializations that could match this
9602 // explicit function template specialization.
9603 UnresolvedSet<8> Candidates;
9604 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9605 /*ForTakingAddress=*/false);
9606
9607 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9608 ConvertedTemplateArgs;
9609
9610 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9611 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9612 I != E; ++I) {
9613 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9614 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9615 // Only consider templates found within the same semantic lookup scope as
9616 // FD.
9617 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9619 continue;
9620
9621 QualType FT = FD->getType();
9622 // C++11 [dcl.constexpr]p8:
9623 // A constexpr specifier for a non-static member function that is not
9624 // a constructor declares that member function to be const.
9625 //
9626 // When matching a constexpr member function template specialization
9627 // against the primary template, we don't yet know whether the
9628 // specialization has an implicit 'const' (because we don't know whether
9629 // it will be a static member function until we know which template it
9630 // specializes). This rule was removed in C++14.
9631 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9632 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9634 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9635 if (OldMD && OldMD->isConst()) {
9636 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9638 EPI.TypeQuals.addConst();
9639 FT = Context.getFunctionType(FPT->getReturnType(),
9640 FPT->getParamTypes(), EPI);
9641 }
9642 }
9643
9645 if (ExplicitTemplateArgs)
9646 Args = *ExplicitTemplateArgs;
9647
9648 // C++ [temp.expl.spec]p11:
9649 // A trailing template-argument can be left unspecified in the
9650 // template-id naming an explicit function template specialization
9651 // provided it can be deduced from the function argument type.
9652 // Perform template argument deduction to determine whether we may be
9653 // specializing this template.
9654 // FIXME: It is somewhat wasteful to build
9655 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9656 FunctionDecl *Specialization = nullptr;
9658 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9659 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9661 // Template argument deduction failed; record why it failed, so
9662 // that we can provide nifty diagnostics.
9663 FailedCandidates.addCandidate().set(
9664 I.getPair(), FunTmpl->getTemplatedDecl(),
9665 MakeDeductionFailureInfo(Context, TDK, Info));
9666 (void)TDK;
9667 continue;
9668 }
9669
9670 // Target attributes are part of the cuda function signature, so
9671 // the deduced template's cuda target must match that of the
9672 // specialization. Given that C++ template deduction does not
9673 // take target attributes into account, we reject candidates
9674 // here that have a different target.
9675 if (LangOpts.CUDA &&
9676 CUDA().IdentifyTarget(Specialization,
9677 /* IgnoreImplicitHDAttr = */ true) !=
9678 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9679 FailedCandidates.addCandidate().set(
9680 I.getPair(), FunTmpl->getTemplatedDecl(),
9683 continue;
9684 }
9685
9686 // Record this candidate.
9687 if (ExplicitTemplateArgs)
9688 ConvertedTemplateArgs[Specialization] = std::move(Args);
9689 Candidates.addDecl(Specialization, I.getAccess());
9690 }
9691 }
9692
9693 // For a qualified friend declaration (with no explicit marker to indicate
9694 // that a template specialization was intended), note all (template and
9695 // non-template) candidates.
9696 if (QualifiedFriend && Candidates.empty()) {
9697 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9698 << FD->getDeclName() << FDLookupContext;
9699 // FIXME: We should form a single candidate list and diagnose all
9700 // candidates at once, to get proper sorting and limiting.
9701 for (auto *OldND : Previous) {
9702 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9703 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9704 }
9705 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9706 return true;
9707 }
9708
9709 // Find the most specialized function template.
9711 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9712 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9713 PDiag(diag::err_function_template_spec_ambiguous)
9714 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9715 PDiag(diag::note_function_template_spec_matched));
9716
9717 if (Result == Candidates.end())
9718 return true;
9719
9720 // Ignore access information; it doesn't figure into redeclaration checking.
9722
9723 if (const auto *PT = Specialization->getPrimaryTemplate();
9724 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9725 auto Message = DSA->getMessage();
9726 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9727 << PT << !Message.empty() << Message;
9728 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9729 }
9730
9731 // C++23 [except.spec]p13:
9732 // An exception specification is considered to be needed when:
9733 // - [...]
9734 // - the exception specification is compared to that of another declaration
9735 // (e.g., an explicit specialization or an overriding virtual function);
9736 // - [...]
9737 //
9738 // The exception specification of a defaulted function is evaluated as
9739 // described above only when needed; similarly, the noexcept-specifier of a
9740 // specialization of a function template or member function of a class
9741 // template is instantiated only when needed.
9742 //
9743 // The standard doesn't specify what the "comparison with another declaration"
9744 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9745 // not state which properties of an explicit specialization must match the
9746 // primary template.
9747 //
9748 // We assume that an explicit specialization must correspond with (per
9749 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9750 // the declaration produced by substitution into the function template.
9751 //
9752 // Since the determination whether two function declarations correspond does
9753 // not consider exception specification, we only need to instantiate it once
9754 // we determine the primary template when comparing types per
9755 // [basic.link]p11.1.
9756 auto *SpecializationFPT =
9757 Specialization->getType()->castAs<FunctionProtoType>();
9758 // If the function has a dependent exception specification, resolve it after
9759 // we have selected the primary template so we can check whether it matches.
9760 if (getLangOpts().CPlusPlus17 &&
9761 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9762 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9763 return true;
9764
9766 = Specialization->getTemplateSpecializationInfo();
9767 assert(SpecInfo && "Function template specialization info missing?");
9768
9769 // Note: do not overwrite location info if previous template
9770 // specialization kind was explicit.
9772 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9773 Specialization->setLocation(FD->getLocation());
9774 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9775 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9776 // function can differ from the template declaration with respect to
9777 // the constexpr specifier.
9778 // FIXME: We need an update record for this AST mutation.
9779 // FIXME: What if there are multiple such prior declarations (for instance,
9780 // from different modules)?
9781 Specialization->setConstexprKind(FD->getConstexprKind());
9782 }
9783
9784 // FIXME: Check if the prior specialization has a point of instantiation.
9785 // If so, we have run afoul of .
9786
9787 // If this is a friend declaration, then we're not really declaring
9788 // an explicit specialization.
9789 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9790
9791 // Check the scope of this explicit specialization.
9792 if (!isFriend &&
9794 Specialization->getPrimaryTemplate(),
9796 false))
9797 return true;
9798
9799 // C++ [temp.expl.spec]p6:
9800 // If a template, a member template or the member of a class template is
9801 // explicitly specialized then that specialization shall be declared
9802 // before the first use of that specialization that would cause an implicit
9803 // instantiation to take place, in every translation unit in which such a
9804 // use occurs; no diagnostic is required.
9805 bool HasNoEffect = false;
9806 if (!isFriend &&
9811 SpecInfo->getPointOfInstantiation(),
9812 HasNoEffect))
9813 return true;
9814
9815 // Mark the prior declaration as an explicit specialization, so that later
9816 // clients know that this is an explicit specialization.
9817 // A dependent friend specialization which has a definition should be treated
9818 // as explicit specialization, despite being invalid.
9819 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9820 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9821 // Since explicit specializations do not inherit '=delete' from their
9822 // primary function template - check if the 'specialization' that was
9823 // implicitly generated (during template argument deduction for partial
9824 // ordering) from the most specialized of all the function templates that
9825 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9826 // first check that it was implicitly generated during template argument
9827 // deduction by making sure it wasn't referenced, and then reset the deleted
9828 // flag to not-deleted, so that we can inherit that information from 'FD'.
9829 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9830 !Specialization->getCanonicalDecl()->isReferenced()) {
9831 // FIXME: This assert will not hold in the presence of modules.
9832 assert(
9833 Specialization->getCanonicalDecl() == Specialization &&
9834 "This must be the only existing declaration of this specialization");
9835 // FIXME: We need an update record for this AST mutation.
9836 Specialization->setDeletedAsWritten(false);
9837 }
9838 // FIXME: We need an update record for this AST mutation.
9841 }
9842
9843 // Turn the given function declaration into a function template
9844 // specialization, with the template arguments from the previous
9845 // specialization.
9846 // Take copies of (semantic and syntactic) template argument lists.
9848 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9849 FD->setFunctionTemplateSpecialization(
9850 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9852 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9853
9854 // A function template specialization inherits the target attributes
9855 // of its template. (We require the attributes explicitly in the
9856 // code to match, but a template may have implicit attributes by
9857 // virtue e.g. of being constexpr, and it passes these implicit
9858 // attributes on to its specializations.)
9859 if (LangOpts.CUDA)
9860 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9861
9862 // The "previous declaration" for this function template specialization is
9863 // the prior function template specialization.
9864 Previous.clear();
9865 Previous.addDecl(Specialization);
9866 return false;
9867}
9868
9869bool
9871 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9872 "Only for non-template members");
9873
9874 // Try to find the member we are instantiating.
9875 NamedDecl *FoundInstantiation = nullptr;
9876 NamedDecl *Instantiation = nullptr;
9877 NamedDecl *InstantiatedFrom = nullptr;
9878 MemberSpecializationInfo *MSInfo = nullptr;
9879
9880 if (Previous.empty()) {
9881 // Nowhere to look anyway.
9882 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9883 UnresolvedSet<8> Candidates;
9884 for (NamedDecl *Candidate : Previous) {
9885 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9886 // Ignore any candidates that aren't member functions.
9887 if (!Method)
9888 continue;
9889
9890 QualType Adjusted = Function->getType();
9891 if (!hasExplicitCallingConv(Adjusted))
9892 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9893 // Ignore any candidates with the wrong type.
9894 // This doesn't handle deduced return types, but both function
9895 // declarations should be undeduced at this point.
9896 // FIXME: The exception specification should probably be ignored when
9897 // comparing the types.
9898 if (!Context.hasSameType(Adjusted, Method->getType()))
9899 continue;
9900
9901 // Ignore any candidates with unsatisfied constraints.
9902 if (ConstraintSatisfaction Satisfaction;
9903 Method->getTrailingRequiresClause() &&
9904 (CheckFunctionConstraints(Method, Satisfaction,
9905 /*UsageLoc=*/Member->getLocation(),
9906 /*ForOverloadResolution=*/true) ||
9907 !Satisfaction.IsSatisfied))
9908 continue;
9909
9910 Candidates.addDecl(Candidate);
9911 }
9912
9913 // If we have no viable candidates left after filtering, we are done.
9914 if (Candidates.empty())
9915 return false;
9916
9917 // Find the function that is more constrained than every other function it
9918 // has been compared to.
9919 UnresolvedSetIterator Best = Candidates.begin();
9920 CXXMethodDecl *BestMethod = nullptr;
9921 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9922 I != E; ++I) {
9923 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9924 if (I == Best ||
9925 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9926 Best = I;
9927 BestMethod = Method;
9928 }
9929 }
9930
9931 FoundInstantiation = *Best;
9932 Instantiation = BestMethod;
9933 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9934 MSInfo = BestMethod->getMemberSpecializationInfo();
9935
9936 // Make sure the best candidate is more constrained than all of the others.
9937 bool Ambiguous = false;
9938 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9939 I != E; ++I) {
9940 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9941 if (I != Best &&
9942 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9943 Ambiguous = true;
9944 break;
9945 }
9946 }
9947
9948 if (Ambiguous) {
9949 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9950 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9951 for (NamedDecl *Candidate : Candidates) {
9952 Candidate = Candidate->getUnderlyingDecl();
9953 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9954 << Candidate;
9955 }
9956 return true;
9957 }
9958 } else if (isa<VarDecl>(Member)) {
9959 VarDecl *PrevVar;
9960 if (Previous.isSingleResult() &&
9961 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9962 if (PrevVar->isStaticDataMember()) {
9963 FoundInstantiation = Previous.getRepresentativeDecl();
9964 Instantiation = PrevVar;
9965 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9966 MSInfo = PrevVar->getMemberSpecializationInfo();
9967 }
9968 } else if (isa<RecordDecl>(Member)) {
9969 CXXRecordDecl *PrevRecord;
9970 if (Previous.isSingleResult() &&
9971 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9972 FoundInstantiation = Previous.getRepresentativeDecl();
9973 Instantiation = PrevRecord;
9974 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9975 MSInfo = PrevRecord->getMemberSpecializationInfo();
9976 }
9977 } else if (isa<EnumDecl>(Member)) {
9978 EnumDecl *PrevEnum;
9979 if (Previous.isSingleResult() &&
9980 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9981 FoundInstantiation = Previous.getRepresentativeDecl();
9982 Instantiation = PrevEnum;
9983 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9984 MSInfo = PrevEnum->getMemberSpecializationInfo();
9985 }
9986 }
9987
9988 if (!Instantiation) {
9989 // There is no previous declaration that matches. Since member
9990 // specializations are always out-of-line, the caller will complain about
9991 // this mismatch later.
9992 return false;
9993 }
9994
9995 // A member specialization in a friend declaration isn't really declaring
9996 // an explicit specialization, just identifying a specific (possibly implicit)
9997 // specialization. Don't change the template specialization kind.
9998 //
9999 // FIXME: Is this really valid? Other compilers reject.
10000 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10001 // Preserve instantiation information.
10002 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10003 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10004 cast<CXXMethodDecl>(InstantiatedFrom),
10006 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10007 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10008 cast<CXXRecordDecl>(InstantiatedFrom),
10010 }
10011
10012 Previous.clear();
10013 Previous.addDecl(FoundInstantiation);
10014 return false;
10015 }
10016
10017 // Make sure that this is a specialization of a member.
10018 if (!InstantiatedFrom) {
10019 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10020 << Member;
10021 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10022 return true;
10023 }
10024
10025 // C++ [temp.expl.spec]p6:
10026 // If a template, a member template or the member of a class template is
10027 // explicitly specialized then that specialization shall be declared
10028 // before the first use of that specialization that would cause an implicit
10029 // instantiation to take place, in every translation unit in which such a
10030 // use occurs; no diagnostic is required.
10031 assert(MSInfo && "Member specialization info missing?");
10032
10033 bool HasNoEffect = false;
10036 Instantiation,
10038 MSInfo->getPointOfInstantiation(),
10039 HasNoEffect))
10040 return true;
10041
10042 // Check the scope of this explicit specialization.
10044 InstantiatedFrom,
10045 Instantiation, Member->getLocation(),
10046 false))
10047 return true;
10048
10049 // Note that this member specialization is an "instantiation of" the
10050 // corresponding member of the original template.
10051 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10052 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10053 if (InstantiationFunction->getTemplateSpecializationKind() ==
10055 // Explicit specializations of member functions of class templates do not
10056 // inherit '=delete' from the member function they are specializing.
10057 if (InstantiationFunction->isDeleted()) {
10058 // FIXME: This assert will not hold in the presence of modules.
10059 assert(InstantiationFunction->getCanonicalDecl() ==
10060 InstantiationFunction);
10061 // FIXME: We need an update record for this AST mutation.
10062 InstantiationFunction->setDeletedAsWritten(false);
10063 }
10064 }
10065
10066 MemberFunction->setInstantiationOfMemberFunction(
10068 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10069 MemberVar->setInstantiationOfStaticDataMember(
10070 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10071 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10072 MemberClass->setInstantiationOfMemberClass(
10074 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10075 MemberEnum->setInstantiationOfMemberEnum(
10076 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10077 } else {
10078 llvm_unreachable("unknown member specialization kind");
10079 }
10080
10081 // Save the caller the trouble of having to figure out which declaration
10082 // this specialization matches.
10083 Previous.clear();
10084 Previous.addDecl(FoundInstantiation);
10085 return false;
10086}
10087
10088/// Complete the explicit specialization of a member of a class template by
10089/// updating the instantiated member to be marked as an explicit specialization.
10090///
10091/// \param OrigD The member declaration instantiated from the template.
10092/// \param Loc The location of the explicit specialization of the member.
10093template<typename DeclT>
10094static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10095 SourceLocation Loc) {
10096 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10097 return;
10098
10099 // FIXME: Inform AST mutation listeners of this AST mutation.
10100 // FIXME: If there are multiple in-class declarations of the member (from
10101 // multiple modules, or a declaration and later definition of a member type),
10102 // should we update all of them?
10103 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10104 OrigD->setLocation(Loc);
10105}
10106
10109 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10110 if (Instantiation == Member)
10111 return;
10112
10113 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10114 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10115 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10116 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10117 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10118 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10119 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10120 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10121 else
10122 llvm_unreachable("unknown member specialization kind");
10123}
10124
10125/// Check the scope of an explicit instantiation.
10126///
10127/// \returns true if a serious error occurs, false otherwise.
10129 SourceLocation InstLoc,
10130 bool WasQualifiedName) {
10132 DeclContext *CurContext = S.CurContext->getRedeclContext();
10133
10134 if (CurContext->isRecord()) {
10135 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10136 << D;
10137 return true;
10138 }
10139
10140 // C++11 [temp.explicit]p3:
10141 // An explicit instantiation shall appear in an enclosing namespace of its
10142 // template. If the name declared in the explicit instantiation is an
10143 // unqualified name, the explicit instantiation shall appear in the
10144 // namespace where its template is declared or, if that namespace is inline
10145 // (7.3.1), any namespace from its enclosing namespace set.
10146 //
10147 // This is DR275, which we do not retroactively apply to C++98/03.
10148 if (WasQualifiedName) {
10149 if (CurContext->Encloses(OrigContext))
10150 return false;
10151 } else {
10152 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10153 return false;
10154 }
10155
10156 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10157 if (WasQualifiedName)
10158 S.Diag(InstLoc,
10159 S.getLangOpts().CPlusPlus11?
10160 diag::err_explicit_instantiation_out_of_scope :
10161 diag::warn_explicit_instantiation_out_of_scope_0x)
10162 << D << NS;
10163 else
10164 S.Diag(InstLoc,
10165 S.getLangOpts().CPlusPlus11?
10166 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10167 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10168 << D << NS;
10169 } else
10170 S.Diag(InstLoc,
10171 S.getLangOpts().CPlusPlus11?
10172 diag::err_explicit_instantiation_must_be_global :
10173 diag::warn_explicit_instantiation_must_be_global_0x)
10174 << D;
10175 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10176 return false;
10177}
10178
10179/// Common checks for whether an explicit instantiation of \p D is valid.
10181 SourceLocation InstLoc,
10182 bool WasQualifiedName,
10184 // C++ [temp.explicit]p13:
10185 // An explicit instantiation declaration shall not name a specialization of
10186 // a template with internal linkage.
10189 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10190 return true;
10191 }
10192
10193 // C++11 [temp.explicit]p3: [DR 275]
10194 // An explicit instantiation shall appear in an enclosing namespace of its
10195 // template.
10196 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10197 return true;
10198
10199 return false;
10200}
10201
10202/// Determine whether the given scope specifier has a template-id in it.
10204 // C++11 [temp.explicit]p3:
10205 // If the explicit instantiation is for a member function, a member class
10206 // or a static data member of a class template specialization, the name of
10207 // the class template specialization in the qualified-id for the member
10208 // name shall be a simple-template-id.
10209 //
10210 // C++98 has the same restriction, just worded differently.
10211 for (NestedNameSpecifier NNS = SS.getScopeRep();
10213 /**/) {
10214 const Type *T = NNS.getAsType();
10216 return true;
10217 NNS = T->getPrefix();
10218 }
10219 return false;
10220}
10221
10222/// Make a dllexport or dllimport attr on a class template specialization take
10223/// effect.
10226 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10227 assert(A && "dllExportImportClassTemplateSpecialization called "
10228 "on Def without dllexport or dllimport");
10229
10230 // We reject explicit instantiations in class scope, so there should
10231 // never be any delayed exported classes to worry about.
10232 assert(S.DelayedDllExportClasses.empty() &&
10233 "delayed exports present at explicit instantiation");
10235
10236 // Propagate attribute to base class templates.
10237 for (auto &B : Def->bases()) {
10238 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10239 B.getType()->getAsCXXRecordDecl()))
10241 }
10242
10244}
10245
10247 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10248 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10249 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10250 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10251 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10252 // Find the class template we're specializing
10253 TemplateName Name = TemplateD.get();
10254 TemplateDecl *TD = Name.getAsTemplateDecl();
10255 // Check that the specialization uses the same tag kind as the
10256 // original template.
10258 assert(Kind != TagTypeKind::Enum &&
10259 "Invalid enum tag in class template explicit instantiation!");
10260
10261 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10262
10263 if (!ClassTemplate) {
10264 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10265 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10266 Diag(TD->getLocation(), diag::note_previous_use);
10267 return true;
10268 }
10269
10270 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10271 Kind, /*isDefinition*/false, KWLoc,
10272 ClassTemplate->getIdentifier())) {
10273 Diag(KWLoc, diag::err_use_with_wrong_tag)
10274 << ClassTemplate
10276 ClassTemplate->getTemplatedDecl()->getKindName());
10277 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10278 diag::note_previous_use);
10279 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10280 }
10281
10282 // C++0x [temp.explicit]p2:
10283 // There are two forms of explicit instantiation: an explicit instantiation
10284 // definition and an explicit instantiation declaration. An explicit
10285 // instantiation declaration begins with the extern keyword. [...]
10286 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10289
10291 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10292 // Check for dllexport class template instantiation declarations,
10293 // except for MinGW mode.
10294 for (const ParsedAttr &AL : Attr) {
10295 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10296 Diag(ExternLoc,
10297 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10298 Diag(AL.getLoc(), diag::note_attribute);
10299 break;
10300 }
10301 }
10302
10303 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10304 Diag(ExternLoc,
10305 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10306 Diag(A->getLocation(), diag::note_attribute);
10307 }
10308 }
10309
10310 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10311 // instantiation declarations for most purposes.
10312 bool DLLImportExplicitInstantiationDef = false;
10314 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10315 // Check for dllimport class template instantiation definitions.
10316 bool DLLImport =
10317 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10318 for (const ParsedAttr &AL : Attr) {
10319 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10320 DLLImport = true;
10321 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10322 // dllexport trumps dllimport here.
10323 DLLImport = false;
10324 break;
10325 }
10326 }
10327 if (DLLImport) {
10329 DLLImportExplicitInstantiationDef = true;
10330 }
10331 }
10332
10333 // Translate the parser's template argument list in our AST format.
10334 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10335 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10336
10337 // Check that the template argument list is well-formed for this
10338 // template.
10340 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10341 /*DefaultArgs=*/{}, false, CTAI,
10342 /*UpdateArgsWithConversions=*/true,
10343 /*ConstraintsNotSatisfied=*/nullptr))
10344 return true;
10345
10346 // Find the class template specialization declaration that
10347 // corresponds to these arguments.
10348 void *InsertPos = nullptr;
10350 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10351
10352 TemplateSpecializationKind PrevDecl_TSK
10353 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10354
10355 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10356 Context.getTargetInfo().getTriple().isOSCygMing()) {
10357 // Check for dllexport class template instantiation definitions in MinGW
10358 // mode, if a previous declaration of the instantiation was seen.
10359 for (const ParsedAttr &AL : Attr) {
10360 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10361 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10362 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10363 } else {
10364 Diag(AL.getLoc(),
10365 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10366 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10367 }
10368 break;
10369 }
10370 }
10371 }
10372
10373 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10374 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10375 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10376 return AL.getKind() == ParsedAttr::AT_DLLExport;
10377 })) {
10378 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10379 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10380 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10381 }
10382 }
10383
10384 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10385 SS.isSet(), TSK))
10386 return true;
10387
10389
10390 bool HasNoEffect = false;
10391 if (PrevDecl) {
10392 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10393 PrevDecl, PrevDecl_TSK,
10394 PrevDecl->getPointOfInstantiation(),
10395 HasNoEffect))
10396 return PrevDecl;
10397
10398 // Even though HasNoEffect == true means that this explicit instantiation
10399 // has no effect on semantics, we go on to put its syntax in the AST.
10400
10401 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10402 PrevDecl_TSK == TSK_Undeclared) {
10403 // Since the only prior class template specialization with these
10404 // arguments was referenced but not declared, reuse that
10405 // declaration node as our own, updating the source location
10406 // for the template name to reflect our new declaration.
10407 // (Other source locations will be updated later.)
10408 Specialization = PrevDecl;
10409 Specialization->setLocation(TemplateNameLoc);
10410 PrevDecl = nullptr;
10411 }
10412
10413 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10414 DLLImportExplicitInstantiationDef) {
10415 // The new specialization might add a dllimport attribute.
10416 HasNoEffect = false;
10417 }
10418 }
10419
10420 if (!Specialization) {
10421 // Create a new class template specialization declaration node for
10422 // this explicit specialization.
10424 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10425 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10427
10428 // A MSInheritanceAttr attached to the previous declaration must be
10429 // propagated to the new node prior to instantiation.
10430 if (PrevDecl) {
10431 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10432 auto *Clone = A->clone(getASTContext());
10433 Clone->setInherited(true);
10434 Specialization->addAttr(Clone);
10435 Consumer.AssignInheritanceModel(Specialization);
10436 }
10437 }
10438
10439 if (!HasNoEffect && !PrevDecl) {
10440 // Insert the new specialization.
10441 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10442 }
10443 }
10444
10445 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10446
10447 // Set source locations for keywords.
10448 Specialization->setExternKeywordLoc(ExternLoc);
10449 Specialization->setTemplateKeywordLoc(TemplateLoc);
10450 Specialization->setBraceRange(SourceRange());
10451
10452 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10455
10456 // Add the explicit instantiation into its lexical context. However,
10457 // since explicit instantiations are never found by name lookup, we
10458 // just put it into the declaration context directly.
10459 Specialization->setLexicalDeclContext(CurContext);
10460 CurContext->addDecl(Specialization);
10461
10462 // Syntax is now OK, so return if it has no other effect on semantics.
10463 if (HasNoEffect) {
10464 // Set the template specialization kind.
10465 Specialization->setTemplateSpecializationKind(TSK);
10466
10468 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10469 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10470 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10471 Context.getCanonicalTagType(Specialization));
10473 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10474 TemplateNameLoc, TSI, TSK);
10475 return Specialization;
10476 }
10477
10478 // C++ [temp.explicit]p3:
10479 // A definition of a class template or class member template
10480 // shall be in scope at the point of the explicit instantiation of
10481 // the class template or class member template.
10482 //
10483 // This check comes when we actually try to perform the
10484 // instantiation.
10486 = cast_or_null<ClassTemplateSpecializationDecl>(
10487 Specialization->getDefinition());
10488 if (!Def)
10490 /*Complain=*/true,
10491 CTAI.StrictPackMatch);
10492 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10493 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10494 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10495 }
10496
10497 // Instantiate the members of this class template specialization.
10498 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10499 Specialization->getDefinition());
10500 if (Def) {
10502 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10503 // TSK_ExplicitInstantiationDefinition
10504 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10506 DLLImportExplicitInstantiationDef)) {
10507 // FIXME: Need to notify the ASTMutationListener that we did this.
10509
10510 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10511 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10512 // An explicit instantiation definition can add a dll attribute to a
10513 // template with a previous instantiation declaration. MinGW doesn't
10514 // allow this.
10515 auto *A = cast<InheritableAttr>(
10517 A->setInherited(true);
10518 Def->addAttr(A);
10520 }
10521 }
10522
10523 // Fix a TSK_ImplicitInstantiation followed by a
10524 // TSK_ExplicitInstantiationDefinition
10525 bool NewlyDLLExported =
10526 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10527 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10528 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10529 // An explicit instantiation definition can add a dll attribute to a
10530 // template with a previous implicit instantiation. MinGW doesn't allow
10531 // this. We limit clang to only adding dllexport, to avoid potentially
10532 // strange codegen behavior. For example, if we extend this conditional
10533 // to dllimport, and we have a source file calling a method on an
10534 // implicitly instantiated template class instance and then declaring a
10535 // dllimport explicit instantiation definition for the same template
10536 // class, the codegen for the method call will not respect the dllimport,
10537 // while it will with cl. The Def will already have the DLL attribute,
10538 // since the Def and Specialization will be the same in the case of
10539 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10540 // attribute to the Specialization; we just need to make it take effect.
10541 assert(Def == Specialization &&
10542 "Def and Specialization should match for implicit instantiation");
10544 }
10545
10546 // In MinGW mode, export the template instantiation if the declaration
10547 // was marked dllexport.
10548 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10549 Context.getTargetInfo().getTriple().isOSCygMing() &&
10550 PrevDecl->hasAttr<DLLExportAttr>()) {
10552 }
10553
10554 // Set the template specialization kind. Make sure it is set before
10555 // instantiating the members which will trigger ASTConsumer callbacks.
10556 Specialization->setTemplateSpecializationKind(TSK);
10557 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10558 } else {
10559
10560 // Set the template specialization kind.
10561 Specialization->setTemplateSpecializationKind(TSK);
10562 }
10563
10565 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10566 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10567 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10568 Context.getCanonicalTagType(Specialization));
10570 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10571 TemplateNameLoc, TSI, TSK);
10572 return Specialization;
10573}
10574
10577 SourceLocation TemplateLoc, unsigned TagSpec,
10578 SourceLocation KWLoc, CXXScopeSpec &SS,
10579 IdentifierInfo *Name, SourceLocation NameLoc,
10580 const ParsedAttributesView &Attr) {
10581
10582 bool Owned = false;
10583 bool IsDependent = false;
10584 Decl *TagD =
10585 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10586 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10587 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10588 false, TypeResult(), /*IsTypeSpecifier*/ false,
10589 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10590 .get();
10591 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10592
10593 if (!TagD)
10594 return true;
10595
10596 TagDecl *Tag = cast<TagDecl>(TagD);
10597 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10598
10599 if (Tag->isInvalidDecl())
10600 return true;
10601
10603 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10604 if (!Pattern) {
10605 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10606 << Context.getCanonicalTagType(Record);
10607 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10608 return true;
10609 }
10610
10611 // C++0x [temp.explicit]p2:
10612 // If the explicit instantiation is for a class or member class, the
10613 // elaborated-type-specifier in the declaration shall include a
10614 // simple-template-id.
10615 //
10616 // C++98 has the same restriction, just worded differently.
10618 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10619 << Record << SS.getRange();
10620
10621 // C++0x [temp.explicit]p2:
10622 // There are two forms of explicit instantiation: an explicit instantiation
10623 // definition and an explicit instantiation declaration. An explicit
10624 // instantiation declaration begins with the extern keyword. [...]
10628
10629 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10630
10631 // Verify that it is okay to explicitly instantiate here.
10632 CXXRecordDecl *PrevDecl
10633 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10634 if (!PrevDecl && Record->getDefinition())
10635 PrevDecl = Record;
10636 if (PrevDecl) {
10638 bool HasNoEffect = false;
10639 assert(MSInfo && "No member specialization information?");
10640 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10641 PrevDecl,
10643 MSInfo->getPointOfInstantiation(),
10644 HasNoEffect))
10645 return true;
10646 if (HasNoEffect) {
10650 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10651 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10652 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10653 TL.setElaboratedKeywordLoc(KWLoc);
10654 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10655 TL.setNameLoc(NameLoc);
10657 TemplateLoc, NestedNameSpecifierLoc(),
10658 nullptr, NameLoc, TSI, TSK);
10659 return TagD;
10660 }
10661 }
10662
10663 CXXRecordDecl *RecordDef
10664 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10665 if (!RecordDef) {
10666 // C++ [temp.explicit]p3:
10667 // A definition of a member class of a class template shall be in scope
10668 // at the point of an explicit instantiation of the member class.
10669 CXXRecordDecl *Def
10670 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10671 if (!Def) {
10672 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10673 << 0 << Record->getDeclName() << Record->getDeclContext();
10674 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10675 << Pattern;
10676 return true;
10677 } else {
10678 if (InstantiateClass(NameLoc, Record, Def,
10680 TSK))
10681 return true;
10682
10683 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10684 if (!RecordDef)
10685 return true;
10686 }
10687 }
10688
10689 // Instantiate all of the members of the class.
10690 InstantiateClassMembers(NameLoc, RecordDef,
10692
10694 MarkVTableUsed(NameLoc, RecordDef, true);
10695
10698 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10699 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10700 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10701 TL.setElaboratedKeywordLoc(KWLoc);
10702 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10703 TL.setNameLoc(NameLoc);
10705 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10706 NameLoc, TSI, TSK);
10707 return TagD;
10708}
10709
10711 SourceLocation ExternLoc,
10712 SourceLocation TemplateLoc,
10713 Declarator &D) {
10714 // Explicit instantiations always require a name.
10715 // TODO: check if/when DNInfo should replace Name.
10717 DeclarationName Name = NameInfo.getName();
10718 if (!Name) {
10719 if (!D.isInvalidType())
10721 diag::err_explicit_instantiation_requires_name)
10723
10724 return true;
10725 }
10726
10727 // Get the innermost enclosing declaration scope.
10728 S = S->getDeclParent();
10729
10730 // Determine the type of the declaration.
10732 QualType R = T->getType();
10733 if (R.isNull())
10734 return true;
10735
10736 // C++ [dcl.stc]p1:
10737 // A storage-class-specifier shall not be specified in [...] an explicit
10738 // instantiation (14.7.2) directive.
10740 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10741 << Name;
10742 return true;
10743 } else if (D.getDeclSpec().getStorageClassSpec()
10745 // Complain about then remove the storage class specifier.
10746 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10748
10750 }
10751
10752 // C++0x [temp.explicit]p1:
10753 // [...] An explicit instantiation of a function template shall not use the
10754 // inline or constexpr specifiers.
10755 // Presumably, this also applies to member functions of class templates as
10756 // well.
10760 diag::err_explicit_instantiation_inline :
10761 diag::warn_explicit_instantiation_inline_0x)
10763 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10764 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10765 // not already specified.
10767 diag::err_explicit_instantiation_constexpr);
10768
10769 // A deduction guide is not on the list of entities that can be explicitly
10770 // instantiated.
10772 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10773 << /*explicit instantiation*/ 0;
10774 return true;
10775 }
10776
10777 // C++0x [temp.explicit]p2:
10778 // There are two forms of explicit instantiation: an explicit instantiation
10779 // definition and an explicit instantiation declaration. An explicit
10780 // instantiation declaration begins with the extern keyword. [...]
10784
10785 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10787 /*ObjectType=*/QualType());
10788
10789 if (!R->isFunctionType()) {
10790 // C++ [temp.explicit]p1:
10791 // A [...] static data member of a class template can be explicitly
10792 // instantiated from the member definition associated with its class
10793 // template.
10794 // C++1y [temp.explicit]p1:
10795 // A [...] variable [...] template specialization can be explicitly
10796 // instantiated from its template.
10797 if (Previous.isAmbiguous())
10798 return true;
10799
10800 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10801 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10802 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10803
10804 if (!PrevTemplate) {
10805 if (!Prev || !Prev->isStaticDataMember()) {
10806 // We expect to see a static data member here.
10807 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10808 << Name;
10809 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10810 P != PEnd; ++P)
10811 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10812 return true;
10813 }
10814
10816 // FIXME: Check for explicit specialization?
10818 diag::err_explicit_instantiation_data_member_not_instantiated)
10819 << Prev;
10820 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10821 // FIXME: Can we provide a note showing where this was declared?
10822 return true;
10823 }
10824 } else {
10825 // Explicitly instantiate a variable template.
10826
10827 // C++1y [dcl.spec.auto]p6:
10828 // ... A program that uses auto or decltype(auto) in a context not
10829 // explicitly allowed in this section is ill-formed.
10830 //
10831 // This includes auto-typed variable template instantiations.
10832 if (R->isUndeducedType()) {
10833 Diag(T->getTypeLoc().getBeginLoc(),
10834 diag::err_auto_not_allowed_var_inst);
10835 return true;
10836 }
10837
10839 // C++1y [temp.explicit]p3:
10840 // If the explicit instantiation is for a variable, the unqualified-id
10841 // in the declaration shall be a template-id.
10843 diag::err_explicit_instantiation_without_template_id)
10844 << PrevTemplate;
10845 Diag(PrevTemplate->getLocation(),
10846 diag::note_explicit_instantiation_here);
10847 return true;
10848 }
10849
10850 // Translate the parser's template argument list into our AST format.
10851 TemplateArgumentListInfo TemplateArgs =
10853
10854 DeclResult Res =
10855 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10856 TemplateArgs, /*SetWrittenArgs=*/true);
10857 if (Res.isInvalid())
10858 return true;
10859
10860 if (!Res.isUsable()) {
10861 // We somehow specified dependent template arguments in an explicit
10862 // instantiation. This should probably only happen during error
10863 // recovery.
10864 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10865 return true;
10866 }
10867
10868 // Ignore access control bits, we don't need them for redeclaration
10869 // checking.
10870 Prev = cast<VarDecl>(Res.get());
10871 ArgsAsWritten =
10873 }
10874
10875 // C++0x [temp.explicit]p2:
10876 // If the explicit instantiation is for a member function, a member class
10877 // or a static data member of a class template specialization, the name of
10878 // the class template specialization in the qualified-id for the member
10879 // name shall be a simple-template-id.
10880 //
10881 // C++98 has the same restriction, just worded differently.
10882 //
10883 // This does not apply to variable template specializations, where the
10884 // template-id is in the unqualified-id instead.
10885 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10887 diag::ext_explicit_instantiation_without_qualified_id)
10888 << Prev << D.getCXXScopeSpec().getRange();
10889
10890 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10891
10892 // Verify that it is okay to explicitly instantiate here.
10895 bool HasNoEffect = false;
10897 PrevTSK, POI, HasNoEffect))
10898 return true;
10899
10900 if (!HasNoEffect) {
10901 // Instantiate static data member or variable template.
10903 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10904 VTSD->setExternKeywordLoc(ExternLoc);
10905 VTSD->setTemplateKeywordLoc(TemplateLoc);
10906 }
10907
10908 // Merge attributes.
10910 if (PrevTemplate)
10911 ProcessAPINotes(Prev);
10912
10915 }
10916
10917 // Check the new variable specialization against the parsed input.
10918 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10919 Diag(T->getTypeLoc().getBeginLoc(),
10920 diag::err_invalid_var_template_spec_type)
10921 << 0 << PrevTemplate << R << Prev->getType();
10922 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10923 << 2 << PrevTemplate->getDeclName();
10924 return true;
10925 }
10926
10928 Context, CurContext, Prev, ExternLoc, TemplateLoc,
10929 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10930 D.getIdentifierLoc(), T, TSK);
10931 return (Decl *)nullptr;
10932 }
10933
10934 // If the declarator is a template-id, translate the parser's template
10935 // argument list into our AST format.
10936 bool HasExplicitTemplateArgs = false;
10937 TemplateArgumentListInfo TemplateArgs;
10939 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10940 HasExplicitTemplateArgs = true;
10941 }
10942
10943 // C++ [temp.explicit]p1:
10944 // A [...] function [...] can be explicitly instantiated from its template.
10945 // A member function [...] of a class template can be explicitly
10946 // instantiated from the member definition associated with its class
10947 // template.
10948 UnresolvedSet<8> TemplateMatches;
10949 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10951 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10952 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10953 P != PEnd; ++P) {
10954 NamedDecl *Prev = *P;
10955 if (!HasExplicitTemplateArgs) {
10956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10957 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10958 /*AdjustExceptionSpec*/true);
10959 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10960 if (Method->getPrimaryTemplate()) {
10961 TemplateMatches.addDecl(Method, P.getAccess());
10962 } else {
10963 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10964 C.FoundDecl = P.getPair();
10965 C.Function = Method;
10966 C.Viable = true;
10968 if (Method->getTrailingRequiresClause() &&
10970 /*ForOverloadResolution=*/true) ||
10971 !S.IsSatisfied)) {
10972 C.Viable = false;
10974 }
10975 }
10976 }
10977 }
10978 }
10979
10980 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10981 if (!FunTmpl)
10982 continue;
10983
10984 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10985 FunctionDecl *Specialization = nullptr;
10987 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10988 Specialization, Info);
10990 // Keep track of almost-matches.
10991 FailedTemplateCandidates.addCandidate().set(
10992 P.getPair(), FunTmpl->getTemplatedDecl(),
10993 MakeDeductionFailureInfo(Context, TDK, Info));
10994 (void)TDK;
10995 continue;
10996 }
10997
10998 // Target attributes are part of the cuda function signature, so
10999 // the cuda target of the instantiated function must match that of its
11000 // template. Given that C++ template deduction does not take
11001 // target attributes into account, we reject candidates here that
11002 // have a different target.
11003 if (LangOpts.CUDA &&
11004 CUDA().IdentifyTarget(Specialization,
11005 /* IgnoreImplicitHDAttr = */ true) !=
11006 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11007 FailedTemplateCandidates.addCandidate().set(
11008 P.getPair(), FunTmpl->getTemplatedDecl(),
11011 continue;
11012 }
11013
11014 TemplateMatches.addDecl(Specialization, P.getAccess());
11015 }
11016
11017 FunctionDecl *Specialization = nullptr;
11018 if (!NonTemplateMatches.empty()) {
11019 unsigned Msg = 0;
11020 OverloadCandidateDisplayKind DisplayKind;
11022 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11023 Best)) {
11024 case OR_Success:
11025 case OR_Deleted:
11026 Specialization = cast<FunctionDecl>(Best->Function);
11027 break;
11028 case OR_Ambiguous:
11029 Msg = diag::err_explicit_instantiation_ambiguous;
11030 DisplayKind = OCD_AmbiguousCandidates;
11031 break;
11033 Msg = diag::err_explicit_instantiation_no_candidate;
11034 DisplayKind = OCD_AllCandidates;
11035 break;
11036 }
11037 if (Msg) {
11038 PartialDiagnostic Diag = PDiag(Msg) << Name;
11039 NonTemplateMatches.NoteCandidates(
11040 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11041 {});
11042 return true;
11043 }
11044 }
11045
11046 if (!Specialization) {
11047 // Find the most specialized function template specialization.
11049 TemplateMatches.begin(), TemplateMatches.end(),
11050 FailedTemplateCandidates, D.getIdentifierLoc(),
11051 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11052 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11053 PDiag(diag::note_explicit_instantiation_candidate));
11054
11055 if (Result == TemplateMatches.end())
11056 return true;
11057
11058 // Ignore access control bits, we don't need them for redeclaration checking.
11060 }
11061
11062 // C++11 [except.spec]p4
11063 // In an explicit instantiation an exception-specification may be specified,
11064 // but is not required.
11065 // If an exception-specification is specified in an explicit instantiation
11066 // directive, it shall be compatible with the exception-specifications of
11067 // other declarations of that function.
11068 if (auto *FPT = R->getAs<FunctionProtoType>())
11069 if (FPT->hasExceptionSpec()) {
11070 unsigned DiagID =
11071 diag::err_mismatched_exception_spec_explicit_instantiation;
11072 if (getLangOpts().MicrosoftExt)
11073 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11075 PDiag(DiagID) << Specialization->getType(),
11076 PDiag(diag::note_explicit_instantiation_here),
11077 Specialization->getType()->getAs<FunctionProtoType>(),
11078 Specialization->getLocation(), FPT, D.getBeginLoc());
11079 // In Microsoft mode, mismatching exception specifications just cause a
11080 // warning.
11081 if (!getLangOpts().MicrosoftExt && Result)
11082 return true;
11083 }
11084
11085 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11087 diag::err_explicit_instantiation_member_function_not_instantiated)
11089 << (Specialization->getTemplateSpecializationKind() ==
11091 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11092 return true;
11093 }
11094
11095 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11096 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11097 PrevDecl = Specialization;
11098
11099 if (PrevDecl) {
11100 bool HasNoEffect = false;
11102 PrevDecl,
11104 PrevDecl->getPointOfInstantiation(),
11105 HasNoEffect))
11106 return true;
11107
11108 if (HasNoEffect) {
11109 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11110 if (HasExplicitTemplateArgs)
11111 ArgsAsWritten =
11114 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11115 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11116 D.getIdentifierLoc(), T, TSK);
11117 return (Decl *)nullptr;
11118 }
11119 }
11120
11121 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11122 // functions
11123 // valarray<size_t>::valarray(size_t) and
11124 // valarray<size_t>::~valarray()
11125 // that it declared to have internal linkage with the internal_linkage
11126 // attribute. Ignore the explicit instantiation declaration in this case.
11127 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11129 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11130 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11131 RD->isInStdNamespace())
11132 return (Decl*) nullptr;
11133 }
11134
11137
11138 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11139 // instantiation declarations.
11141 Specialization->hasAttr<DLLImportAttr>() &&
11142 Context.getTargetInfo().getCXXABI().isMicrosoft())
11144
11145 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11146 if (Specialization->isDefined()) {
11147 // Let the ASTConsumer know that this function has been explicitly
11148 // instantiated now, and its linkage might have changed.
11149 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11150 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11151 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11152 // be explicitly instantiated.
11153 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11154 RD && RD->isLambda()) {
11155 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11156 << /*instantiation*/ 1;
11157 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11158 return (Decl *)nullptr;
11159 }
11161 }
11162
11163 // C++0x [temp.explicit]p2:
11164 // If the explicit instantiation is for a member function, a member class
11165 // or a static data member of a class template specialization, the name of
11166 // the class template specialization in the qualified-id for the member
11167 // name shall be a simple-template-id.
11168 //
11169 // C++98 has the same restriction, just worded differently.
11170 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11171 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11172 D.getCXXScopeSpec().isSet() &&
11175 diag::ext_explicit_instantiation_without_qualified_id)
11177
11179 *this,
11180 FunTmpl ? (NamedDecl *)FunTmpl
11181 : Specialization->getInstantiatedFromMemberFunction(),
11182 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11183
11184 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11185 if (HasExplicitTemplateArgs)
11186 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11188 TemplateLoc,
11190 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11191 return (Decl *)nullptr;
11192}
11193
11195 const CXXScopeSpec &SS,
11196 const IdentifierInfo *Name,
11197 SourceLocation TagLoc,
11198 SourceLocation NameLoc) {
11199 // This has to hold, because SS is expected to be defined.
11200 assert(Name && "Expected a name in a dependent tag");
11201
11203 if (!NNS)
11204 return true;
11205
11207
11208 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11209 Diag(NameLoc, diag::err_dependent_tag_decl)
11210 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11211 return true;
11212 }
11213
11214 // Create the resulting type.
11216 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11217
11218 // Create type-source location information for this type.
11219 TypeLocBuilder TLB;
11221 TL.setElaboratedKeywordLoc(TagLoc);
11223 TL.setNameLoc(NameLoc);
11225}
11226
11228 const CXXScopeSpec &SS,
11229 const IdentifierInfo &II,
11230 SourceLocation IdLoc,
11231 ImplicitTypenameContext IsImplicitTypename) {
11232 if (SS.isInvalid())
11233 return true;
11234
11235 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11236 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11237 << FixItHint::CreateRemoval(TypenameLoc);
11238
11240 TypeSourceInfo *TSI = nullptr;
11241 QualType T =
11244 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11245 /*DeducedTSTContext=*/true);
11246 if (T.isNull())
11247 return true;
11248 return CreateParsedType(T, TSI);
11249}
11250
11253 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11254 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11255 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11256 ASTTemplateArgsPtr TemplateArgsIn,
11257 SourceLocation RAngleLoc) {
11258 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11259 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11260 ? diag::compat_cxx11_typename_outside_of_template
11261 : diag::compat_pre_cxx11_typename_outside_of_template)
11262 << FixItHint::CreateRemoval(TypenameLoc);
11263
11264 // Strangely, non-type results are not ignored by this lookup, so the
11265 // program is ill-formed if it finds an injected-class-name.
11266 if (TypenameLoc.isValid()) {
11267 auto *LookupRD =
11268 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11269 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11270 Diag(TemplateIILoc,
11271 diag::ext_out_of_line_qualified_id_type_names_constructor)
11272 << TemplateII << 0 /*injected-class-name used as template name*/
11273 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11274 }
11275 }
11276
11277 // Translate the parser's template argument list in our AST format.
11278 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11279 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11280
11284 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11285 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11286 if (T.isNull())
11287 return true;
11288
11289 // Provide source-location information for the template specialization type.
11290 TypeLocBuilder Builder;
11292 = Builder.push<TemplateSpecializationTypeLoc>(T);
11293 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11294 TemplateIILoc, TemplateArgs);
11295 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11296 return CreateParsedType(T, TSI);
11297}
11298
11299/// Determine whether this failed name lookup should be treated as being
11300/// disabled by a usage of std::enable_if.
11302 SourceRange &CondRange, Expr *&Cond) {
11303 // We must be looking for a ::type...
11304 if (!II.isStr("type"))
11305 return false;
11306
11307 // ... within an explicitly-written template specialization...
11309 return false;
11310
11311 // FIXME: Look through sugar.
11312 auto EnableIfTSTLoc =
11314 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11315 return false;
11316 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11317
11318 // ... which names a complete class template declaration...
11319 const TemplateDecl *EnableIfDecl =
11320 EnableIfTST->getTemplateName().getAsTemplateDecl();
11321 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11322 return false;
11323
11324 // ... called "enable_if".
11325 const IdentifierInfo *EnableIfII =
11326 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11327 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11328 return false;
11329
11330 // Assume the first template argument is the condition.
11331 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11332
11333 // Dig out the condition.
11334 Cond = nullptr;
11335 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11337 return true;
11338
11339 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11340
11341 // Ignore Boolean literals; they add no value.
11342 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11343 Cond = nullptr;
11344
11345 return true;
11346}
11347
11350 SourceLocation KeywordLoc,
11351 NestedNameSpecifierLoc QualifierLoc,
11352 const IdentifierInfo &II,
11353 SourceLocation IILoc,
11354 TypeSourceInfo **TSI,
11355 bool DeducedTSTContext) {
11356 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11357 DeducedTSTContext);
11358 if (T.isNull())
11359 return QualType();
11360
11361 TypeLocBuilder TLB;
11363 auto TL = TLB.push<DependentNameTypeLoc>(T);
11364 TL.setElaboratedKeywordLoc(KeywordLoc);
11365 TL.setQualifierLoc(QualifierLoc);
11366 TL.setNameLoc(IILoc);
11369 TL.setElaboratedKeywordLoc(KeywordLoc);
11370 TL.setQualifierLoc(QualifierLoc);
11371 TL.setNameLoc(IILoc);
11372 } else if (isa<TemplateTypeParmType>(T)) {
11373 // FIXME: There might be a 'typename' keyword here, but we just drop it
11374 // as it can't be represented.
11375 assert(!QualifierLoc);
11376 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11377 } else if (isa<TagType>(T)) {
11378 auto TL = TLB.push<TagTypeLoc>(T);
11379 TL.setElaboratedKeywordLoc(KeywordLoc);
11380 TL.setQualifierLoc(QualifierLoc);
11381 TL.setNameLoc(IILoc);
11382 } else if (isa<TypedefType>(T)) {
11383 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11384 } else {
11385 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11386 }
11387 *TSI = TLB.getTypeSourceInfo(Context, T);
11388 return T;
11389}
11390
11391/// Build the type that describes a C++ typename specifier,
11392/// e.g., "typename T::type".
11395 SourceLocation KeywordLoc,
11396 NestedNameSpecifierLoc QualifierLoc,
11397 const IdentifierInfo &II,
11398 SourceLocation IILoc, bool DeducedTSTContext) {
11399 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11400
11401 CXXScopeSpec SS;
11402 SS.Adopt(QualifierLoc);
11403
11404 DeclContext *Ctx = nullptr;
11405 if (QualifierLoc) {
11406 Ctx = computeDeclContext(SS);
11407 if (!Ctx) {
11408 // If the nested-name-specifier is dependent and couldn't be
11409 // resolved to a type, build a typename type.
11410 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11411 return Context.getDependentNameType(Keyword,
11412 QualifierLoc.getNestedNameSpecifier(),
11413 &II);
11414 }
11415
11416 // If the nested-name-specifier refers to the current instantiation,
11417 // the "typename" keyword itself is superfluous. In C++03, the
11418 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11419 // allows such extraneous "typename" keywords, and we retroactively
11420 // apply this DR to C++03 code with only a warning. In any case we continue.
11421
11422 if (RequireCompleteDeclContext(SS, Ctx))
11423 return QualType();
11424 }
11425
11426 DeclarationName Name(&II);
11427 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11428 if (Ctx)
11429 LookupQualifiedName(Result, Ctx, SS);
11430 else
11431 LookupName(Result, CurScope);
11432 unsigned DiagID = 0;
11433 Decl *Referenced = nullptr;
11434 switch (Result.getResultKind()) {
11436 // If we're looking up 'type' within a template named 'enable_if', produce
11437 // a more specific diagnostic.
11438 SourceRange CondRange;
11439 Expr *Cond = nullptr;
11440 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11441 // If we have a condition, narrow it down to the specific failed
11442 // condition.
11443 if (Cond) {
11444 Expr *FailedCond;
11445 std::string FailedDescription;
11446 std::tie(FailedCond, FailedDescription) =
11448
11449 Diag(FailedCond->getExprLoc(),
11450 diag::err_typename_nested_not_found_requirement)
11451 << FailedDescription
11452 << FailedCond->getSourceRange();
11453 return QualType();
11454 }
11455
11456 Diag(CondRange.getBegin(),
11457 diag::err_typename_nested_not_found_enable_if)
11458 << Ctx << CondRange;
11459 return QualType();
11460 }
11461
11462 DiagID = Ctx ? diag::err_typename_nested_not_found
11463 : diag::err_unknown_typename;
11464 break;
11465 }
11466
11468 // We found a using declaration that is a value. Most likely, the using
11469 // declaration itself is meant to have the 'typename' keyword.
11470 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11471 IILoc);
11472 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11473 << Name << Ctx << FullRange;
11474 if (UnresolvedUsingValueDecl *Using
11475 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11476 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11477 Diag(Loc, diag::note_using_value_decl_missing_typename)
11478 << FixItHint::CreateInsertion(Loc, "typename ");
11479 }
11480 }
11481 // Fall through to create a dependent typename type, from which we can
11482 // recover better.
11483 [[fallthrough]];
11484
11486 // Okay, it's a member of an unknown instantiation.
11487 return Context.getDependentNameType(Keyword,
11488 QualifierLoc.getNestedNameSpecifier(),
11489 &II);
11490
11492 // FXIME: Missing support for UsingShadowDecl on this path?
11493 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11494 // C++ [class.qual]p2:
11495 // In a lookup in which function names are not ignored and the
11496 // nested-name-specifier nominates a class C, if the name specified
11497 // after the nested-name-specifier, when looked up in C, is the
11498 // injected-class-name of C [...] then the name is instead considered
11499 // to name the constructor of class C.
11500 //
11501 // Unlike in an elaborated-type-specifier, function names are not ignored
11502 // in typename-specifier lookup. However, they are ignored in all the
11503 // contexts where we form a typename type with no keyword (that is, in
11504 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11505 //
11506 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11507 // ignore functions, but that appears to be an oversight.
11512 Type, IILoc);
11513 // FIXME: This appears to be the only case where a template type parameter
11514 // can have an elaborated keyword. We should preserve it somehow.
11517 assert(!QualifierLoc);
11519 }
11520 return Context.getTypeDeclType(
11521 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11522 }
11523
11524 // C++ [dcl.type.simple]p2:
11525 // A type-specifier of the form
11526 // typename[opt] nested-name-specifier[opt] template-name
11527 // is a placeholder for a deduced class type [...].
11528 if (getLangOpts().CPlusPlus17) {
11529 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11530 if (!DeducedTSTContext) {
11531 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11532 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11533 Diag(IILoc, diag::err_dependent_deduced_tst)
11535 << QualType(Qualifier.getAsType(), 0);
11536 else
11537 Diag(IILoc, diag::err_deduced_tst)
11540 return QualType();
11541 }
11542 TemplateName Name = Context.getQualifiedTemplateName(
11543 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11544 TemplateName(TD));
11545 return Context.getDeducedTemplateSpecializationType(
11546 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11547 Name);
11548 }
11549 }
11550
11551 DiagID = Ctx ? diag::err_typename_nested_not_type
11552 : diag::err_typename_not_type;
11553 Referenced = Result.getFoundDecl();
11554 break;
11555
11557 DiagID = Ctx ? diag::err_typename_nested_not_type
11558 : diag::err_typename_not_type;
11559 Referenced = *Result.begin();
11560 break;
11561
11563 return QualType();
11564 }
11565
11566 // If we get here, it's because name lookup did not find a
11567 // type. Emit an appropriate diagnostic and return an error.
11568 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11569 IILoc);
11570 if (Ctx)
11571 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11572 else
11573 Diag(IILoc, DiagID) << FullRange << Name;
11574 if (Referenced)
11575 Diag(Referenced->getLocation(),
11576 Ctx ? diag::note_typename_member_refers_here
11577 : diag::note_typename_refers_here)
11578 << Name;
11579 return QualType();
11580}
11581
11582namespace {
11583 // See Sema::RebuildTypeInCurrentInstantiation
11584 class CurrentInstantiationRebuilder
11585 : public TreeTransform<CurrentInstantiationRebuilder> {
11586 SourceLocation Loc;
11587 DeclarationName Entity;
11588
11589 public:
11591
11592 CurrentInstantiationRebuilder(Sema &SemaRef,
11593 SourceLocation Loc,
11594 DeclarationName Entity)
11595 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11596 Loc(Loc), Entity(Entity) { }
11597
11598 /// Determine whether the given type \p T has already been
11599 /// transformed.
11600 ///
11601 /// For the purposes of type reconstruction, a type has already been
11602 /// transformed if it is NULL or if it is not dependent.
11603 bool AlreadyTransformed(QualType T) {
11604 return T.isNull() || !T->isInstantiationDependentType();
11605 }
11606
11607 /// Returns the location of the entity whose type is being
11608 /// rebuilt.
11609 SourceLocation getBaseLocation() { return Loc; }
11610
11611 /// Returns the name of the entity whose type is being rebuilt.
11612 DeclarationName getBaseEntity() { return Entity; }
11613
11614 /// Sets the "base" location and entity when that
11615 /// information is known based on another transformation.
11616 void setBase(SourceLocation Loc, DeclarationName Entity) {
11617 this->Loc = Loc;
11618 this->Entity = Entity;
11619 }
11620
11621 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11622 // Lambdas never need to be transformed.
11623 return E;
11624 }
11625 };
11626} // end anonymous namespace
11627
11629 SourceLocation Loc,
11630 DeclarationName Name) {
11631 if (!T || !T->getType()->isInstantiationDependentType())
11632 return T;
11633
11634 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11635 return Rebuilder.TransformType(T);
11636}
11637
11639 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11640 DeclarationName());
11641 return Rebuilder.TransformExpr(E);
11642}
11643
11645 if (SS.isInvalid())
11646 return true;
11647
11649 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11650 DeclarationName());
11652 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11653 if (!Rebuilt)
11654 return true;
11655
11656 SS.Adopt(Rebuilt);
11657 return false;
11658}
11659
11661 TemplateParameterList *Params) {
11662 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11663 Decl *Param = Params->getParam(I);
11664
11665 // There is nothing to rebuild in a type parameter.
11666 if (isa<TemplateTypeParmDecl>(Param))
11667 continue;
11668
11669 // Rebuild the template parameter list of a template template parameter.
11671 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11673 TTP->getTemplateParameters()))
11674 return true;
11675
11676 continue;
11677 }
11678
11679 // Rebuild the type of a non-type template parameter.
11681 TypeSourceInfo *NewTSI
11683 NTTP->getLocation(),
11684 NTTP->getDeclName());
11685 if (!NewTSI)
11686 return true;
11687
11688 if (NewTSI->getType()->isUndeducedType()) {
11689 // C++17 [temp.dep.expr]p3:
11690 // An id-expression is type-dependent if it contains
11691 // - an identifier associated by name lookup with a non-type
11692 // template-parameter declared with a type that contains a
11693 // placeholder type (7.1.7.4),
11694 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11695 }
11696
11697 if (NewTSI != NTTP->getTypeSourceInfo()) {
11698 NTTP->setTypeSourceInfo(NewTSI);
11699 NTTP->setType(NewTSI->getType());
11700 }
11701 }
11702
11703 return false;
11704}
11705
11706std::string
11708 const TemplateArgumentList &Args) {
11709 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11710}
11711
11712std::string
11714 const TemplateArgument *Args,
11715 unsigned NumArgs) {
11716 SmallString<128> Str;
11717 llvm::raw_svector_ostream Out(Str);
11718
11719 if (!Params || Params->size() == 0 || NumArgs == 0)
11720 return std::string();
11721
11722 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11723 if (I >= NumArgs)
11724 break;
11725
11726 if (I == 0)
11727 Out << "[with ";
11728 else
11729 Out << ", ";
11730
11731 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11732 Out << Id->getName();
11733 } else {
11734 Out << '$' << I;
11735 }
11736
11737 Out << " = ";
11738 Args[I].print(getPrintingPolicy(), Out,
11740 getPrintingPolicy(), Params, I));
11741 }
11742
11743 Out << ']';
11744 return std::string(Out.str());
11745}
11746
11748 CachedTokens &Toks) {
11749 if (!FD)
11750 return;
11751
11752 auto LPT = std::make_unique<LateParsedTemplate>();
11753
11754 // Take tokens to avoid allocations
11755 LPT->Toks.swap(Toks);
11756 LPT->D = FnD;
11757 LPT->FPO = getCurFPFeatures();
11758 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11759
11760 FD->setLateTemplateParsed(true);
11761}
11762
11764 if (!FD)
11765 return;
11766 FD->setLateTemplateParsed(false);
11767}
11768
11770 DeclContext *DC = CurContext;
11771
11772 while (DC) {
11773 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11774 const FunctionDecl *FD = RD->isLocalClass();
11775 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11776 } else if (DC->isTranslationUnit() || DC->isNamespace())
11777 return false;
11778
11779 DC = DC->getParent();
11780 }
11781 return false;
11782}
11783
11784namespace {
11785/// Walk the path from which a declaration was instantiated, and check
11786/// that every explicit specialization along that path is visible. This enforces
11787/// C++ [temp.expl.spec]/6:
11788///
11789/// If a template, a member template or a member of a class template is
11790/// explicitly specialized then that specialization shall be declared before
11791/// the first use of that specialization that would cause an implicit
11792/// instantiation to take place, in every translation unit in which such a
11793/// use occurs; no diagnostic is required.
11794///
11795/// and also C++ [temp.class.spec]/1:
11796///
11797/// A partial specialization shall be declared before the first use of a
11798/// class template specialization that would make use of the partial
11799/// specialization as the result of an implicit or explicit instantiation
11800/// in every translation unit in which such a use occurs; no diagnostic is
11801/// required.
11802class ExplicitSpecializationVisibilityChecker {
11803 Sema &S;
11804 SourceLocation Loc;
11807
11808public:
11809 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11811 : S(S), Loc(Loc), Kind(Kind) {}
11812
11813 void check(NamedDecl *ND) {
11814 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11815 return checkImpl(FD);
11816 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11817 return checkImpl(RD);
11818 if (auto *VD = dyn_cast<VarDecl>(ND))
11819 return checkImpl(VD);
11820 if (auto *ED = dyn_cast<EnumDecl>(ND))
11821 return checkImpl(ED);
11822 }
11823
11824private:
11825 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11826 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11827 : Sema::MissingImportKind::ExplicitSpecialization;
11828 const bool Recover = true;
11829
11830 // If we got a custom set of modules (because only a subset of the
11831 // declarations are interesting), use them, otherwise let
11832 // diagnoseMissingImport intelligently pick some.
11833 if (Modules.empty())
11834 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11835 else
11836 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11837 }
11838
11839 bool CheckMemberSpecialization(const NamedDecl *D) {
11840 return Kind == Sema::AcceptableKind::Visible
11843 }
11844
11845 bool CheckExplicitSpecialization(const NamedDecl *D) {
11846 return Kind == Sema::AcceptableKind::Visible
11849 }
11850
11851 bool CheckDeclaration(const NamedDecl *D) {
11852 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11854 }
11855
11856 // Check a specific declaration. There are three problematic cases:
11857 //
11858 // 1) The declaration is an explicit specialization of a template
11859 // specialization.
11860 // 2) The declaration is an explicit specialization of a member of an
11861 // templated class.
11862 // 3) The declaration is an instantiation of a template, and that template
11863 // is an explicit specialization of a member of a templated class.
11864 //
11865 // We don't need to go any deeper than that, as the instantiation of the
11866 // surrounding class / etc is not triggered by whatever triggered this
11867 // instantiation, and thus should be checked elsewhere.
11868 template<typename SpecDecl>
11869 void checkImpl(SpecDecl *Spec) {
11870 bool IsHiddenExplicitSpecialization = false;
11871 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11872 // Some invalid friend declarations are written as specializations but are
11873 // instantiated implicitly.
11874 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11875 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11876 if (SpecKind == TSK_ExplicitSpecialization) {
11877 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11878 ? !CheckMemberSpecialization(Spec)
11879 : !CheckExplicitSpecialization(Spec);
11880 } else {
11881 checkInstantiated(Spec);
11882 }
11883
11884 if (IsHiddenExplicitSpecialization)
11885 diagnose(Spec->getMostRecentDecl(), false);
11886 }
11887
11888 void checkInstantiated(FunctionDecl *FD) {
11889 if (auto *TD = FD->getPrimaryTemplate())
11890 checkTemplate(TD);
11891 }
11892
11893 void checkInstantiated(CXXRecordDecl *RD) {
11894 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11895 if (!SD)
11896 return;
11897
11898 auto From = SD->getSpecializedTemplateOrPartial();
11899 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11900 checkTemplate(TD);
11901 else if (auto *TD =
11902 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11903 if (!CheckDeclaration(TD))
11904 diagnose(TD, true);
11905 checkTemplate(TD);
11906 }
11907 }
11908
11909 void checkInstantiated(VarDecl *RD) {
11910 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11911 if (!SD)
11912 return;
11913
11914 auto From = SD->getSpecializedTemplateOrPartial();
11915 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11916 checkTemplate(TD);
11917 else if (auto *TD =
11918 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11919 if (!CheckDeclaration(TD))
11920 diagnose(TD, true);
11921 checkTemplate(TD);
11922 }
11923 }
11924
11925 void checkInstantiated(EnumDecl *FD) {}
11926
11927 template<typename TemplDecl>
11928 void checkTemplate(TemplDecl *TD) {
11929 if (TD->isMemberSpecialization()) {
11930 if (!CheckMemberSpecialization(TD))
11931 diagnose(TD->getMostRecentDecl(), false);
11932 }
11933 }
11934};
11935} // end anonymous namespace
11936
11938 if (!getLangOpts().Modules)
11939 return;
11940
11941 ExplicitSpecializationVisibilityChecker(*this, Loc,
11943 .check(Spec);
11944}
11945
11947 NamedDecl *Spec) {
11948 if (!getLangOpts().CPlusPlusModules)
11949 return checkSpecializationVisibility(Loc, Spec);
11950
11951 ExplicitSpecializationVisibilityChecker(*this, Loc,
11953 .check(Spec);
11954}
11955
11958 return N->getLocation();
11959 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11961 return FD->getLocation();
11964 return N->getLocation();
11965 }
11966 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11967 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11968 continue;
11969 return CSC.PointOfInstantiation;
11970 }
11971 return N->getLocation();
11972}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static TemplateName resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope, const AssumedTemplateStorage *ATN, SourceLocation NameLoc)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, bool IsSpecified, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1020
APSInt & getInt()
Definition APValue.h:511
APSInt & getComplexIntImag()
Definition APValue.h:549
ValueKind getKind() const
Definition APValue.h:482
APFixedPoint & getFixedPoint()
Definition APValue.h:533
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1103
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
bool isMemberPointer() const
Definition APValue.h:499
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
@ 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:1056
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3991
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition Attr.h:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2424
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2466
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8341
Pointer to a block type.
Definition TypeBase.h:3641
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:3229
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition Expr.cpp:2113
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:738
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3869
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1557
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:771
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2032
base_class_range bases()
Definition DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2039
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2073
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1071
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3340
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:3859
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4486
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
bool isFileContext() const
Definition DeclBase.h:2197
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2219
bool isTranslationUnit() const
Definition DeclBase.h:2202
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1377
ValueDecl * getDecl()
Definition Expr.h:1344
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:704
void ClearStorageClassSpecs()
Definition DeclSpec.h:546
bool isNoreturnSpecified() const
Definition DeclSpec.h:717
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:541
SCS getStorageClassSpec() const
Definition DeclSpec.h:532
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:608
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:718
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:710
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:533
ParsedAttributes & getAttributes()
Definition DeclSpec.h:929
bool isInlineSpecified() const
Definition DeclSpec.h:693
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:542
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:705
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:892
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:696
bool hasExplicitSpecifier() const
Definition DeclSpec.h:707
bool hasConstexprSpecifier() const
Definition DeclSpec.h:893
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1078
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1243
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1234
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:824
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1197
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2823
bool isInvalidDecl() const
Definition DeclBase.h:596
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:814
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2001
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2437
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2827
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2167
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2163
bool hasEllipsis() const
Definition DeclSpec.h:2826
bool isInvalidType() const
Definition DeclSpec.h:2815
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2155
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4160
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3509
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4110
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4200
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4572
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4326
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:4055
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4327
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5154
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3106
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:833
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4081
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4366
Represents a member of a struct/union/class.
Definition Decl.h:3204
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1003
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1082
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h: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:2029
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2512
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4185
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4514
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4293
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4152
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3727
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4124
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:4358
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2398
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4397
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3149
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4145
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4984
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5695
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5691
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:4942
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:4008
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5314
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3716
Represents a linkage specification.
Definition DeclCXX.h:3036
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4424
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
QualType getPointeeType() const
Definition TypeBase.h:3770
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:240
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
NamedDecl * getMostRecentDecl()
Definition Decl.h:501
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8051
Represents a pointer to an Objective C object.
Definition TypeBase.h:8107
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
bool isVarDeclReference() const
Definition ExprCXX.h:3301
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3317
bool isConceptReference() const
Definition ExprCXX.h:3290
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3336
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:4362
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
ParsedTemplateArgument()
Build an empty template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition TypeBase.h:8307
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8578
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3686
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
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:8674
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3679
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
bool ValidateCandidate(const TypoCorrection &Candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
QualifiedLookupValidatorCCC(bool HasQualifier)
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3734
Represents a struct/union/class.
Definition Decl.h:4369
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4553
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5374
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
QualType getPointeeType() const
Definition TypeBase.h:3690
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13805
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8541
A RAII object to temporarily push a declaration context.
Definition Sema.h:3538
Whether and why a template name is required in this lookup.
Definition Sema.h:11548
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11556
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12607
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12641
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7810
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
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:13752
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13203
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2688
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:9423
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9427
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9435
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9430
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:9739
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:1477
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4217
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:2085
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:11519
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12118
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12121
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12125
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1310
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
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:941
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:778
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:1214
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:12297
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12315
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12305
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12325
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:11569
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11576
@ None
This is not assumed to be a template name.
Definition Sema.h:11571
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11573
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:11505
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:936
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14594
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14582
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14591
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14585
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14609
const LangOptions & getLangOpts() const
Definition Sema.h:934
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:1309
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:1308
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1450
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13843
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:15609
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:1311
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:4715
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:6830
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6809
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:14105
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:11546
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:523
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition Sema.h:11729
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11739
@ TPC_FriendFunctionTemplate
Definition Sema.h:11737
@ TPC_ClassTemplateMember
Definition Sema.h:11735
@ TPC_FunctionTemplate
Definition Sema.h:11734
@ TPC_FriendClassTemplate
Definition Sema.h:11736
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11738
friend class InitializationSequence
Definition Sema.h:1592
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition Sema.h:6380
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6517
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1302
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3531
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11511
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition SemaDecl.cpp:149
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition Sema.h:9748
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13046
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8755
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13840
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:4663
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
StringRef getKindName() const
Definition Decl.h:3957
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4906
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5042
TagKind getTagKind() const
Definition Decl.h:3961
A convenient class for passing around template argument information.
SourceLocation getRAngleLoc() const
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getLAngleLoc() const
A template argument list.
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Location wrapper for a TemplateArgument.
SourceLocation getLocation() const
SourceLocation getTemplateEllipsisLoc() const
TemplateArgumentLocInfo getLocInfo() const
const TemplateArgument & getArgument() const
SourceLocation getTemplateNameLoc() const
TypeSourceInfo * getTypeSourceInfo() const
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
void print(const PrintingPolicy &Policy, raw_ostream &Out, bool IncludeType) const
Print this template argument to the given output stream.
QualType getIntegralType() const
Retrieve the type of the integral value.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DeducedTemplateStorage * getAsDeducedTemplateName() const
Retrieve the deduced template info, if any.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
std::pair< TemplateName, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template name that this template name refers to, along with the deduced defa...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
bool isDependent() const
Determines whether this is a dependent template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
NamedDecl ** iterator
Iterates through the template parameters in this list.
bool hasAssociatedConstraints() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition TypeLoc.cpp:648
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3732
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:3557
const Type * getTypeForDecl() const
Definition Decl.h:3582
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3591
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:888
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:6317
A container of type source information.
Definition TypeBase.h:8460
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:8471
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:1876
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2546
bool isBooleanType() const
Definition TypeBase.h:9229
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2359
bool isRValueReferenceType() const
Definition TypeBase.h:8758
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8825
bool isPointerType() const
Definition TypeBase.h:8726
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2160
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9214
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8913
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2964
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2855
bool isLValueReferenceType() const
Definition TypeBase.h:8754
bool isBitIntType() const
Definition TypeBase.h:9001
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8849
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2113
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2865
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9235
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:5035
bool isPointerOrReferenceType() const
Definition TypeBase.h:8730
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8722
bool isVectorType() const
Definition TypeBase.h:8865
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2986
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2472
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isNullPtrType() const
Definition TypeBase.h:9129
bool isRecordType() const
Definition TypeBase.h:8853
QualType getUnderlyingType() const
Definition Decl.h:3661
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4177
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1120
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1300
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1297
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1116
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3389
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6122
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3961
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3484
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
TLSKind getTLSKind() const
Definition Decl.cpp:2149
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2735
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:2870
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:2763
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:2742
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2861
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4065
Represents a GCC generic vector type.
Definition TypeBase.h:4274
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1984
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpaquePtr< TemplateName > ParsedTemplateTy
Definition Ownership.h:256
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus17
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition Ownership.h:263
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:604
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1080
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1072
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1066
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1068
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:124
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:249
@ SC_Extern
Definition Specifiers.h:252
@ TSCS_unspecified
Definition Specifiers.h:237
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:451
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6030
@ Enum
The "enum" keyword.
Definition TypeBase.h:6044
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1810
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:207
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1305
@ 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
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
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:6005
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6026
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6019
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6023
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2248
CharacterLiteralKind
Definition Expr.h:1609
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:640
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5491
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3389
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3406
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3371
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:12156
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12152
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12145
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12142
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12142
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13254
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13358
A stack object to be created when performing template instantiation.
Definition Sema.h:13448
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13601
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:1099