clang 22.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"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/Type.h"
30#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/Overload.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/SemaCUDA.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/SmallBitVector.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/SaveAndRestore.h"
45
46#include <optional>
47using namespace clang;
48using namespace sema;
49
50// Exported for use by Parser.
53 unsigned N) {
54 if (!N) return SourceRange();
55 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56}
57
58unsigned Sema::getTemplateDepth(Scope *S) const {
59 unsigned Depth = 0;
60
61 // Each template parameter scope represents one level of template parameter
62 // depth.
63 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65 ++Depth;
66 }
67
68 // Note that there are template parameters with the given depth.
69 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70
71 // Look for parameters of an enclosing generic lambda. We don't create a
72 // template parameter scope for these.
74 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75 if (!LSI->TemplateParams.empty()) {
76 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77 break;
78 }
79 if (LSI->GLTemplateParameterList) {
80 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81 break;
82 }
83 }
84 }
85
86 // Look for parameters of an enclosing terse function template. We don't
87 // create a template parameter scope for these either.
88 for (const InventedTemplateParameterInfo &Info :
90 if (!Info.TemplateParams.empty()) {
91 ParamsAtDepth(Info.AutoTemplateParameterDepth);
92 break;
93 }
94 }
95
96 return Depth;
97}
98
99/// \brief Determine whether the declaration found is acceptable as the name
100/// of a template and, if so, return that template declaration. Otherwise,
101/// returns null.
102///
103/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104/// is true. In all other cases it will return a TemplateDecl (or null).
106 bool AllowFunctionTemplates,
107 bool AllowDependent) {
108 D = D->getUnderlyingDecl();
109
110 if (isa<TemplateDecl>(D)) {
111 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112 return nullptr;
113
114 return D;
115 }
116
117 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118 // C++ [temp.local]p1:
119 // Like normal (non-template) classes, class templates have an
120 // injected-class-name (Clause 9). The injected-class-name
121 // can be used with or without a template-argument-list. When
122 // it is used without a template-argument-list, it is
123 // equivalent to the injected-class-name followed by the
124 // template-parameters of the class template enclosed in
125 // <>. When it is used with a template-argument-list, it
126 // refers to the specified class template specialization,
127 // which could be the current specialization or another
128 // specialization.
129 if (Record->isInjectedClassName()) {
130 Record = cast<CXXRecordDecl>(Record->getDeclContext());
131 if (Record->getDescribedClassTemplate())
132 return Record->getDescribedClassTemplate();
133
134 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135 return Spec->getSpecializedTemplate();
136 }
137
138 return nullptr;
139 }
140
141 // 'using Dependent::foo;' can resolve to a template name.
142 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143 // injected-class-name).
144 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145 return D;
146
147 return nullptr;
148}
149
151 bool AllowFunctionTemplates,
152 bool AllowDependent) {
153 LookupResult::Filter filter = R.makeFilter();
154 while (filter.hasNext()) {
155 NamedDecl *Orig = filter.next();
156 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157 filter.erase();
158 }
159 filter.done();
160}
161
163 bool AllowFunctionTemplates,
164 bool AllowDependent,
165 bool AllowNonTemplateFunctions) {
166 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168 return true;
169 if (AllowNonTemplateFunctions &&
170 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171 return true;
172 }
173
174 return false;
175}
176
178 CXXScopeSpec &SS,
179 bool hasTemplateKeyword,
180 const UnqualifiedId &Name,
181 ParsedType ObjectTypePtr,
182 bool EnteringContext,
183 TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool Disambiguation) {
186 assert(getLangOpts().CPlusPlus && "No template names in C!");
187
188 DeclarationName TName;
189 MemberOfUnknownSpecialization = false;
190
191 switch (Name.getKind()) {
193 TName = DeclarationName(Name.Identifier);
194 break;
195
197 TName = Context.DeclarationNames.getCXXOperatorName(
199 break;
200
202 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203 break;
204
205 default:
206 return TNK_Non_template;
207 }
208
209 QualType ObjectType = ObjectTypePtr.get();
210
211 AssumedTemplateKind AssumedTemplate;
212 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214 /*RequiredTemplate=*/SourceLocation(),
215 &AssumedTemplate,
216 /*AllowTypoCorrection=*/!Disambiguation))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
280 } else {
281 if (!D) {
283 assert(D && "unambiguous result is not a template name");
284 }
285
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299 Template);
300 }
301
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
307 } else {
311 TemplateKind =
313 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
317 }
318 }
319
321 S->getTemplateParamParent() == nullptr)
322 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(Template);
327 return TemplateKind;
328}
329
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
351 if (!TD || !getAsTypeTemplateDecl(TD))
352 return false;
353
354 if (Template) {
355 TemplateName Name = Context.getQualifiedTemplateName(
356 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
357 *Template = TemplateTy::make(Name);
358 }
359 return true;
360}
361
363 SourceLocation IILoc,
364 Scope *S,
365 const CXXScopeSpec *SS,
366 TemplateTy &SuggestedTemplate,
367 TemplateNameKind &SuggestedKind) {
368 // We can't recover unless there's a dependent scope specifier preceding the
369 // template name.
370 // FIXME: Typo correction?
371 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
373 return false;
374
375 // The code is missing a 'template' keyword prior to the dependent template
376 // name.
377 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(
378 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
379 Diag(IILoc, diag::err_template_kw_missing)
380 << SuggestedTemplate.get()
381 << FixItHint::CreateInsertion(IILoc, "template ");
382 SuggestedKind = TNK_Dependent_template_name;
383 return true;
384}
385
387 QualType ObjectType, bool EnteringContext,
388 RequiredTemplateKind RequiredTemplate,
390 bool AllowTypoCorrection) {
391 if (ATK)
393
394 if (SS.isInvalid())
395 return true;
396
397 Found.setTemplateNameLookup(true);
398
399 // Determine where to perform name lookup
400 DeclContext *LookupCtx = nullptr;
401 bool IsDependent = false;
402 if (!ObjectType.isNull()) {
403 // This nested-name-specifier occurs in a member access expression, e.g.,
404 // x->B::f, and we are looking into the type of the object.
405 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
406 LookupCtx = computeDeclContext(ObjectType);
407 IsDependent = !LookupCtx && ObjectType->isDependentType();
408 assert((IsDependent || !ObjectType->isIncompleteType() ||
409 !ObjectType->getAs<TagType>() ||
410 ObjectType->castAs<TagType>()
411 ->getOriginalDecl()
412 ->isEntityBeingDefined()) &&
413 "Caller should have completed object type");
414
415 // Template names cannot appear inside an Objective-C class or object type
416 // or a vector type.
417 //
418 // FIXME: This is wrong. For example:
419 //
420 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
421 // Vec<int> vi;
422 // vi.Vec<int>::~Vec<int>();
423 //
424 // ... should be accepted but we will not treat 'Vec' as a template name
425 // here. The right thing to do would be to check if the name is a valid
426 // vector component name, and look up a template name if not. And similarly
427 // for lookups into Objective-C class and object types, where the same
428 // problem can arise.
429 if (ObjectType->isObjCObjectOrInterfaceType() ||
430 ObjectType->isVectorType()) {
431 Found.clear();
432 return false;
433 }
434 } else if (SS.isNotEmpty()) {
435 // This nested-name-specifier occurs after another nested-name-specifier,
436 // so long into the context associated with the prior nested-name-specifier.
437 LookupCtx = computeDeclContext(SS, EnteringContext);
438 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
439
440 // The declaration context must be complete.
441 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
442 return true;
443 }
444
445 bool ObjectTypeSearchedInScope = false;
446 bool AllowFunctionTemplatesInLookup = true;
447 if (LookupCtx) {
448 // Perform "qualified" name lookup into the declaration context we
449 // computed, which is either the type of the base of a member access
450 // expression or the declaration context associated with a prior
451 // nested-name-specifier.
452 LookupQualifiedName(Found, LookupCtx);
453
454 // FIXME: The C++ standard does not clearly specify what happens in the
455 // case where the object type is dependent, and implementations vary. In
456 // Clang, we treat a name after a . or -> as a template-name if lookup
457 // finds a non-dependent member or member of the current instantiation that
458 // is a type template, or finds no such members and lookup in the context
459 // of the postfix-expression finds a type template. In the latter case, the
460 // name is nonetheless dependent, and we may resolve it to a member of an
461 // unknown specialization when we come to instantiate the template.
462 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
463 }
464
465 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
466 // C++ [basic.lookup.classref]p1:
467 // In a class member access expression (5.2.5), if the . or -> token is
468 // immediately followed by an identifier followed by a <, the
469 // identifier must be looked up to determine whether the < is the
470 // beginning of a template argument list (14.2) or a less-than operator.
471 // The identifier is first looked up in the class of the object
472 // expression. If the identifier is not found, it is then looked up in
473 // the context of the entire postfix-expression and shall name a class
474 // template.
475 if (S)
476 LookupName(Found, S);
477
478 if (!ObjectType.isNull()) {
479 // FIXME: We should filter out all non-type templates here, particularly
480 // variable templates and concepts. But the exclusion of alias templates
481 // and template template parameters is a wording defect.
482 AllowFunctionTemplatesInLookup = false;
483 ObjectTypeSearchedInScope = true;
484 }
485
486 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
487 }
488
489 if (Found.isAmbiguous())
490 return false;
491
492 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
493 !RequiredTemplate.hasTemplateKeyword()) {
494 // C++2a [temp.names]p2:
495 // A name is also considered to refer to a template if it is an
496 // unqualified-id followed by a < and name lookup finds either one or more
497 // functions or finds nothing.
498 //
499 // To keep our behavior consistent, we apply the "finds nothing" part in
500 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
501 // successfully form a call to an undeclared template-id.
502 bool AllFunctions =
503 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
505 });
506 if (AllFunctions || (Found.empty() && !IsDependent)) {
507 // If lookup found any functions, or if this is a name that can only be
508 // used for a function, then strongly assume this is a function
509 // template-id.
510 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
513 Found.clear();
514 return false;
515 }
516 }
517
518 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
519 // If we did not find any names, and this is not a disambiguation, attempt
520 // to correct any typos.
521 DeclarationName Name = Found.getLookupName();
522 Found.clear();
523 // Simple filter callback that, for keywords, only accepts the C++ *_cast
524 DefaultFilterCCC FilterCCC{};
525 FilterCCC.WantTypeSpecifiers = false;
526 FilterCCC.WantExpressionKeywords = false;
527 FilterCCC.WantRemainingKeywords = false;
528 FilterCCC.WantCXXNamedCasts = true;
529 if (TypoCorrection Corrected = CorrectTypo(
530 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
531 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
532 if (auto *ND = Corrected.getFoundDecl())
533 Found.addDecl(ND);
535 if (Found.isAmbiguous()) {
536 Found.clear();
537 } else if (!Found.empty()) {
538 // Do not erase the typo-corrected result to avoid duplicated
539 // diagnostics.
540 AllowFunctionTemplatesInLookup = true;
541 Found.setLookupName(Corrected.getCorrection());
542 if (LookupCtx) {
543 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
544 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
545 Name.getAsString() == CorrectedStr;
546 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
547 << Name << LookupCtx << DroppedSpecifier
548 << SS.getRange());
549 } else {
550 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
551 }
552 }
553 }
554 }
555
556 NamedDecl *ExampleLookupResult =
557 Found.empty() ? nullptr : Found.getRepresentativeDecl();
558 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
559 if (Found.empty()) {
560 if (IsDependent) {
561 Found.setNotFoundInCurrentInstantiation();
562 return false;
563 }
564
565 // If a 'template' keyword was used, a lookup that finds only non-template
566 // names is an error.
567 if (ExampleLookupResult && RequiredTemplate) {
568 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
569 << Found.getLookupName() << SS.getRange()
570 << RequiredTemplate.hasTemplateKeyword()
571 << RequiredTemplate.getTemplateKeywordLoc();
572 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
573 diag::note_template_kw_refers_to_non_template)
574 << Found.getLookupName();
575 return true;
576 }
577
578 return false;
579 }
580
581 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
583 // C++03 [basic.lookup.classref]p1:
584 // [...] If the lookup in the class of the object expression finds a
585 // template, the name is also looked up in the context of the entire
586 // postfix-expression and [...]
587 //
588 // Note: C++11 does not perform this second lookup.
589 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
591 FoundOuter.setTemplateNameLookup(true);
592 LookupName(FoundOuter, S);
593 // FIXME: We silently accept an ambiguous lookup here, in violation of
594 // [basic.lookup]/1.
595 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
596
597 NamedDecl *OuterTemplate;
598 if (FoundOuter.empty()) {
599 // - if the name is not found, the name found in the class of the
600 // object expression is used, otherwise
601 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
602 !(OuterTemplate =
603 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
604 // - if the name is found in the context of the entire
605 // postfix-expression and does not name a class template, the name
606 // found in the class of the object expression is used, otherwise
607 FoundOuter.clear();
608 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
609 // - if the name found is a class template, it must refer to the same
610 // entity as the one found in the class of the object expression,
611 // otherwise the program is ill-formed.
612 if (!Found.isSingleResult() ||
613 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
614 OuterTemplate->getCanonicalDecl()) {
615 Diag(Found.getNameLoc(),
616 diag::ext_nested_name_member_ref_lookup_ambiguous)
617 << Found.getLookupName()
618 << ObjectType;
619 Diag(Found.getRepresentativeDecl()->getLocation(),
620 diag::note_ambig_member_ref_object_type)
621 << ObjectType;
622 Diag(FoundOuter.getFoundDecl()->getLocation(),
623 diag::note_ambig_member_ref_scope);
624
625 // Recover by taking the template that we found in the object
626 // expression's type.
627 }
628 }
629 }
630
631 return false;
632}
633
637 if (TemplateName.isInvalid())
638 return;
639
640 DeclarationNameInfo NameInfo;
641 CXXScopeSpec SS;
642 LookupNameKind LookupKind;
643
644 DeclContext *LookupCtx = nullptr;
645 NamedDecl *Found = nullptr;
646 bool MissingTemplateKeyword = false;
647
648 // Figure out what name we looked up.
649 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
650 NameInfo = DRE->getNameInfo();
651 SS.Adopt(DRE->getQualifierLoc());
652 LookupKind = LookupOrdinaryName;
653 Found = DRE->getFoundDecl();
654 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
655 NameInfo = ME->getMemberNameInfo();
656 SS.Adopt(ME->getQualifierLoc());
657 LookupKind = LookupMemberName;
658 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
659 Found = ME->getMemberDecl();
660 } else if (auto *DSDRE =
661 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
662 NameInfo = DSDRE->getNameInfo();
663 SS.Adopt(DSDRE->getQualifierLoc());
664 MissingTemplateKeyword = true;
665 } else if (auto *DSME =
666 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
667 NameInfo = DSME->getMemberNameInfo();
668 SS.Adopt(DSME->getQualifierLoc());
669 MissingTemplateKeyword = true;
670 } else {
671 llvm_unreachable("unexpected kind of potential template name");
672 }
673
674 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
675 // was missing.
676 if (MissingTemplateKeyword) {
677 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
678 << NameInfo.getName() << SourceRange(Less, Greater);
679 return;
680 }
681
682 // Try to correct the name by looking for templates and C++ named casts.
683 struct TemplateCandidateFilter : CorrectionCandidateCallback {
684 Sema &S;
685 TemplateCandidateFilter(Sema &S) : S(S) {
686 WantTypeSpecifiers = false;
687 WantExpressionKeywords = false;
688 WantRemainingKeywords = false;
689 WantCXXNamedCasts = true;
690 };
691 bool ValidateCandidate(const TypoCorrection &Candidate) override {
692 if (auto *ND = Candidate.getCorrectionDecl())
693 return S.getAsTemplateNameDecl(ND);
694 return Candidate.isKeyword();
695 }
696
697 std::unique_ptr<CorrectionCandidateCallback> clone() override {
698 return std::make_unique<TemplateCandidateFilter>(*this);
699 }
700 };
701
702 DeclarationName Name = NameInfo.getName();
703 TemplateCandidateFilter CCC(*this);
704 if (TypoCorrection Corrected =
705 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
706 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
707 auto *ND = Corrected.getFoundDecl();
708 if (ND)
709 ND = getAsTemplateNameDecl(ND);
710 if (ND || Corrected.isKeyword()) {
711 if (LookupCtx) {
712 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
713 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
714 Name.getAsString() == CorrectedStr;
715 diagnoseTypo(Corrected,
716 PDiag(diag::err_non_template_in_member_template_id_suggest)
717 << Name << LookupCtx << DroppedSpecifier
718 << SS.getRange(), false);
719 } else {
720 diagnoseTypo(Corrected,
721 PDiag(diag::err_non_template_in_template_id_suggest)
722 << Name, false);
723 }
724 if (Found)
725 Diag(Found->getLocation(),
726 diag::note_non_template_in_template_id_found);
727 return;
728 }
729 }
730
731 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
732 << Name << SourceRange(Less, Greater);
733 if (Found)
734 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
735}
736
739 SourceLocation TemplateKWLoc,
740 const DeclarationNameInfo &NameInfo,
741 bool isAddressOfOperand,
742 const TemplateArgumentListInfo *TemplateArgs) {
743 if (SS.isEmpty()) {
744 // FIXME: This codepath is only used by dependent unqualified names
745 // (e.g. a dependent conversion-function-id, or operator= once we support
746 // it). It doesn't quite do the right thing, and it will silently fail if
747 // getCurrentThisType() returns null.
748 QualType ThisType = getCurrentThisType();
749 if (ThisType.isNull())
750 return ExprError();
751
753 Context, /*Base=*/nullptr, ThisType,
754 /*IsArrow=*/!Context.getLangOpts().HLSL,
755 /*OperatorLoc=*/SourceLocation(),
756 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
757 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
758 }
759 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
760}
761
764 SourceLocation TemplateKWLoc,
765 const DeclarationNameInfo &NameInfo,
766 const TemplateArgumentListInfo *TemplateArgs) {
767 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
768 if (!SS.isValid())
769 return CreateRecoveryExpr(
770 SS.getBeginLoc(),
771 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
772
774 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
775 TemplateArgs);
776}
777
779 NamedDecl *Instantiation,
780 bool InstantiatedFromMember,
781 const NamedDecl *Pattern,
782 const NamedDecl *PatternDef,
784 bool Complain, bool *Unreachable) {
785 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
786 isa<VarDecl>(Instantiation));
787
788 bool IsEntityBeingDefined = false;
789 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
790 IsEntityBeingDefined = TD->isBeingDefined();
791
792 if (PatternDef && !IsEntityBeingDefined) {
793 NamedDecl *SuggestedDef = nullptr;
794 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
795 &SuggestedDef,
796 /*OnlyNeedComplete*/ false)) {
797 if (Unreachable)
798 *Unreachable = true;
799 // If we're allowed to diagnose this and recover, do so.
800 bool Recover = Complain && !isSFINAEContext();
801 if (Complain)
802 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
804 return !Recover;
805 }
806 return false;
807 }
808
809 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
810 return true;
811
812 CanQualType InstantiationTy;
813 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
814 InstantiationTy = Context.getCanonicalTagType(TD);
815 if (PatternDef) {
816 Diag(PointOfInstantiation,
817 diag::err_template_instantiate_within_definition)
818 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
819 << InstantiationTy;
820 // Not much point in noting the template declaration here, since
821 // we're lexically inside it.
822 Instantiation->setInvalidDecl();
823 } else if (InstantiatedFromMember) {
824 if (isa<FunctionDecl>(Instantiation)) {
825 Diag(PointOfInstantiation,
826 diag::err_explicit_instantiation_undefined_member)
827 << /*member function*/ 1 << Instantiation->getDeclName()
828 << Instantiation->getDeclContext();
829 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
830 } else {
831 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
832 Diag(PointOfInstantiation,
833 diag::err_implicit_instantiate_member_undefined)
834 << InstantiationTy;
835 Diag(Pattern->getLocation(), diag::note_member_declared_at);
836 }
837 } else {
838 if (isa<FunctionDecl>(Instantiation)) {
839 Diag(PointOfInstantiation,
840 diag::err_explicit_instantiation_undefined_func_template)
841 << Pattern;
842 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
843 } else if (isa<TagDecl>(Instantiation)) {
844 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
845 << (TSK != TSK_ImplicitInstantiation)
846 << InstantiationTy;
847 NoteTemplateLocation(*Pattern);
848 } else {
849 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
850 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_var_template)
853 << Instantiation;
854 Instantiation->setInvalidDecl();
855 } else
856 Diag(PointOfInstantiation,
857 diag::err_explicit_instantiation_undefined_member)
858 << /*static data member*/ 2 << Instantiation->getDeclName()
859 << Instantiation->getDeclContext();
860 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
861 }
862 }
863
864 // In general, Instantiation isn't marked invalid to get more than one
865 // error for multiple undefined instantiations. But the code that does
866 // explicit declaration -> explicit definition conversion can't handle
867 // invalid declarations, so mark as invalid in that case.
869 Instantiation->setInvalidDecl();
870 return true;
871}
872
874 bool SupportedForCompatibility) {
875 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
876
877 // C++23 [temp.local]p6:
878 // The name of a template-parameter shall not be bound to any following.
879 // declaration whose locus is contained by the scope to which the
880 // template-parameter belongs.
881 //
882 // When MSVC compatibility is enabled, the diagnostic is always a warning
883 // by default. Otherwise, it an error unless SupportedForCompatibility is
884 // true, in which case it is a default-to-error warning.
885 unsigned DiagId =
886 getLangOpts().MSVCCompat
887 ? diag::ext_template_param_shadow
888 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
889 : diag::err_template_param_shadow);
890 const auto *ND = cast<NamedDecl>(PrevDecl);
891 Diag(Loc, DiagId) << ND->getDeclName();
893}
894
896 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
897 D = Temp->getTemplatedDecl();
898 return Temp;
899 }
900 return nullptr;
901}
902
904 SourceLocation EllipsisLoc) const {
905 assert(Kind == Template &&
906 "Only template template arguments can be pack expansions here");
907 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
908 "Template template argument pack expansion without packs");
910 Result.EllipsisLoc = EllipsisLoc;
911 return Result;
912}
913
915 const ParsedTemplateArgument &Arg) {
916
917 switch (Arg.getKind()) {
919 TypeSourceInfo *DI;
920 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
921 if (!DI)
922 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
924 }
925
927 Expr *E = Arg.getAsExpr();
928 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
929 }
930
933 TemplateArgument TArg;
934 if (Arg.getEllipsisLoc().isValid())
935 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
936 else
937 TArg = Template;
938 return TemplateArgumentLoc(
939 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
941 Arg.getNameLoc(), Arg.getEllipsisLoc());
942 }
943 }
944
945 llvm_unreachable("Unhandled parsed template argument");
946}
947
949 TemplateArgumentListInfo &TemplateArgs) {
950 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
951 TemplateArgs.addArgument(translateTemplateArgument(*this,
952 TemplateArgsIn[I]));
953}
954
956 SourceLocation Loc,
957 const IdentifierInfo *Name) {
958 NamedDecl *PrevDecl =
959 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
961 if (PrevDecl && PrevDecl->isTemplateParameter())
962 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
963}
964
966 TypeSourceInfo *TInfo;
967 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
968 if (T.isNull())
969 return ParsedTemplateArgument();
970 assert(TInfo && "template argument with no location");
971
972 // If we might have formed a deduced template specialization type, convert
973 // it to a template template argument.
974 if (getLangOpts().CPlusPlus17) {
975 TypeLoc TL = TInfo->getTypeLoc();
976 SourceLocation EllipsisLoc;
977 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
978 EllipsisLoc = PET.getEllipsisLoc();
979 TL = PET.getPatternLoc();
980 }
981
982 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
983 TemplateName Name = DTST.getTypePtr()->getTemplateName();
984 CXXScopeSpec SS;
985 SS.Adopt(DTST.getQualifierLoc());
986 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
987 TemplateTy::make(Name),
988 DTST.getTemplateNameLoc());
989 if (EllipsisLoc.isValid())
990 Result = Result.getTemplatePackExpansion(EllipsisLoc);
991 return Result;
992 }
993 }
994
995 // This is a normal type template argument. Note, if the type template
996 // argument is an injected-class-name for a template, it has a dual nature
997 // and can be used as either a type or a template. We handle that in
998 // convertTypeTemplateArgumentToTemplate.
1000 ParsedType.get().getAsOpaquePtr(),
1001 TInfo->getTypeLoc().getBeginLoc());
1002}
1003
1005 SourceLocation EllipsisLoc,
1006 SourceLocation KeyLoc,
1007 IdentifierInfo *ParamName,
1008 SourceLocation ParamNameLoc,
1009 unsigned Depth, unsigned Position,
1010 SourceLocation EqualLoc,
1011 ParsedType DefaultArg,
1012 bool HasTypeConstraint) {
1013 assert(S->isTemplateParamScope() &&
1014 "Template type parameter not in template parameter scope!");
1015
1016 bool IsParameterPack = EllipsisLoc.isValid();
1018 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1019 KeyLoc, ParamNameLoc, Depth, Position,
1020 ParamName, Typename, IsParameterPack,
1021 HasTypeConstraint);
1022 Param->setAccess(AS_public);
1023
1024 if (Param->isParameterPack())
1025 if (auto *CSI = getEnclosingLambdaOrBlock())
1026 CSI->LocalPacks.push_back(Param);
1027
1028 if (ParamName) {
1029 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1030
1031 // Add the template parameter into the current scope.
1032 S->AddDecl(Param);
1033 IdResolver.AddDecl(Param);
1034 }
1035
1036 // C++0x [temp.param]p9:
1037 // A default template-argument may be specified for any kind of
1038 // template-parameter that is not a template parameter pack.
1039 if (DefaultArg && IsParameterPack) {
1040 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1041 DefaultArg = nullptr;
1042 }
1043
1044 // Handle the default argument, if provided.
1045 if (DefaultArg) {
1046 TypeSourceInfo *DefaultTInfo;
1047 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1048
1049 assert(DefaultTInfo && "expected source information for type");
1050
1051 // Check for unexpanded parameter packs.
1052 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1054 return Param;
1055
1056 // Check the template argument itself.
1057 if (CheckTemplateArgument(DefaultTInfo)) {
1058 Param->setInvalidDecl();
1059 return Param;
1060 }
1061
1062 Param->setDefaultArgument(
1063 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1064 }
1065
1066 return Param;
1067}
1068
1069/// Convert the parser's template argument list representation into our form.
1072 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1073 TemplateId.RAngleLoc);
1074 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1075 TemplateId.NumArgs);
1076 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1077 return TemplateArgs;
1078}
1079
1081
1082 TemplateName TN = TypeConstr->Template.get();
1083 NamedDecl *CD = nullptr;
1084 bool IsTypeConcept = false;
1085 bool RequiresArguments = false;
1086 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1087 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1088 RequiresArguments =
1089 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1090 CD = TTP;
1091 } else {
1092 CD = TN.getAsTemplateDecl();
1093 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1094 RequiresArguments = cast<ConceptDecl>(CD)
1095 ->getTemplateParameters()
1096 ->getMinRequiredArguments() > 1;
1097 }
1098
1099 // C++2a [temp.param]p4:
1100 // [...] The concept designated by a type-constraint shall be a type
1101 // concept ([temp.concept]).
1102 if (!IsTypeConcept) {
1103 Diag(TypeConstr->TemplateNameLoc,
1104 diag::err_type_constraint_non_type_concept);
1105 return true;
1106 }
1107
1108 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1109 return true;
1110
1111 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1112
1113 if (!WereArgsSpecified && RequiresArguments) {
1114 Diag(TypeConstr->TemplateNameLoc,
1115 diag::err_type_constraint_missing_arguments)
1116 << CD;
1117 return true;
1118 }
1119 return false;
1120}
1121
1123 TemplateIdAnnotation *TypeConstr,
1124 TemplateTypeParmDecl *ConstrainedParameter,
1125 SourceLocation EllipsisLoc) {
1126 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1127 false);
1128}
1129
1131 TemplateIdAnnotation *TypeConstr,
1132 TemplateTypeParmDecl *ConstrainedParameter,
1133 SourceLocation EllipsisLoc,
1134 bool AllowUnexpandedPack) {
1135
1136 if (CheckTypeConstraint(TypeConstr))
1137 return true;
1138
1139 TemplateName TN = TypeConstr->Template.get();
1142
1143 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1144 TypeConstr->TemplateNameLoc);
1145
1146 TemplateArgumentListInfo TemplateArgs;
1147 if (TypeConstr->LAngleLoc.isValid()) {
1148 TemplateArgs =
1149 makeTemplateArgumentListInfo(*this, *TypeConstr);
1150
1151 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1152 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1154 return true;
1155 }
1156 }
1157 }
1158 return AttachTypeConstraint(
1160 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1161 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1162 ConstrainedParameter, EllipsisLoc);
1163}
1164
1165template <typename ArgumentLocAppender>
1168 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1169 SourceLocation RAngleLoc, QualType ConstrainedType,
1170 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1171 SourceLocation EllipsisLoc) {
1172
1173 TemplateArgumentListInfo ConstraintArgs;
1174 ConstraintArgs.addArgument(
1176 /*NTTPType=*/QualType(), ParamNameLoc));
1177
1178 ConstraintArgs.setRAngleLoc(RAngleLoc);
1179 ConstraintArgs.setLAngleLoc(LAngleLoc);
1180 Appender(ConstraintArgs);
1181
1182 // C++2a [temp.param]p4:
1183 // [...] This constraint-expression E is called the immediately-declared
1184 // constraint of T. [...]
1185 CXXScopeSpec SS;
1186 SS.Adopt(NS);
1187 ExprResult ImmediatelyDeclaredConstraint;
1188 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1189 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1190 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1191 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, CD,
1192 &ConstraintArgs);
1193 }
1194 // We have a template template parameter
1195 else {
1196 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1197 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1198 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1199 }
1200 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1201 return ImmediatelyDeclaredConstraint;
1202
1203 // C++2a [temp.param]p4:
1204 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1205 //
1206 // We have the following case:
1207 //
1208 // template<typename T> concept C1 = true;
1209 // template<C1... T> struct s1;
1210 //
1211 // The constraint: (C1<T> && ...)
1212 //
1213 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1214 // any unqualified lookups for 'operator&&' here.
1215 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1216 /*LParenLoc=*/SourceLocation(),
1217 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1218 EllipsisLoc, /*RHS=*/nullptr,
1219 /*RParenLoc=*/SourceLocation(),
1220 /*NumExpansions=*/std::nullopt);
1221}
1222
1224 DeclarationNameInfo NameInfo,
1225 TemplateDecl *NamedConcept,
1226 NamedDecl *FoundDecl,
1227 const TemplateArgumentListInfo *TemplateArgs,
1228 TemplateTypeParmDecl *ConstrainedParameter,
1229 SourceLocation EllipsisLoc) {
1230 // C++2a [temp.param]p4:
1231 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1232 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1233 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1235 *TemplateArgs) : nullptr;
1236
1237 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1238
1239 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1240 *this, NS, NameInfo, NamedConcept, FoundDecl,
1241 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1242 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1243 ParamAsArgument, ConstrainedParameter->getLocation(),
1244 [&](TemplateArgumentListInfo &ConstraintArgs) {
1245 if (TemplateArgs)
1246 for (const auto &ArgLoc : TemplateArgs->arguments())
1247 ConstraintArgs.addArgument(ArgLoc);
1248 },
1249 EllipsisLoc);
1250 if (ImmediatelyDeclaredConstraint.isInvalid())
1251 return true;
1252
1253 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1254 /*TemplateKWLoc=*/SourceLocation{},
1255 /*ConceptNameInfo=*/NameInfo,
1256 /*FoundDecl=*/FoundDecl,
1257 /*NamedConcept=*/NamedConcept,
1258 /*ArgsWritten=*/ArgsAsWritten);
1259 ConstrainedParameter->setTypeConstraint(
1260 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1261 return false;
1262}
1263
1265 NonTypeTemplateParmDecl *NewConstrainedParm,
1266 NonTypeTemplateParmDecl *OrigConstrainedParm,
1267 SourceLocation EllipsisLoc) {
1268 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1270 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1271 diag::err_unsupported_placeholder_constraint)
1272 << NewConstrainedParm->getTypeSourceInfo()
1273 ->getTypeLoc()
1274 .getSourceRange();
1275 return true;
1276 }
1277 // FIXME: Concepts: This should be the type of the placeholder, but this is
1278 // unclear in the wording right now.
1279 DeclRefExpr *Ref =
1280 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1281 VK_PRValue, OrigConstrainedParm->getLocation());
1282 if (!Ref)
1283 return true;
1284 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1286 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1288 OrigConstrainedParm->getLocation(),
1289 [&](TemplateArgumentListInfo &ConstraintArgs) {
1290 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1291 ConstraintArgs.addArgument(TL.getArgLoc(I));
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1295 !ImmediatelyDeclaredConstraint.isUsable())
1296 return true;
1297
1298 NewConstrainedParm->setPlaceholderTypeConstraint(
1299 ImmediatelyDeclaredConstraint.get());
1300 return false;
1301}
1302
1304 SourceLocation Loc) {
1305 if (TSI->getType()->isUndeducedType()) {
1306 // C++17 [temp.dep.expr]p3:
1307 // An id-expression is type-dependent if it contains
1308 // - an identifier associated by name lookup with a non-type
1309 // template-parameter declared with a type that contains a
1310 // placeholder type (7.1.7.4),
1312 }
1313
1314 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1315}
1316
1318 if (T->isDependentType())
1319 return false;
1320
1321 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1322 return true;
1323
1324 if (T->isStructuralType())
1325 return false;
1326
1327 // Structural types are required to be object types or lvalue references.
1328 if (T->isRValueReferenceType()) {
1329 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1330 return true;
1331 }
1332
1333 // Don't mention structural types in our diagnostic prior to C++20. Also,
1334 // there's not much more we can say about non-scalar non-class types --
1335 // because we can't see functions or arrays here, those can only be language
1336 // extensions.
1337 if (!getLangOpts().CPlusPlus20 ||
1338 (!T->isScalarType() && !T->isRecordType())) {
1339 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1340 return true;
1341 }
1342
1343 // Structural types are required to be literal types.
1344 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1345 return true;
1346
1347 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1348
1349 // Drill down into the reason why the class is non-structural.
1350 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1351 // All members are required to be public and non-mutable, and can't be of
1352 // rvalue reference type. Check these conditions first to prefer a "local"
1353 // reason over a more distant one.
1354 for (const FieldDecl *FD : RD->fields()) {
1355 if (FD->getAccess() != AS_public) {
1356 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1357 return true;
1358 }
1359 if (FD->isMutable()) {
1360 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1361 return true;
1362 }
1363 if (FD->getType()->isRValueReferenceType()) {
1364 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1365 << T;
1366 return true;
1367 }
1368 }
1369
1370 // All bases are required to be public.
1371 for (const auto &BaseSpec : RD->bases()) {
1372 if (BaseSpec.getAccessSpecifier() != AS_public) {
1373 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1374 << T << 1;
1375 return true;
1376 }
1377 }
1378
1379 // All subobjects are required to be of structural types.
1380 SourceLocation SubLoc;
1381 QualType SubType;
1382 int Kind = -1;
1383
1384 for (const FieldDecl *FD : RD->fields()) {
1385 QualType T = Context.getBaseElementType(FD->getType());
1386 if (!T->isStructuralType()) {
1387 SubLoc = FD->getLocation();
1388 SubType = T;
1389 Kind = 0;
1390 break;
1391 }
1392 }
1393
1394 if (Kind == -1) {
1395 for (const auto &BaseSpec : RD->bases()) {
1396 QualType T = BaseSpec.getType();
1397 if (!T->isStructuralType()) {
1398 SubLoc = BaseSpec.getBaseTypeLoc();
1399 SubType = T;
1400 Kind = 1;
1401 break;
1402 }
1403 }
1404 }
1405
1406 assert(Kind != -1 && "couldn't find reason why type is not structural");
1407 Diag(SubLoc, diag::note_not_structural_subobject)
1408 << T << Kind << SubType;
1409 T = SubType;
1410 RD = T->getAsCXXRecordDecl();
1411 }
1412
1413 return true;
1414}
1415
1417 SourceLocation Loc) {
1418 // We don't allow variably-modified types as the type of non-type template
1419 // parameters.
1420 if (T->isVariablyModifiedType()) {
1421 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1422 << T;
1423 return QualType();
1424 }
1425
1426 // C++ [temp.param]p4:
1427 //
1428 // A non-type template-parameter shall have one of the following
1429 // (optionally cv-qualified) types:
1430 //
1431 // -- integral or enumeration type,
1432 if (T->isIntegralOrEnumerationType() ||
1433 // -- pointer to object or pointer to function,
1434 T->isPointerType() ||
1435 // -- lvalue reference to object or lvalue reference to function,
1436 T->isLValueReferenceType() ||
1437 // -- pointer to member,
1438 T->isMemberPointerType() ||
1439 // -- std::nullptr_t, or
1440 T->isNullPtrType() ||
1441 // -- a type that contains a placeholder type.
1442 T->isUndeducedType()) {
1443 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1444 // are ignored when determining its type.
1445 return T.getUnqualifiedType();
1446 }
1447
1448 // C++ [temp.param]p8:
1449 //
1450 // A non-type template-parameter of type "array of T" or
1451 // "function returning T" is adjusted to be of type "pointer to
1452 // T" or "pointer to function returning T", respectively.
1453 if (T->isArrayType() || T->isFunctionType())
1454 return Context.getDecayedType(T);
1455
1456 // If T is a dependent type, we can't do the check now, so we
1457 // assume that it is well-formed. Note that stripping off the
1458 // qualifiers here is not really correct if T turns out to be
1459 // an array type, but we'll recompute the type everywhere it's
1460 // used during instantiation, so that should be OK. (Using the
1461 // qualified type is equally wrong.)
1462 if (T->isDependentType())
1463 return T.getUnqualifiedType();
1464
1465 // C++20 [temp.param]p6:
1466 // -- a structural type
1467 if (RequireStructuralType(T, Loc))
1468 return QualType();
1469
1470 if (!getLangOpts().CPlusPlus20) {
1471 // FIXME: Consider allowing structural types as an extension in C++17. (In
1472 // earlier language modes, the template argument evaluation rules are too
1473 // inflexible.)
1474 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1475 return QualType();
1476 }
1477
1478 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1479 return T.getUnqualifiedType();
1480}
1481
1483 unsigned Depth,
1484 unsigned Position,
1485 SourceLocation EqualLoc,
1486 Expr *Default) {
1488
1489 // Check that we have valid decl-specifiers specified.
1490 auto CheckValidDeclSpecifiers = [this, &D] {
1491 // C++ [temp.param]
1492 // p1
1493 // template-parameter:
1494 // ...
1495 // parameter-declaration
1496 // p2
1497 // ... A storage class shall not be specified in a template-parameter
1498 // declaration.
1499 // [dcl.typedef]p1:
1500 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1501 // of a parameter-declaration
1502 const DeclSpec &DS = D.getDeclSpec();
1503 auto EmitDiag = [this](SourceLocation Loc) {
1504 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1506 };
1508 EmitDiag(DS.getStorageClassSpecLoc());
1509
1511 EmitDiag(DS.getThreadStorageClassSpecLoc());
1512
1513 // [dcl.inline]p1:
1514 // The inline specifier can be applied only to the declaration or
1515 // definition of a variable or function.
1516
1517 if (DS.isInlineSpecified())
1518 EmitDiag(DS.getInlineSpecLoc());
1519
1520 // [dcl.constexpr]p1:
1521 // The constexpr specifier shall be applied only to the definition of a
1522 // variable or variable template or the declaration of a function or
1523 // function template.
1524
1525 if (DS.hasConstexprSpecifier())
1526 EmitDiag(DS.getConstexprSpecLoc());
1527
1528 // [dcl.fct.spec]p1:
1529 // Function-specifiers can be used only in function declarations.
1530
1531 if (DS.isVirtualSpecified())
1532 EmitDiag(DS.getVirtualSpecLoc());
1533
1534 if (DS.hasExplicitSpecifier())
1535 EmitDiag(DS.getExplicitSpecLoc());
1536
1537 if (DS.isNoreturnSpecified())
1538 EmitDiag(DS.getNoreturnSpecLoc());
1539 };
1540
1541 CheckValidDeclSpecifiers();
1542
1543 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1544 if (isa<AutoType>(T))
1546 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1547 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1548
1549 assert(S->isTemplateParamScope() &&
1550 "Non-type template parameter not in template parameter scope!");
1551 bool Invalid = false;
1552
1554 if (T.isNull()) {
1555 T = Context.IntTy; // Recover with an 'int' type.
1556 Invalid = true;
1557 }
1558
1560
1561 const IdentifierInfo *ParamName = D.getIdentifier();
1562 bool IsParameterPack = D.hasEllipsis();
1564 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1565 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1566 TInfo);
1567 Param->setAccess(AS_public);
1568
1570 if (TL.isConstrained()) {
1571 if (D.getEllipsisLoc().isInvalid() &&
1572 T->containsUnexpandedParameterPack()) {
1573 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1574 for (auto &Loc :
1575 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1578 }
1579 if (!Invalid &&
1580 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1581 Invalid = true;
1582 }
1583
1584 if (Invalid)
1585 Param->setInvalidDecl();
1586
1587 if (Param->isParameterPack())
1588 if (auto *CSI = getEnclosingLambdaOrBlock())
1589 CSI->LocalPacks.push_back(Param);
1590
1591 if (ParamName) {
1593 ParamName);
1594
1595 // Add the template parameter into the current scope.
1596 S->AddDecl(Param);
1597 IdResolver.AddDecl(Param);
1598 }
1599
1600 // C++0x [temp.param]p9:
1601 // A default template-argument may be specified for any kind of
1602 // template-parameter that is not a template parameter pack.
1603 if (Default && IsParameterPack) {
1604 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1605 Default = nullptr;
1606 }
1607
1608 // Check the well-formedness of the default template argument, if provided.
1609 if (Default) {
1610 // Check for unexpanded parameter packs.
1612 return Param;
1613
1614 Param->setDefaultArgument(
1616 TemplateArgument(Default, /*IsCanonical=*/false),
1617 QualType(), SourceLocation()));
1618 }
1619
1620 return Param;
1621}
1622
1623/// ActOnTemplateTemplateParameter - Called when a C++ template template
1624/// parameter (e.g. T in template <template <typename> class T> class array)
1625/// has been parsed. S is the current scope.
1627 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1628 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1629 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1630 unsigned Position, SourceLocation EqualLoc,
1632 assert(S->isTemplateParamScope() &&
1633 "Template template parameter not in template parameter scope!");
1634
1635 bool IsParameterPack = EllipsisLoc.isValid();
1636
1637 bool Invalid = false;
1639 Params,
1640 /*OldParams=*/nullptr,
1641 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1642 Invalid = true;
1643
1644 // Construct the parameter object.
1646 Context, Context.getTranslationUnitDecl(),
1647 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1648 Name, Kind, Typename, Params);
1649 Param->setAccess(AS_public);
1650
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambdaOrBlock())
1653 LSI->LocalPacks.push_back(Param);
1654
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1657 if (Name) {
1658 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1659
1660 S->AddDecl(Param);
1661 IdResolver.AddDecl(Param);
1662 }
1663
1664 if (Params->size() == 0) {
1665 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1666 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1667 Invalid = true;
1668 }
1669
1670 if (Invalid)
1671 Param->setInvalidDecl();
1672
1673 // C++0x [temp.param]p9:
1674 // A default template-argument may be specified for any kind of
1675 // template-parameter that is not a template parameter pack.
1676 if (IsParameterPack && !Default.isInvalid()) {
1677 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1679 }
1680
1681 if (!Default.isInvalid()) {
1682 // Check only that we have a template template argument. We don't want to
1683 // try to check well-formedness now, because our template template parameter
1684 // might have dependent types in its template parameters, which we wouldn't
1685 // be able to match now.
1686 //
1687 // If none of the template template parameter's template arguments mention
1688 // other template parameters, we could actually perform more checking here.
1689 // However, it isn't worth doing.
1691 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1692 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1693 << DefaultArg.getSourceRange();
1694 return Param;
1695 }
1696
1697 TemplateName Name =
1700 if (Template &&
1702 return Param;
1703 }
1704
1705 // Check for unexpanded parameter packs.
1707 DefaultArg.getArgument().getAsTemplate(),
1709 return Param;
1710
1711 Param->setDefaultArgument(Context, DefaultArg);
1712 }
1713
1714 return Param;
1715}
1716
1717namespace {
1718class ConstraintRefersToContainingTemplateChecker
1720 using inherited = ConstDynamicRecursiveASTVisitor;
1721 bool Result = false;
1722 const FunctionDecl *Friend = nullptr;
1723 unsigned TemplateDepth = 0;
1724
1725 // Check a record-decl that we've seen to see if it is a lexical parent of the
1726 // Friend, likely because it was referred to without its template arguments.
1727 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1728 CheckingRD = CheckingRD->getMostRecentDecl();
1729 if (!CheckingRD->isTemplated())
1730 return true;
1731
1732 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1733 DC && !DC->isFileContext(); DC = DC->getParent())
1734 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1735 if (CheckingRD == RD->getMostRecentDecl()) {
1736 Result = true;
1737 return false;
1738 }
1739
1740 return true;
1741 }
1742
1743 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1744 if (D->getDepth() < TemplateDepth)
1745 Result = true;
1746
1747 // Necessary because the type of the NTTP might be what refers to the parent
1748 // constriant.
1749 return TraverseType(D->getType());
1750 }
1751
1752public:
1753 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1754 unsigned TemplateDepth)
1755 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1756
1757 bool getResult() const { return Result; }
1758
1759 // This should be the only template parm type that we have to deal with.
1760 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1761 // FunctionParmPackExpr are all partially substituted, which cannot happen
1762 // with concepts at this point in translation.
1763 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1764 if (Type->getDecl()->getDepth() < TemplateDepth) {
1765 Result = true;
1766 return false;
1767 }
1768 return true;
1769 }
1770
1771 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1772 return TraverseDecl(E->getDecl());
1773 }
1774
1775 bool TraverseTypedefType(const TypedefType *TT,
1776 bool /*TraverseQualifier*/) override {
1777 return TraverseType(TT->desugar());
1778 }
1779
1780 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1781 // We don't care about TypeLocs. So traverse Types instead.
1782 return TraverseType(TL.getType(), TraverseQualifier);
1783 }
1784
1785 bool VisitTagType(const TagType *T) override {
1786 return TraverseDecl(T->getOriginalDecl());
1787 }
1788
1789 bool TraverseDecl(const Decl *D) override {
1790 assert(D);
1791 // FIXME : This is possibly an incomplete list, but it is unclear what other
1792 // Decl kinds could be used to refer to the template parameters. This is a
1793 // best guess so far based on examples currently available, but the
1794 // unreachable should catch future instances/cases.
1795 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1796 return TraverseType(TD->getUnderlyingType());
1797 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1798 return CheckNonTypeTemplateParmDecl(NTTPD);
1799 if (auto *VD = dyn_cast<ValueDecl>(D))
1800 return TraverseType(VD->getType());
1801 if (isa<TemplateDecl>(D))
1802 return true;
1803 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1804 return CheckIfContainingRecord(RD);
1805
1807 // No direct types to visit here I believe.
1808 } else
1809 llvm_unreachable("Don't know how to handle this declaration type yet");
1810 return true;
1811 }
1812};
1813} // namespace
1814
1816 const FunctionDecl *Friend, unsigned TemplateDepth,
1817 const Expr *Constraint) {
1818 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1819 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1820 Checker.TraverseStmt(Constraint);
1821 return Checker.getResult();
1822}
1823
1826 SourceLocation ExportLoc,
1827 SourceLocation TemplateLoc,
1828 SourceLocation LAngleLoc,
1829 ArrayRef<NamedDecl *> Params,
1830 SourceLocation RAngleLoc,
1831 Expr *RequiresClause) {
1832 if (ExportLoc.isValid())
1833 Diag(ExportLoc, diag::warn_template_export_unsupported);
1834
1835 for (NamedDecl *P : Params)
1837
1838 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1839 llvm::ArrayRef(Params), RAngleLoc,
1840 RequiresClause);
1841}
1842
1844 const CXXScopeSpec &SS) {
1845 if (SS.isSet())
1846 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1847}
1848
1849// Returns the template parameter list with all default template argument
1850// information.
1852 // Make sure we get the template parameter list from the most
1853 // recent declaration, since that is the only one that is guaranteed to
1854 // have all the default template argument information.
1855 Decl *D = TD->getMostRecentDecl();
1856 // C++11 N3337 [temp.param]p12:
1857 // A default template argument shall not be specified in a friend class
1858 // template declaration.
1859 //
1860 // Skip past friend *declarations* because they are not supposed to contain
1861 // default template arguments. Moreover, these declarations may introduce
1862 // template parameters living in different template depths than the
1863 // corresponding template parameters in TD, causing unmatched constraint
1864 // substitution.
1865 //
1866 // FIXME: Diagnose such cases within a class template:
1867 // template <class T>
1868 // struct S {
1869 // template <class = void> friend struct C;
1870 // };
1871 // template struct S<int>;
1873 D->getPreviousDecl())
1874 D = D->getPreviousDecl();
1875 return cast<TemplateDecl>(D)->getTemplateParameters();
1876}
1877
1879 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1880 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1881 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1882 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1883 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1884 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1885 assert(TemplateParams && TemplateParams->size() > 0 &&
1886 "No template parameters");
1887 assert(TUK != TagUseKind::Reference &&
1888 "Can only declare or define class templates");
1889 bool Invalid = false;
1890
1891 // Check that we can declare a template here.
1892 if (CheckTemplateDeclScope(S, TemplateParams))
1893 return true;
1894
1896 assert(Kind != TagTypeKind::Enum &&
1897 "can't build template of enumerated type");
1898
1899 // There is no such thing as an unnamed class template.
1900 if (!Name) {
1901 Diag(KWLoc, diag::err_template_unnamed_class);
1902 return true;
1903 }
1904
1905 // Find any previous declaration with this name. For a friend with no
1906 // scope explicitly specified, we only look for tag declarations (per
1907 // C++11 [basic.lookup.elab]p2).
1908 DeclContext *SemanticContext;
1909 LookupResult Previous(*this, Name, NameLoc,
1910 (SS.isEmpty() && TUK == TagUseKind::Friend)
1914 if (SS.isNotEmpty() && !SS.isInvalid()) {
1915 SemanticContext = computeDeclContext(SS, true);
1916 if (!SemanticContext) {
1917 // FIXME: Horrible, horrible hack! We can't currently represent this
1918 // in the AST, and historically we have just ignored such friend
1919 // class templates, so don't complain here.
1920 Diag(NameLoc, TUK == TagUseKind::Friend
1921 ? diag::warn_template_qualified_friend_ignored
1922 : diag::err_template_qualified_declarator_no_match)
1923 << SS.getScopeRep() << SS.getRange();
1924 return TUK != TagUseKind::Friend;
1925 }
1926
1927 if (RequireCompleteDeclContext(SS, SemanticContext))
1928 return true;
1929
1930 // If we're adding a template to a dependent context, we may need to
1931 // rebuilding some of the types used within the template parameter list,
1932 // now that we know what the current instantiation is.
1933 if (SemanticContext->isDependentContext()) {
1934 ContextRAII SavedContext(*this, SemanticContext);
1936 Invalid = true;
1937 }
1938
1939 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1940 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1941 /*TemplateId-*/ nullptr,
1942 /*IsMemberSpecialization*/ false);
1943
1944 LookupQualifiedName(Previous, SemanticContext);
1945 } else {
1946 SemanticContext = CurContext;
1947
1948 // C++14 [class.mem]p14:
1949 // If T is the name of a class, then each of the following shall have a
1950 // name different from T:
1951 // -- every member template of class T
1952 if (TUK != TagUseKind::Friend &&
1953 DiagnoseClassNameShadow(SemanticContext,
1954 DeclarationNameInfo(Name, NameLoc)))
1955 return true;
1956
1957 LookupName(Previous, S);
1958 }
1959
1960 if (Previous.isAmbiguous())
1961 return true;
1962
1963 // Let the template parameter scope enter the lookup chain of the current
1964 // class template. For example, given
1965 //
1966 // namespace ns {
1967 // template <class> bool Param = false;
1968 // template <class T> struct N;
1969 // }
1970 //
1971 // template <class Param> struct ns::N { void foo(Param); };
1972 //
1973 // When we reference Param inside the function parameter list, our name lookup
1974 // chain for it should be like:
1975 // FunctionScope foo
1976 // -> RecordScope N
1977 // -> TemplateParamScope (where we will find Param)
1978 // -> NamespaceScope ns
1979 //
1980 // See also CppLookupName().
1981 if (S->isTemplateParamScope())
1982 EnterTemplatedContext(S, SemanticContext);
1983
1984 NamedDecl *PrevDecl = nullptr;
1985 if (Previous.begin() != Previous.end())
1986 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1987
1988 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1989 // Maybe we will complain about the shadowed template parameter.
1990 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1991 // Just pretend that we didn't see the previous declaration.
1992 PrevDecl = nullptr;
1993 }
1994
1995 // If there is a previous declaration with the same name, check
1996 // whether this is a valid redeclaration.
1997 ClassTemplateDecl *PrevClassTemplate =
1998 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1999
2000 // We may have found the injected-class-name of a class template,
2001 // class template partial specialization, or class template specialization.
2002 // In these cases, grab the template that is being defined or specialized.
2003 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2004 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2005 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2006 PrevClassTemplate
2007 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2008 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2009 PrevClassTemplate
2011 ->getSpecializedTemplate();
2012 }
2013 }
2014
2015 if (TUK == TagUseKind::Friend) {
2016 // C++ [namespace.memdef]p3:
2017 // [...] When looking for a prior declaration of a class or a function
2018 // declared as a friend, and when the name of the friend class or
2019 // function is neither a qualified name nor a template-id, scopes outside
2020 // the innermost enclosing namespace scope are not considered.
2021 if (!SS.isSet()) {
2022 DeclContext *OutermostContext = CurContext;
2023 while (!OutermostContext->isFileContext())
2024 OutermostContext = OutermostContext->getLookupParent();
2025
2026 if (PrevDecl &&
2027 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2028 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2029 SemanticContext = PrevDecl->getDeclContext();
2030 } else {
2031 // Declarations in outer scopes don't matter. However, the outermost
2032 // context we computed is the semantic context for our new
2033 // declaration.
2034 PrevDecl = PrevClassTemplate = nullptr;
2035 SemanticContext = OutermostContext;
2036
2037 // Check that the chosen semantic context doesn't already contain a
2038 // declaration of this name as a non-tag type.
2040 DeclContext *LookupContext = SemanticContext;
2041 while (LookupContext->isTransparentContext())
2042 LookupContext = LookupContext->getLookupParent();
2043 LookupQualifiedName(Previous, LookupContext);
2044
2045 if (Previous.isAmbiguous())
2046 return true;
2047
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050 }
2051 }
2052 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2053 SemanticContext, S, SS.isValid()))
2054 PrevDecl = PrevClassTemplate = nullptr;
2055
2056 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2057 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2058 if (SS.isEmpty() &&
2059 !(PrevClassTemplate &&
2060 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2061 SemanticContext->getRedeclContext()))) {
2062 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2063 Diag(Shadow->getTargetDecl()->getLocation(),
2064 diag::note_using_decl_target);
2065 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2066 // Recover by ignoring the old declaration.
2067 PrevDecl = PrevClassTemplate = nullptr;
2068 }
2069 }
2070
2071 if (PrevClassTemplate) {
2072 // Ensure that the template parameter lists are compatible. Skip this check
2073 // for a friend in a dependent context: the template parameter list itself
2074 // could be dependent.
2075 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2077 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2078 : CurContext,
2079 CurContext, KWLoc),
2080 TemplateParams, PrevClassTemplate,
2081 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2083 return true;
2084
2085 // C++ [temp.class]p4:
2086 // In a redeclaration, partial specialization, explicit
2087 // specialization or explicit instantiation of a class template,
2088 // the class-key shall agree in kind with the original class
2089 // template declaration (7.1.5.3).
2090 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2092 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2093 Diag(KWLoc, diag::err_use_with_wrong_tag)
2094 << Name
2095 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2096 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2097 Kind = PrevRecordDecl->getTagKind();
2098 }
2099
2100 // Check for redefinition of this class template.
2101 if (TUK == TagUseKind::Definition) {
2102 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2103 // If we have a prior definition that is not visible, treat this as
2104 // simply making that previous definition visible.
2105 NamedDecl *Hidden = nullptr;
2106 bool HiddenDefVisible = false;
2107 if (SkipBody &&
2108 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2109 SkipBody->ShouldSkip = true;
2110 SkipBody->Previous = Def;
2111 if (!HiddenDefVisible && Hidden) {
2112 auto *Tmpl =
2113 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2114 assert(Tmpl && "original definition of a class template is not a "
2115 "class template?");
2118 }
2119 } else {
2120 Diag(NameLoc, diag::err_redefinition) << Name;
2121 Diag(Def->getLocation(), diag::note_previous_definition);
2122 // FIXME: Would it make sense to try to "forget" the previous
2123 // definition, as part of error recovery?
2124 return true;
2125 }
2126 }
2127 }
2128 } else if (PrevDecl) {
2129 // C++ [temp]p5:
2130 // A class template shall not have the same name as any other
2131 // template, class, function, object, enumeration, enumerator,
2132 // namespace, or type in the same scope (3.3), except as specified
2133 // in (14.5.4).
2134 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2135 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2136 return true;
2137 }
2138
2139 // Check the template parameter list of this declaration, possibly
2140 // merging in the template parameter list from the previous class
2141 // template declaration. Skip this check for a friend in a dependent
2142 // context, because the template parameter list might be dependent.
2143 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2145 TemplateParams,
2146 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2147 : nullptr,
2148 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2149 SemanticContext->isDependentContext())
2152 : TPC_Other,
2153 SkipBody))
2154 Invalid = true;
2155
2156 if (SS.isSet()) {
2157 // If the name of the template was qualified, we must be defining the
2158 // template out-of-line.
2159 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2160 Diag(NameLoc, TUK == TagUseKind::Friend
2161 ? diag::err_friend_decl_does_not_match
2162 : diag::err_member_decl_does_not_match)
2163 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2164 Invalid = true;
2165 }
2166 }
2167
2168 // If this is a templated friend in a dependent context we should not put it
2169 // on the redecl chain. In some cases, the templated friend can be the most
2170 // recent declaration tricking the template instantiator to make substitutions
2171 // there.
2172 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2173 bool ShouldAddRedecl =
2174 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2175
2177 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2178 PrevClassTemplate && ShouldAddRedecl
2179 ? PrevClassTemplate->getTemplatedDecl()
2180 : nullptr);
2181 SetNestedNameSpecifier(*this, NewClass, SS);
2182 if (NumOuterTemplateParamLists > 0)
2184 Context,
2185 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2186
2187 // Add alignment attributes if necessary; these attributes are checked when
2188 // the ASTContext lays out the structure.
2189 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2190 if (LangOpts.HLSL)
2191 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2194 }
2195
2196 ClassTemplateDecl *NewTemplate
2197 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2198 DeclarationName(Name), TemplateParams,
2199 NewClass);
2200
2201 if (ShouldAddRedecl)
2202 NewTemplate->setPreviousDecl(PrevClassTemplate);
2203
2204 NewClass->setDescribedClassTemplate(NewTemplate);
2205
2206 if (ModulePrivateLoc.isValid())
2207 NewTemplate->setModulePrivate();
2208
2209 // If we are providing an explicit specialization of a member that is a
2210 // class template, make a note of that.
2211 if (PrevClassTemplate &&
2212 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2213 PrevClassTemplate->setMemberSpecialization();
2214
2215 // Set the access specifier.
2216 if (!Invalid && TUK != TagUseKind::Friend &&
2217 NewTemplate->getDeclContext()->isRecord())
2218 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2219
2220 // Set the lexical context of these templates
2222 NewTemplate->setLexicalDeclContext(CurContext);
2223
2224 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2225 NewClass->startDefinition();
2226
2227 ProcessDeclAttributeList(S, NewClass, Attr);
2228
2229 if (PrevClassTemplate)
2230 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2231
2235
2236 if (TUK != TagUseKind::Friend) {
2237 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2238 Scope *Outer = S;
2239 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2240 Outer = Outer->getParent();
2241 PushOnScopeChains(NewTemplate, Outer);
2242 } else {
2243 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2244 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2245 NewClass->setAccess(PrevClassTemplate->getAccess());
2246 }
2247
2248 NewTemplate->setObjectOfFriendDecl();
2249
2250 // Friend templates are visible in fairly strange ways.
2251 if (!CurContext->isDependentContext()) {
2252 DeclContext *DC = SemanticContext->getRedeclContext();
2253 DC->makeDeclVisibleInContext(NewTemplate);
2254 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2255 PushOnScopeChains(NewTemplate, EnclosingScope,
2256 /* AddToContext = */ false);
2257 }
2258
2260 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2261 Friend->setAccess(AS_public);
2262 CurContext->addDecl(Friend);
2263 }
2264
2265 if (PrevClassTemplate)
2266 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2267
2268 if (Invalid) {
2269 NewTemplate->setInvalidDecl();
2270 NewClass->setInvalidDecl();
2271 }
2272
2273 ActOnDocumentableDecl(NewTemplate);
2274
2275 if (SkipBody && SkipBody->ShouldSkip)
2276 return SkipBody->Previous;
2277
2278 return NewTemplate;
2279}
2280
2281/// Diagnose the presence of a default template argument on a
2282/// template parameter, which is ill-formed in certain contexts.
2283///
2284/// \returns true if the default template argument should be dropped.
2287 SourceLocation ParamLoc,
2288 SourceRange DefArgRange) {
2289 switch (TPC) {
2290 case Sema::TPC_Other:
2292 return false;
2293
2296 // C++ [temp.param]p9:
2297 // A default template-argument shall not be specified in a
2298 // function template declaration or a function template
2299 // definition [...]
2300 // If a friend function template declaration specifies a default
2301 // template-argument, that declaration shall be a definition and shall be
2302 // the only declaration of the function template in the translation unit.
2303 // (C++98/03 doesn't have this wording; see DR226).
2304 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2305 << DefArgRange;
2306 return false;
2307
2309 // C++0x [temp.param]p9:
2310 // A default template-argument shall not be specified in the
2311 // template-parameter-lists of the definition of a member of a
2312 // class template that appears outside of the member's class.
2313 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2314 << DefArgRange;
2315 return true;
2316
2319 // C++ [temp.param]p9:
2320 // A default template-argument shall not be specified in a
2321 // friend template declaration.
2322 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2323 << DefArgRange;
2324 return true;
2325
2326 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2327 // for friend function templates if there is only a single
2328 // declaration (and it is a definition). Strange!
2329 }
2330
2331 llvm_unreachable("Invalid TemplateParamListContext!");
2332}
2333
2334/// Check for unexpanded parameter packs within the template parameters
2335/// of a template template parameter, recursively.
2338 // A template template parameter which is a parameter pack is also a pack
2339 // expansion.
2340 if (TTP->isParameterPack())
2341 return false;
2342
2344 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2345 NamedDecl *P = Params->getParam(I);
2346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2347 if (!TTP->isParameterPack())
2348 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2349 if (TC->hasExplicitTemplateArgs())
2350 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2353 return true;
2354 continue;
2355 }
2356
2357 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2358 if (!NTTP->isParameterPack() &&
2359 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2360 NTTP->getTypeSourceInfo(),
2362 return true;
2363
2364 continue;
2365 }
2366
2367 if (TemplateTemplateParmDecl *InnerTTP
2368 = dyn_cast<TemplateTemplateParmDecl>(P))
2369 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2370 return true;
2371 }
2372
2373 return false;
2374}
2375
2377 TemplateParameterList *OldParams,
2379 SkipBodyInfo *SkipBody) {
2380 bool Invalid = false;
2381
2382 // C++ [temp.param]p10:
2383 // The set of default template-arguments available for use with a
2384 // template declaration or definition is obtained by merging the
2385 // default arguments from the definition (if in scope) and all
2386 // declarations in scope in the same way default function
2387 // arguments are (8.3.6).
2388 bool SawDefaultArgument = false;
2389 SourceLocation PreviousDefaultArgLoc;
2390
2391 // Dummy initialization to avoid warnings.
2392 TemplateParameterList::iterator OldParam = NewParams->end();
2393 if (OldParams)
2394 OldParam = OldParams->begin();
2395
2396 bool RemoveDefaultArguments = false;
2397 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2398 NewParamEnd = NewParams->end();
2399 NewParam != NewParamEnd; ++NewParam) {
2400 // Whether we've seen a duplicate default argument in the same translation
2401 // unit.
2402 bool RedundantDefaultArg = false;
2403 // Whether we've found inconsis inconsitent default arguments in different
2404 // translation unit.
2405 bool InconsistentDefaultArg = false;
2406 // The name of the module which contains the inconsistent default argument.
2407 std::string PrevModuleName;
2408
2409 SourceLocation OldDefaultLoc;
2410 SourceLocation NewDefaultLoc;
2411
2412 // Variable used to diagnose missing default arguments
2413 bool MissingDefaultArg = false;
2414
2415 // Variable used to diagnose non-final parameter packs
2416 bool SawParameterPack = false;
2417
2418 if (TemplateTypeParmDecl *NewTypeParm
2419 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2420 // Check the presence of a default argument here.
2421 if (NewTypeParm->hasDefaultArgument() &&
2423 *this, TPC, NewTypeParm->getLocation(),
2424 NewTypeParm->getDefaultArgument().getSourceRange()))
2425 NewTypeParm->removeDefaultArgument();
2426
2427 // Merge default arguments for template type parameters.
2428 TemplateTypeParmDecl *OldTypeParm
2429 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2430 if (NewTypeParm->isParameterPack()) {
2431 assert(!NewTypeParm->hasDefaultArgument() &&
2432 "Parameter packs can't have a default argument!");
2433 SawParameterPack = true;
2434 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2435 NewTypeParm->hasDefaultArgument() &&
2436 (!SkipBody || !SkipBody->ShouldSkip)) {
2437 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2438 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2439 SawDefaultArgument = true;
2440
2441 if (!OldTypeParm->getOwningModule())
2442 RedundantDefaultArg = true;
2443 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2444 NewTypeParm)) {
2445 InconsistentDefaultArg = true;
2446 PrevModuleName =
2448 }
2449 PreviousDefaultArgLoc = NewDefaultLoc;
2450 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2451 // Merge the default argument from the old declaration to the
2452 // new declaration.
2453 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2454 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2455 } else if (NewTypeParm->hasDefaultArgument()) {
2456 SawDefaultArgument = true;
2457 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2458 } else if (SawDefaultArgument)
2459 MissingDefaultArg = true;
2460 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2461 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2462 // Check for unexpanded parameter packs, except in a template template
2463 // parameter pack, as in those any unexpanded packs should be expanded
2464 // along with the parameter itself.
2466 !NewNonTypeParm->isParameterPack() &&
2467 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2468 NewNonTypeParm->getTypeSourceInfo(),
2470 Invalid = true;
2471 continue;
2472 }
2473
2474 // Check the presence of a default argument here.
2475 if (NewNonTypeParm->hasDefaultArgument() &&
2477 *this, TPC, NewNonTypeParm->getLocation(),
2478 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2479 NewNonTypeParm->removeDefaultArgument();
2480 }
2481
2482 // Merge default arguments for non-type template parameters
2483 NonTypeTemplateParmDecl *OldNonTypeParm
2484 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2485 if (NewNonTypeParm->isParameterPack()) {
2486 assert(!NewNonTypeParm->hasDefaultArgument() &&
2487 "Parameter packs can't have a default argument!");
2488 if (!NewNonTypeParm->isPackExpansion())
2489 SawParameterPack = true;
2490 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2491 NewNonTypeParm->hasDefaultArgument() &&
2492 (!SkipBody || !SkipBody->ShouldSkip)) {
2493 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2494 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2495 SawDefaultArgument = true;
2496 if (!OldNonTypeParm->getOwningModule())
2497 RedundantDefaultArg = true;
2498 else if (!getASTContext().isSameDefaultTemplateArgument(
2499 OldNonTypeParm, NewNonTypeParm)) {
2500 InconsistentDefaultArg = true;
2501 PrevModuleName =
2502 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2503 }
2504 PreviousDefaultArgLoc = NewDefaultLoc;
2505 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2506 // Merge the default argument from the old declaration to the
2507 // new declaration.
2508 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2509 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2510 } else if (NewNonTypeParm->hasDefaultArgument()) {
2511 SawDefaultArgument = true;
2512 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2513 } else if (SawDefaultArgument)
2514 MissingDefaultArg = true;
2515 } else {
2516 TemplateTemplateParmDecl *NewTemplateParm
2517 = cast<TemplateTemplateParmDecl>(*NewParam);
2518
2519 // Check for unexpanded parameter packs, recursively.
2520 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2521 Invalid = true;
2522 continue;
2523 }
2524
2525 // Check the presence of a default argument here.
2526 if (NewTemplateParm->hasDefaultArgument() &&
2528 NewTemplateParm->getLocation(),
2529 NewTemplateParm->getDefaultArgument().getSourceRange()))
2530 NewTemplateParm->removeDefaultArgument();
2531
2532 // Merge default arguments for template template parameters
2533 TemplateTemplateParmDecl *OldTemplateParm
2534 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2535 if (NewTemplateParm->isParameterPack()) {
2536 assert(!NewTemplateParm->hasDefaultArgument() &&
2537 "Parameter packs can't have a default argument!");
2538 if (!NewTemplateParm->isPackExpansion())
2539 SawParameterPack = true;
2540 } else if (OldTemplateParm &&
2541 hasVisibleDefaultArgument(OldTemplateParm) &&
2542 NewTemplateParm->hasDefaultArgument() &&
2543 (!SkipBody || !SkipBody->ShouldSkip)) {
2544 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2545 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2546 SawDefaultArgument = true;
2547 if (!OldTemplateParm->getOwningModule())
2548 RedundantDefaultArg = true;
2549 else if (!getASTContext().isSameDefaultTemplateArgument(
2550 OldTemplateParm, NewTemplateParm)) {
2551 InconsistentDefaultArg = true;
2552 PrevModuleName =
2553 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2554 }
2555 PreviousDefaultArgLoc = NewDefaultLoc;
2556 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2557 // Merge the default argument from the old declaration to the
2558 // new declaration.
2559 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2560 PreviousDefaultArgLoc
2561 = OldTemplateParm->getDefaultArgument().getLocation();
2562 } else if (NewTemplateParm->hasDefaultArgument()) {
2563 SawDefaultArgument = true;
2564 PreviousDefaultArgLoc
2565 = NewTemplateParm->getDefaultArgument().getLocation();
2566 } else if (SawDefaultArgument)
2567 MissingDefaultArg = true;
2568 }
2569
2570 // C++11 [temp.param]p11:
2571 // If a template parameter of a primary class template or alias template
2572 // is a template parameter pack, it shall be the last template parameter.
2573 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2574 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2575 Diag((*NewParam)->getLocation(),
2576 diag::err_template_param_pack_must_be_last_template_parameter);
2577 Invalid = true;
2578 }
2579
2580 // [basic.def.odr]/13:
2581 // There can be more than one definition of a
2582 // ...
2583 // default template argument
2584 // ...
2585 // in a program provided that each definition appears in a different
2586 // translation unit and the definitions satisfy the [same-meaning
2587 // criteria of the ODR].
2588 //
2589 // Simply, the design of modules allows the definition of template default
2590 // argument to be repeated across translation unit. Note that the ODR is
2591 // checked elsewhere. But it is still not allowed to repeat template default
2592 // argument in the same translation unit.
2593 if (RedundantDefaultArg) {
2594 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2595 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2596 Invalid = true;
2597 } else if (InconsistentDefaultArg) {
2598 // We could only diagnose about the case that the OldParam is imported.
2599 // The case NewParam is imported should be handled in ASTReader.
2600 Diag(NewDefaultLoc,
2601 diag::err_template_param_default_arg_inconsistent_redefinition);
2602 Diag(OldDefaultLoc,
2603 diag::note_template_param_prev_default_arg_in_other_module)
2604 << PrevModuleName;
2605 Invalid = true;
2606 } else if (MissingDefaultArg &&
2607 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2608 TPC == TPC_FriendClassTemplate)) {
2609 // C++ 23[temp.param]p14:
2610 // If a template-parameter of a class template, variable template, or
2611 // alias template has a default template argument, each subsequent
2612 // template-parameter shall either have a default template argument
2613 // supplied or be a template parameter pack.
2614 Diag((*NewParam)->getLocation(),
2615 diag::err_template_param_default_arg_missing);
2616 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2617 Invalid = true;
2618 RemoveDefaultArguments = true;
2619 }
2620
2621 // If we have an old template parameter list that we're merging
2622 // in, move on to the next parameter.
2623 if (OldParams)
2624 ++OldParam;
2625 }
2626
2627 // We were missing some default arguments at the end of the list, so remove
2628 // all of the default arguments.
2629 if (RemoveDefaultArguments) {
2630 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2631 NewParamEnd = NewParams->end();
2632 NewParam != NewParamEnd; ++NewParam) {
2633 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2634 TTP->removeDefaultArgument();
2635 else if (NonTypeTemplateParmDecl *NTTP
2636 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2637 NTTP->removeDefaultArgument();
2638 else
2639 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2640 }
2641 }
2642
2643 return Invalid;
2644}
2645
2646namespace {
2647
2648/// A class which looks for a use of a certain level of template
2649/// parameter.
2650struct DependencyChecker : DynamicRecursiveASTVisitor {
2651 unsigned Depth;
2652
2653 // Whether we're looking for a use of a template parameter that makes the
2654 // overall construct type-dependent / a dependent type. This is strictly
2655 // best-effort for now; we may fail to match at all for a dependent type
2656 // in some cases if this is set.
2657 bool IgnoreNonTypeDependent;
2658
2659 bool Match;
2660 SourceLocation MatchLoc;
2661
2662 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2663 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2664 Match(false) {}
2665
2666 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2667 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2668 NamedDecl *ND = Params->getParam(0);
2669 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2670 Depth = PD->getDepth();
2671 } else if (NonTypeTemplateParmDecl *PD =
2672 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2673 Depth = PD->getDepth();
2674 } else {
2675 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2676 }
2677 }
2678
2679 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2680 if (ParmDepth >= Depth) {
2681 Match = true;
2682 MatchLoc = Loc;
2683 return true;
2684 }
2685 return false;
2686 }
2687
2688 bool TraverseStmt(Stmt *S) override {
2689 // Prune out non-type-dependent expressions if requested. This can
2690 // sometimes result in us failing to find a template parameter reference
2691 // (if a value-dependent expression creates a dependent type), but this
2692 // mode is best-effort only.
2693 if (auto *E = dyn_cast_or_null<Expr>(S))
2694 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2695 return true;
2697 }
2698
2699 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2700 if (IgnoreNonTypeDependent && !TL.isNull() &&
2701 !TL.getType()->isDependentType())
2702 return true;
2703 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2704 }
2705
2706 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2707 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2708 }
2709
2710 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2711 // For a best-effort search, keep looking until we find a location.
2712 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2713 }
2714
2715 bool TraverseTemplateName(TemplateName N) override {
2716 if (TemplateTemplateParmDecl *PD =
2717 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2718 if (Matches(PD->getDepth()))
2719 return false;
2721 }
2722
2723 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2724 if (NonTypeTemplateParmDecl *PD =
2725 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2726 if (Matches(PD->getDepth(), E->getExprLoc()))
2727 return false;
2728 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2729 }
2730
2731 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2732 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2733 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2734 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2735 return false;
2736 }
2737 for (auto &TLoc : ULE->template_arguments())
2739 }
2740 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2741 }
2742
2743 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2744 return TraverseType(T->getReplacementType());
2745 }
2746
2747 bool VisitSubstTemplateTypeParmPackType(
2748 SubstTemplateTypeParmPackType *T) override {
2749 return TraverseTemplateArgument(T->getArgumentPack());
2750 }
2751
2752 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2753 bool TraverseQualifier) override {
2754 // An InjectedClassNameType will never have a dependent template name,
2755 // so no need to traverse it.
2756 return TraverseTemplateArguments(
2757 T->getTemplateArgs(T->getOriginalDecl()->getASTContext()));
2758 }
2759};
2760} // end anonymous namespace
2761
2762/// Determines whether a given type depends on the given parameter
2763/// list.
2764static bool
2766 if (!Params->size())
2767 return false;
2768
2769 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2770 Checker.TraverseType(T);
2771 return Checker.Match;
2772}
2773
2774// Find the source range corresponding to the named type in the given
2775// nested-name-specifier, if any.
2777 QualType T,
2778 const CXXScopeSpec &SS) {
2780 for (;;) {
2783 break;
2784 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2785 return NNSLoc.castAsTypeLoc().getSourceRange();
2786 // FIXME: This will always be empty.
2787 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2788 }
2789
2790 return SourceRange();
2791}
2792
2794 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2795 TemplateIdAnnotation *TemplateId,
2796 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2797 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2798 IsMemberSpecialization = false;
2799 Invalid = false;
2800
2801 // The sequence of nested types to which we will match up the template
2802 // parameter lists. We first build this list by starting with the type named
2803 // by the nested-name-specifier and walking out until we run out of types.
2804 SmallVector<QualType, 4> NestedTypes;
2805 QualType T;
2806 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2807 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2808 if (CXXRecordDecl *Record =
2809 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2810 T = Context.getCanonicalTagType(Record);
2811 else
2812 T = QualType(Qualifier.getAsType(), 0);
2813 }
2814
2815 // If we found an explicit specialization that prevents us from needing
2816 // 'template<>' headers, this will be set to the location of that
2817 // explicit specialization.
2818 SourceLocation ExplicitSpecLoc;
2819
2820 while (!T.isNull()) {
2821 NestedTypes.push_back(T);
2822
2823 // Retrieve the parent of a record type.
2824 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2825 // If this type is an explicit specialization, we're done.
2827 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2829 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2830 ExplicitSpecLoc = Spec->getLocation();
2831 break;
2832 }
2833 } else if (Record->getTemplateSpecializationKind()
2835 ExplicitSpecLoc = Record->getLocation();
2836 break;
2837 }
2838
2839 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2840 T = Context.getTypeDeclType(Parent);
2841 else
2842 T = QualType();
2843 continue;
2844 }
2845
2846 if (const TemplateSpecializationType *TST
2847 = T->getAs<TemplateSpecializationType>()) {
2848 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2849 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2850 T = Context.getTypeDeclType(Parent);
2851 else
2852 T = QualType();
2853 continue;
2854 }
2855 }
2856
2857 // Look one step prior in a dependent template specialization type.
2858 if (const DependentTemplateSpecializationType *DependentTST
2859 = T->getAs<DependentTemplateSpecializationType>()) {
2860 if (NestedNameSpecifier NNS =
2861 DependentTST->getDependentTemplateName().getQualifier();
2863 T = QualType(NNS.getAsType(), 0);
2864 else
2865 T = QualType();
2866 continue;
2867 }
2868
2869 // Look one step prior in a dependent name type.
2870 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2871 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2873 T = QualType(NNS.getAsType(), 0);
2874 else
2875 T = QualType();
2876 continue;
2877 }
2878
2879 // Retrieve the parent of an enumeration type.
2880 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2881 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2882 // check here.
2883 EnumDecl *Enum = EnumT->getOriginalDecl();
2884
2885 // Get to the parent type.
2886 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2887 T = Context.getCanonicalTypeDeclType(Parent);
2888 else
2889 T = QualType();
2890 continue;
2891 }
2892
2893 T = QualType();
2894 }
2895 // Reverse the nested types list, since we want to traverse from the outermost
2896 // to the innermost while checking template-parameter-lists.
2897 std::reverse(NestedTypes.begin(), NestedTypes.end());
2898
2899 // C++0x [temp.expl.spec]p17:
2900 // A member or a member template may be nested within many
2901 // enclosing class templates. In an explicit specialization for
2902 // such a member, the member declaration shall be preceded by a
2903 // template<> for each enclosing class template that is
2904 // explicitly specialized.
2905 bool SawNonEmptyTemplateParameterList = false;
2906
2907 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2908 if (SawNonEmptyTemplateParameterList) {
2909 if (!SuppressDiagnostic)
2910 Diag(DeclLoc, diag::err_specialize_member_of_template)
2911 << !Recovery << Range;
2912 Invalid = true;
2913 IsMemberSpecialization = false;
2914 return true;
2915 }
2916
2917 return false;
2918 };
2919
2920 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2921 // Check that we can have an explicit specialization here.
2922 if (CheckExplicitSpecialization(Range, true))
2923 return true;
2924
2925 // We don't have a template header, but we should.
2926 SourceLocation ExpectedTemplateLoc;
2927 if (!ParamLists.empty())
2928 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2929 else
2930 ExpectedTemplateLoc = DeclStartLoc;
2931
2932 if (!SuppressDiagnostic)
2933 Diag(DeclLoc, diag::err_template_spec_needs_header)
2934 << Range
2935 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2936 return false;
2937 };
2938
2939 unsigned ParamIdx = 0;
2940 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2941 ++TypeIdx) {
2942 T = NestedTypes[TypeIdx];
2943
2944 // Whether we expect a 'template<>' header.
2945 bool NeedEmptyTemplateHeader = false;
2946
2947 // Whether we expect a template header with parameters.
2948 bool NeedNonemptyTemplateHeader = false;
2949
2950 // For a dependent type, the set of template parameters that we
2951 // expect to see.
2952 TemplateParameterList *ExpectedTemplateParams = nullptr;
2953
2954 // C++0x [temp.expl.spec]p15:
2955 // A member or a member template may be nested within many enclosing
2956 // class templates. In an explicit specialization for such a member, the
2957 // member declaration shall be preceded by a template<> for each
2958 // enclosing class template that is explicitly specialized.
2959 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2961 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2962 ExpectedTemplateParams = Partial->getTemplateParameters();
2963 NeedNonemptyTemplateHeader = true;
2964 } else if (Record->isDependentType()) {
2965 if (Record->getDescribedClassTemplate()) {
2966 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2967 ->getTemplateParameters();
2968 NeedNonemptyTemplateHeader = true;
2969 }
2970 } else if (ClassTemplateSpecializationDecl *Spec
2971 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2972 // C++0x [temp.expl.spec]p4:
2973 // Members of an explicitly specialized class template are defined
2974 // in the same manner as members of normal classes, and not using
2975 // the template<> syntax.
2976 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2977 NeedEmptyTemplateHeader = true;
2978 else
2979 continue;
2980 } else if (Record->getTemplateSpecializationKind()) {
2981 if (Record->getTemplateSpecializationKind()
2983 TypeIdx == NumTypes - 1)
2984 IsMemberSpecialization = true;
2985
2986 continue;
2987 }
2988 } else if (const TemplateSpecializationType *TST
2989 = T->getAs<TemplateSpecializationType>()) {
2990 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2991 ExpectedTemplateParams = Template->getTemplateParameters();
2992 NeedNonemptyTemplateHeader = true;
2993 }
2994 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2995 // FIXME: We actually could/should check the template arguments here
2996 // against the corresponding template parameter list.
2997 NeedNonemptyTemplateHeader = false;
2998 }
2999
3000 // C++ [temp.expl.spec]p16:
3001 // In an explicit specialization declaration for a member of a class
3002 // template or a member template that appears in namespace scope, the
3003 // member template and some of its enclosing class templates may remain
3004 // unspecialized, except that the declaration shall not explicitly
3005 // specialize a class member template if its enclosing class templates
3006 // are not explicitly specialized as well.
3007 if (ParamIdx < ParamLists.size()) {
3008 if (ParamLists[ParamIdx]->size() == 0) {
3009 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3010 false))
3011 return nullptr;
3012 } else
3013 SawNonEmptyTemplateParameterList = true;
3014 }
3015
3016 if (NeedEmptyTemplateHeader) {
3017 // If we're on the last of the types, and we need a 'template<>' header
3018 // here, then it's a member specialization.
3019 if (TypeIdx == NumTypes - 1)
3020 IsMemberSpecialization = true;
3021
3022 if (ParamIdx < ParamLists.size()) {
3023 if (ParamLists[ParamIdx]->size() > 0) {
3024 // The header has template parameters when it shouldn't. Complain.
3025 if (!SuppressDiagnostic)
3026 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3027 diag::err_template_param_list_matches_nontemplate)
3028 << T
3029 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3030 ParamLists[ParamIdx]->getRAngleLoc())
3032 Invalid = true;
3033 return nullptr;
3034 }
3035
3036 // Consume this template header.
3037 ++ParamIdx;
3038 continue;
3039 }
3040
3041 if (!IsFriend)
3042 if (DiagnoseMissingExplicitSpecialization(
3044 return nullptr;
3045
3046 continue;
3047 }
3048
3049 if (NeedNonemptyTemplateHeader) {
3050 // In friend declarations we can have template-ids which don't
3051 // depend on the corresponding template parameter lists. But
3052 // assume that empty parameter lists are supposed to match this
3053 // template-id.
3054 if (IsFriend && T->isDependentType()) {
3055 if (ParamIdx < ParamLists.size() &&
3057 ExpectedTemplateParams = nullptr;
3058 else
3059 continue;
3060 }
3061
3062 if (ParamIdx < ParamLists.size()) {
3063 // Check the template parameter list, if we can.
3064 if (ExpectedTemplateParams &&
3066 ExpectedTemplateParams,
3067 !SuppressDiagnostic, TPL_TemplateMatch))
3068 Invalid = true;
3069
3070 if (!Invalid &&
3071 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3073 Invalid = true;
3074
3075 ++ParamIdx;
3076 continue;
3077 }
3078
3079 if (!SuppressDiagnostic)
3080 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3081 << T
3083 Invalid = true;
3084 continue;
3085 }
3086 }
3087
3088 // If there were at least as many template-ids as there were template
3089 // parameter lists, then there are no template parameter lists remaining for
3090 // the declaration itself.
3091 if (ParamIdx >= ParamLists.size()) {
3092 if (TemplateId && !IsFriend) {
3093 // We don't have a template header for the declaration itself, but we
3094 // should.
3095 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3096 TemplateId->RAngleLoc));
3097
3098 // Fabricate an empty template parameter list for the invented header.
3100 SourceLocation(), {},
3101 SourceLocation(), nullptr);
3102 }
3103
3104 return nullptr;
3105 }
3106
3107 // If there were too many template parameter lists, complain about that now.
3108 if (ParamIdx < ParamLists.size() - 1) {
3109 bool HasAnyExplicitSpecHeader = false;
3110 bool AllExplicitSpecHeaders = true;
3111 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3112 if (ParamLists[I]->size() == 0)
3113 HasAnyExplicitSpecHeader = true;
3114 else
3115 AllExplicitSpecHeaders = false;
3116 }
3117
3118 if (!SuppressDiagnostic)
3119 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3120 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3121 : diag::err_template_spec_extra_headers)
3122 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3123 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3124
3125 // If there was a specialization somewhere, such that 'template<>' is
3126 // not required, and there were any 'template<>' headers, note where the
3127 // specialization occurred.
3128 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3129 !SuppressDiagnostic)
3130 Diag(ExplicitSpecLoc,
3131 diag::note_explicit_template_spec_does_not_need_header)
3132 << NestedTypes.back();
3133
3134 // We have a template parameter list with no corresponding scope, which
3135 // means that the resulting template declaration can't be instantiated
3136 // properly (we'll end up with dependent nodes when we shouldn't).
3137 if (!AllExplicitSpecHeaders)
3138 Invalid = true;
3139 }
3140
3141 // C++ [temp.expl.spec]p16:
3142 // In an explicit specialization declaration for a member of a class
3143 // template or a member template that ap- pears in namespace scope, the
3144 // member template and some of its enclosing class templates may remain
3145 // unspecialized, except that the declaration shall not explicitly
3146 // specialize a class member template if its en- closing class templates
3147 // are not explicitly specialized as well.
3148 if (ParamLists.back()->size() == 0 &&
3149 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3150 false))
3151 return nullptr;
3152
3153 // Return the last template parameter list, which corresponds to the
3154 // entity being declared.
3155 return ParamLists.back();
3156}
3157
3159 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3160 Diag(Template->getLocation(), diag::note_template_declared_here)
3162 ? 0
3164 ? 1
3166 ? 2
3168 << Template->getDeclName();
3169 return;
3170 }
3171
3173 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3174 IEnd = OST->end();
3175 I != IEnd; ++I)
3176 Diag((*I)->getLocation(), diag::note_template_declared_here)
3177 << 0 << (*I)->getDeclName();
3178
3179 return;
3180 }
3181}
3182
3184 TemplateName BaseTemplate,
3185 SourceLocation TemplateLoc,
3187 auto lookUpCommonType = [&](TemplateArgument T1,
3188 TemplateArgument T2) -> QualType {
3189 // Don't bother looking for other specializations if both types are
3190 // builtins - users aren't allowed to specialize for them
3191 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3192 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3193 {T1, T2});
3194
3198 Args.addArgument(TemplateArgumentLoc(
3199 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3200
3201 EnterExpressionEvaluationContext UnevaluatedContext(
3203 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3205
3206 QualType BaseTemplateInst =
3207 S.CheckTemplateIdType(Keyword, BaseTemplate, TemplateLoc, Args);
3208
3209 if (SFINAE.hasErrorOccurred())
3210 return QualType();
3211
3212 return BaseTemplateInst;
3213 };
3214
3215 // Note A: For the common_type trait applied to a template parameter pack T of
3216 // types, the member type shall be either defined or not present as follows:
3217 switch (Ts.size()) {
3218
3219 // If sizeof...(T) is zero, there shall be no member type.
3220 case 0:
3221 return QualType();
3222
3223 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3224 // pack T. The member typedef-name type shall denote the same type, if any, as
3225 // common_type_t<T0, T0>; otherwise there shall be no member type.
3226 case 1:
3227 return lookUpCommonType(Ts[0], Ts[0]);
3228
3229 // If sizeof...(T) is two, let the first and second types constituting T be
3230 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3231 // as decay_t<T1> and decay_t<T2>, respectively.
3232 case 2: {
3233 QualType T1 = Ts[0].getAsType();
3234 QualType T2 = Ts[1].getAsType();
3235 QualType D1 = S.BuiltinDecay(T1, {});
3236 QualType D2 = S.BuiltinDecay(T2, {});
3237
3238 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3239 // the same type, if any, as common_type_t<D1, D2>.
3240 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3241 return lookUpCommonType(D1, D2);
3242
3243 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3244 // denotes a valid type, let C denote that type.
3245 {
3246 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3247 EnterExpressionEvaluationContext UnevaluatedContext(
3249 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3251
3252 // false
3254 VK_PRValue);
3255 ExprResult Cond = &CondExpr;
3256
3257 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3258 if (ConstRefQual) {
3259 D1.addConst();
3260 D2.addConst();
3261 }
3262
3263 // declval<D1>()
3264 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3265 ExprResult LHS = &LHSExpr;
3266
3267 // declval<D2>()
3268 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3269 ExprResult RHS = &RHSExpr;
3270
3273
3274 // decltype(false ? declval<D1>() : declval<D2>())
3275 QualType Result =
3276 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3277
3278 if (Result.isNull() || SFINAE.hasErrorOccurred())
3279 return QualType();
3280
3281 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3282 return S.BuiltinDecay(Result, TemplateLoc);
3283 };
3284
3285 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3286 return Res;
3287
3288 // Let:
3289 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3290 // COND-RES(X, Y) be
3291 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3292
3293 // C++20 only
3294 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3295 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3296 if (!S.Context.getLangOpts().CPlusPlus20)
3297 return QualType();
3298 return CheckConditionalOperands(true);
3299 }
3300 }
3301
3302 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3303 // denote the first, second, and (pack of) remaining types constituting T. Let
3304 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3305 // a type C, the member typedef-name type shall denote the same type, if any,
3306 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3307 default: {
3308 QualType Result = Ts.front().getAsType();
3309 for (auto T : llvm::drop_begin(Ts)) {
3310 Result = lookUpCommonType(Result, T.getAsType());
3311 if (Result.isNull())
3312 return QualType();
3313 }
3314 return Result;
3315 }
3316 }
3317}
3318
3319static bool isInVkNamespace(const RecordType *RT) {
3320 DeclContext *DC = RT->getOriginalDecl()->getDeclContext();
3321 if (!DC)
3322 return false;
3323
3324 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3325 if (!ND)
3326 return false;
3327
3328 return ND->getQualifiedNameAsString() == "hlsl::vk";
3329}
3330
3331static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3332 QualType OperandArg,
3333 SourceLocation Loc) {
3334 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3335 bool Literal = false;
3336 SourceLocation LiteralLoc;
3337 if (isInVkNamespace(RT) && RT->getOriginalDecl()->getName() == "Literal") {
3338 auto SpecDecl =
3339 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3340 assert(SpecDecl);
3341
3342 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3343 QualType ConstantType = LiteralArgs[0].getAsType();
3344 RT = ConstantType->getAsCanonical<RecordType>();
3345 Literal = true;
3346 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3347 }
3348
3349 if (RT && isInVkNamespace(RT) &&
3350 RT->getOriginalDecl()->getName() == "integral_constant") {
3351 auto SpecDecl =
3352 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3353 assert(SpecDecl);
3354
3355 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3356
3357 QualType ConstantType = ConstantArgs[0].getAsType();
3358 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3359
3360 if (Literal)
3361 return SpirvOperand::createLiteral(Value);
3362 return SpirvOperand::createConstant(ConstantType, Value);
3363 } else if (Literal) {
3364 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3365 return SpirvOperand();
3366 }
3367 }
3368 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3369 diag::err_call_incomplete_argument))
3370 return SpirvOperand();
3371 return SpirvOperand::createType(OperandArg);
3372}
3373
3376 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3377 TemplateArgumentListInfo &TemplateArgs) {
3378 ASTContext &Context = SemaRef.getASTContext();
3379
3380 switch (BTD->getBuiltinTemplateKind()) {
3381 case BTK__make_integer_seq: {
3382 // Specializations of __make_integer_seq<S, T, N> are treated like
3383 // S<T, 0, ..., N-1>.
3384
3385 QualType OrigType = Converted[1].getAsType();
3386 // C++14 [inteseq.intseq]p1:
3387 // T shall be an integer type.
3388 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3389 SemaRef.Diag(TemplateArgs[1].getLocation(),
3390 diag::err_integer_sequence_integral_element_type);
3391 return QualType();
3392 }
3393
3394 TemplateArgument NumArgsArg = Converted[2];
3395 if (NumArgsArg.isDependent())
3396 return QualType();
3397
3398 TemplateArgumentListInfo SyntheticTemplateArgs;
3399 // The type argument, wrapped in substitution sugar, gets reused as the
3400 // first template argument in the synthetic template argument list.
3401 SyntheticTemplateArgs.addArgument(
3404 OrigType, TemplateArgs[1].getLocation())));
3405
3406 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3407 // Expand N into 0 ... N-1.
3408 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3409 I < NumArgs; ++I) {
3410 TemplateArgument TA(Context, I, OrigType);
3411 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3412 TA, OrigType, TemplateArgs[2].getLocation()));
3413 }
3414 } else {
3415 // C++14 [inteseq.make]p1:
3416 // If N is negative the program is ill-formed.
3417 SemaRef.Diag(TemplateArgs[2].getLocation(),
3418 diag::err_integer_sequence_negative_length);
3419 return QualType();
3420 }
3421
3422 // The first template argument will be reused as the template decl that
3423 // our synthetic template arguments will be applied to.
3424 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3425 TemplateLoc, SyntheticTemplateArgs);
3426 }
3427
3428 case BTK__type_pack_element: {
3429 // Specializations of
3430 // __type_pack_element<Index, T_1, ..., T_N>
3431 // are treated like T_Index.
3432 assert(Converted.size() == 2 &&
3433 "__type_pack_element should be given an index and a parameter pack");
3434
3435 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3436 if (IndexArg.isDependent() || Ts.isDependent())
3437 return QualType();
3438
3439 llvm::APSInt Index = IndexArg.getAsIntegral();
3440 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3441 "type std::size_t, and hence be non-negative");
3442 // If the Index is out of bounds, the program is ill-formed.
3443 if (Index >= Ts.pack_size()) {
3444 SemaRef.Diag(TemplateArgs[0].getLocation(),
3445 diag::err_type_pack_element_out_of_bounds);
3446 return QualType();
3447 }
3448
3449 // We simply return the type at index `Index`.
3450 int64_t N = Index.getExtValue();
3451 return Ts.getPackAsArray()[N].getAsType();
3452 }
3453
3454 case BTK__builtin_common_type: {
3455 assert(Converted.size() == 4);
3456 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3457 return QualType();
3458
3459 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3460 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3461 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3462 TemplateLoc, Ts);
3463 !CT.isNull()) {
3467 CT, TemplateArgs[1].getLocation())));
3468 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3469 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3470 TAs);
3471 }
3472 QualType HasNoTypeMember = Converted[2].getAsType();
3473 return HasNoTypeMember;
3474 }
3475
3476 case BTK__hlsl_spirv_type: {
3477 assert(Converted.size() == 4);
3478
3479 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3480 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3481 }
3482
3483 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3484 return QualType();
3485
3486 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3487 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3488 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3489
3490 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3491
3493
3494 for (auto &OperandTA : OperandArgs) {
3495 QualType OperandArg = OperandTA.getAsType();
3496 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3497 TemplateArgs[3].getLocation());
3498 if (!Operand.isValid())
3499 return QualType();
3500 Operands.push_back(Operand);
3501 }
3502
3503 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3504 }
3505 case BTK__builtin_dedup_pack: {
3506 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3507 "a parameter pack");
3508 TemplateArgument Ts = Converted[0];
3509 // Delay the computation until we can compute the final result. We choose
3510 // not to remove the duplicates upfront before substitution to keep the code
3511 // simple.
3512 if (Ts.isDependent())
3513 return QualType();
3514 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3516 llvm::SmallDenseSet<QualType> Seen;
3517 // Synthesize a new template argument list, removing duplicates.
3518 for (auto T : Ts.getPackAsArray()) {
3519 assert(T.getKind() == clang::TemplateArgument::Type);
3520 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3521 continue;
3522 OutArgs.push_back(T);
3523 }
3524 return Context.getSubstBuiltinTemplatePack(
3525 TemplateArgument::CreatePackCopy(Context, OutArgs));
3526 }
3527 }
3528 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3529}
3530
3531/// Determine whether this alias template is "enable_if_t".
3532/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3534 return AliasTemplate->getName() == "enable_if_t" ||
3535 AliasTemplate->getName() == "__enable_if_t";
3536}
3537
3538/// Collect all of the separable terms in the given condition, which
3539/// might be a conjunction.
3540///
3541/// FIXME: The right answer is to convert the logical expression into
3542/// disjunctive normal form, so we can find the first failed term
3543/// within each possible clause.
3544static void collectConjunctionTerms(Expr *Clause,
3545 SmallVectorImpl<Expr *> &Terms) {
3546 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3547 if (BinOp->getOpcode() == BO_LAnd) {
3548 collectConjunctionTerms(BinOp->getLHS(), Terms);
3549 collectConjunctionTerms(BinOp->getRHS(), Terms);
3550 return;
3551 }
3552 }
3553
3554 Terms.push_back(Clause);
3555}
3556
3557// The ranges-v3 library uses an odd pattern of a top-level "||" with
3558// a left-hand side that is value-dependent but never true. Identify
3559// the idiom and ignore that term.
3561 // Top-level '||'.
3562 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3563 if (!BinOp) return Cond;
3564
3565 if (BinOp->getOpcode() != BO_LOr) return Cond;
3566
3567 // With an inner '==' that has a literal on the right-hand side.
3568 Expr *LHS = BinOp->getLHS();
3569 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3570 if (!InnerBinOp) return Cond;
3571
3572 if (InnerBinOp->getOpcode() != BO_EQ ||
3573 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3574 return Cond;
3575
3576 // If the inner binary operation came from a macro expansion named
3577 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3578 // of the '||', which is the real, user-provided condition.
3579 SourceLocation Loc = InnerBinOp->getExprLoc();
3580 if (!Loc.isMacroID()) return Cond;
3581
3582 StringRef MacroName = PP.getImmediateMacroName(Loc);
3583 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3584 return BinOp->getRHS();
3585
3586 return Cond;
3587}
3588
3589namespace {
3590
3591// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3592// within failing boolean expression, such as substituting template parameters
3593// for actual types.
3594class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3595public:
3596 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3597 : Policy(P) {}
3598
3599 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3600 const auto *DR = dyn_cast<DeclRefExpr>(E);
3601 if (DR && DR->getQualifier()) {
3602 // If this is a qualified name, expand the template arguments in nested
3603 // qualifiers.
3604 DR->getQualifier().print(OS, Policy, true);
3605 // Then print the decl itself.
3606 const ValueDecl *VD = DR->getDecl();
3607 OS << VD->getName();
3608 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3609 // This is a template variable, print the expanded template arguments.
3610 printTemplateArgumentList(
3611 OS, IV->getTemplateArgs().asArray(), Policy,
3612 IV->getSpecializedTemplate()->getTemplateParameters());
3613 }
3614 return true;
3615 }
3616 return false;
3617 }
3618
3619private:
3620 const PrintingPolicy Policy;
3621};
3622
3623} // end anonymous namespace
3624
3625std::pair<Expr *, std::string>
3628
3629 // Separate out all of the terms in a conjunction.
3632
3633 // Determine which term failed.
3634 Expr *FailedCond = nullptr;
3635 for (Expr *Term : Terms) {
3636 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3637
3638 // Literals are uninteresting.
3639 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3640 isa<IntegerLiteral>(TermAsWritten))
3641 continue;
3642
3643 // The initialization of the parameter from the argument is
3644 // a constant-evaluated context.
3647
3648 bool Succeeded;
3649 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3650 !Succeeded) {
3651 FailedCond = TermAsWritten;
3652 break;
3653 }
3654 }
3655 if (!FailedCond)
3656 FailedCond = Cond->IgnoreParenImpCasts();
3657
3658 std::string Description;
3659 {
3660 llvm::raw_string_ostream Out(Description);
3662 Policy.PrintAsCanonical = true;
3663 FailedBooleanConditionPrinterHelper Helper(Policy);
3664 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3665 }
3666 return { FailedCond, Description };
3667}
3668
3670 TemplateName Name,
3671 SourceLocation TemplateLoc,
3672 TemplateArgumentListInfo &TemplateArgs) {
3673 // FIXME: 'getUnderlying' loses SubstTemplateTemplateParm nodes from alias
3674 // template substitutions.
3675 if (DependentTemplateName *DTN =
3677 DTN && DTN->getName().getIdentifier())
3678 // When building a template-id where the template-name is dependent,
3679 // assume the template is a type template. Either our assumption is
3680 // correct, or the code is ill-formed and will be diagnosed when the
3681 // dependent name is substituted.
3682 return Context.getDependentTemplateSpecializationType(
3683 ElaboratedTypeKeyword::None, *DTN, TemplateArgs.arguments());
3684
3685 if (Name.getAsAssumedTemplateName() &&
3686 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3687 return QualType();
3688
3690 DefaultArguments DefaultArgs;
3693 Template = S->getParameterPack();
3694 } else {
3695 std::tie(Template, DefaultArgs) = Name.getTemplateDeclAndDefaultArgs();
3698 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name;
3700 return QualType();
3701 }
3702 }
3703
3704 // Check that the template argument list is well-formed for this
3705 // template.
3707 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3708 DefaultArgs, /*PartialTemplateArgs=*/false,
3709 CTAI,
3710 /*UpdateArgsWithConversions=*/true))
3711 return QualType();
3712
3713 QualType CanonType;
3714
3716 // We might have a substituted template template parameter pack. If so,
3717 // build a template specialization type for it.
3719 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3720
3721 // C++0x [dcl.type.elab]p2:
3722 // If the identifier resolves to a typedef-name or the simple-template-id
3723 // resolves to an alias template specialization, the
3724 // elaborated-type-specifier is ill-formed.
3727 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3730 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3731 }
3732
3733 // Find the canonical type for this type alias template specialization.
3734 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3735 if (Pattern->isInvalidDecl())
3736 return QualType();
3737
3738 // Only substitute for the innermost template argument list.
3739 MultiLevelTemplateArgumentList TemplateArgLists;
3741 /*Final=*/true);
3742 TemplateArgLists.addOuterRetainedLevels(
3743 AliasTemplate->getTemplateParameters()->getDepth());
3744
3747 *this, /*PointOfInstantiation=*/TemplateLoc,
3748 /*Entity=*/AliasTemplate,
3749 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3750
3751 // Diagnose uses of this alias.
3752 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3753
3754 if (Inst.isInvalid())
3755 return QualType();
3756
3757 std::optional<ContextRAII> SavedContext;
3758 if (!AliasTemplate->getDeclContext()->isFileContext())
3759 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3760
3761 CanonType =
3762 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3763 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3764 if (CanonType.isNull()) {
3765 // If this was enable_if and we failed to find the nested type
3766 // within enable_if in a SFINAE context, dig out the specific
3767 // enable_if condition that failed and present that instead.
3769 if (auto DeductionInfo = isSFINAEContext()) {
3770 if (*DeductionInfo &&
3771 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3772 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3773 diag::err_typename_nested_not_found_enable_if &&
3774 TemplateArgs[0].getArgument().getKind()
3776 Expr *FailedCond;
3777 std::string FailedDescription;
3778 std::tie(FailedCond, FailedDescription) =
3779 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3780
3781 // Remove the old SFINAE diagnostic.
3782 PartialDiagnosticAt OldDiag =
3784 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3785
3786 // Add a new SFINAE diagnostic specifying which condition
3787 // failed.
3788 (*DeductionInfo)->addSFINAEDiagnostic(
3789 OldDiag.first,
3790 PDiag(diag::err_typename_nested_not_found_requirement)
3791 << FailedDescription
3792 << FailedCond->getSourceRange());
3793 }
3794 }
3795 }
3796
3797 return QualType();
3798 }
3799 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3800 CanonType = checkBuiltinTemplateIdType(
3801 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3802 } else if (Name.isDependent() ||
3803 TemplateSpecializationType::anyDependentTemplateArguments(
3804 TemplateArgs, CTAI.CanonicalConverted)) {
3805 // This class template specialization is a dependent
3806 // type. Therefore, its canonical type is another class template
3807 // specialization type that contains all of the converted
3808 // arguments in canonical form. This ensures that, e.g., A<T> and
3809 // A<T, T> have identical types when A is declared as:
3810 //
3811 // template<typename T, typename U = T> struct A;
3812 CanonType = Context.getCanonicalTemplateSpecializationType(
3813 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3814 CTAI.CanonicalConverted);
3815 assert(CanonType->isCanonicalUnqualified());
3816
3817 // This might work out to be a current instantiation, in which
3818 // case the canonical type needs to be the InjectedClassNameType.
3819 //
3820 // TODO: in theory this could be a simple hashtable lookup; most
3821 // changes to CurContext don't change the set of current
3822 // instantiations.
3824 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3825 // If we get out to a namespace, we're done.
3826 if (Ctx->isFileContext()) break;
3827
3828 // If this isn't a record, keep looking.
3829 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3830 if (!Record) continue;
3831
3832 // Look for one of the two cases with InjectedClassNameTypes
3833 // and check whether it's the same template.
3835 !Record->getDescribedClassTemplate())
3836 continue;
3837
3838 // Fetch the injected class name type and check whether its
3839 // injected type is equal to the type we just built.
3840 CanQualType ICNT = Context.getCanonicalTagType(Record);
3841 CanQualType Injected =
3842 Record->getCanonicalTemplateSpecializationType(Context);
3843
3844 if (CanonType != Injected)
3845 continue;
3846
3847 // If so, the canonical type of this TST is the injected
3848 // class name type of the record we just found.
3849 CanonType = ICNT;
3850 break;
3851 }
3852 }
3853 } else if (ClassTemplateDecl *ClassTemplate =
3854 dyn_cast<ClassTemplateDecl>(Template)) {
3855 // Find the class template specialization declaration that
3856 // corresponds to these arguments.
3857 void *InsertPos = nullptr;
3859 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3860 if (!Decl) {
3861 // This is the first time we have referenced this class template
3862 // specialization. Create the canonical declaration and add it to
3863 // the set of specializations.
3865 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3866 ClassTemplate->getDeclContext(),
3867 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3868 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3869 CTAI.StrictPackMatch, nullptr);
3870 ClassTemplate->AddSpecialization(Decl, InsertPos);
3871 if (ClassTemplate->isOutOfLine())
3872 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3873 }
3874
3875 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3876 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3877 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3878 if (!Inst.isInvalid()) {
3880 CTAI.CanonicalConverted,
3881 /*Final=*/false);
3882 InstantiateAttrsForDecl(TemplateArgLists,
3883 ClassTemplate->getTemplatedDecl(), Decl);
3884 }
3885 }
3886
3887 // Diagnose uses of this specialization.
3888 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3889
3890 CanonType = Context.getCanonicalTagType(Decl);
3891 assert(isa<RecordType>(CanonType) &&
3892 "type of non-dependent specialization is not a RecordType");
3893 } else {
3894 llvm_unreachable("Unhandled template kind");
3895 }
3896
3897 // Build the fully-sugared type for this class template
3898 // specialization, which refers back to the class template
3899 // specialization we created or found.
3900 return Context.getTemplateSpecializationType(
3901 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3902 CanonType);
3903}
3904
3906 TemplateNameKind &TNK,
3907 SourceLocation NameLoc,
3908 IdentifierInfo *&II) {
3909 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3910
3911 TemplateName Name = ParsedName.get();
3912 auto *ATN = Name.getAsAssumedTemplateName();
3913 assert(ATN && "not an assumed template name");
3914 II = ATN->getDeclName().getAsIdentifierInfo();
3915
3916 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3917 // Resolved to a type template name.
3918 ParsedName = TemplateTy::make(Name);
3919 TNK = TNK_Type_template;
3920 }
3921}
3922
3924 SourceLocation NameLoc,
3925 bool Diagnose) {
3926 // We assumed this undeclared identifier to be an (ADL-only) function
3927 // template name, but it was used in a context where a type was required.
3928 // Try to typo-correct it now.
3930 assert(ATN && "not an assumed template name");
3931
3932 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3933 struct CandidateCallback : CorrectionCandidateCallback {
3934 bool ValidateCandidate(const TypoCorrection &TC) override {
3935 return TC.getCorrectionDecl() &&
3937 }
3938 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3939 return std::make_unique<CandidateCallback>(*this);
3940 }
3941 } FilterCCC;
3942
3943 TypoCorrection Corrected =
3944 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3946 if (Corrected && Corrected.getFoundDecl()) {
3947 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3948 << ATN->getDeclName());
3949 Name = Context.getQualifiedTemplateName(
3950 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3952 return false;
3953 }
3954
3955 if (Diagnose)
3956 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3957 return true;
3958}
3959
3961 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
3962 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
3963 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
3964 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
3965 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
3966 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
3967 ImplicitTypenameContext AllowImplicitTypename) {
3968 if (SS.isInvalid())
3969 return true;
3970
3971 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3972 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3973
3974 // C++ [temp.res]p3:
3975 // A qualified-id that refers to a type and in which the
3976 // nested-name-specifier depends on a template-parameter (14.6.2)
3977 // shall be prefixed by the keyword typename to indicate that the
3978 // qualified-id denotes a type, forming an
3979 // elaborated-type-specifier (7.1.5.3).
3980 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3981 // C++2a relaxes some of those restrictions in [temp.res]p5.
3982 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
3983 SS.getScopeRep(), TemplateII);
3985 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3986 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
3987 << NNS;
3988 if (!getLangOpts().CPlusPlus20)
3989 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3990 } else
3991 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
3992
3993 // FIXME: This is not quite correct recovery as we don't transform SS
3994 // into the corresponding dependent form (and we don't diagnose missing
3995 // 'template' keywords within SS as a result).
3996 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3997 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3998 TemplateArgsIn, RAngleLoc);
3999 }
4000
4001 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4002 // it's not actually allowed to be used as a type in most cases. Because
4003 // we annotate it before we know whether it's valid, we have to check for
4004 // this case here.
4005 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4006 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4007 Diag(TemplateIILoc,
4008 TemplateKWLoc.isInvalid()
4009 ? diag::err_out_of_line_qualified_id_type_names_constructor
4010 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4011 << TemplateII << 0 /*injected-class-name used as template name*/
4012 << 1 /*if any keyword was present, it was 'template'*/;
4013 }
4014 }
4015
4016 TemplateName Template = TemplateD.get();
4017 if (Template.getAsAssumedTemplateName() &&
4018 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4019 return true;
4020
4021 // Translate the parser's template argument list in our AST format.
4022 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4023 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4024
4025 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4026 assert(SS.getScopeRep() == DTN->getQualifier());
4027 QualType T = Context.getDependentTemplateSpecializationType(
4028 ElaboratedKeyword, *DTN, TemplateArgs.arguments());
4029 // Build type-source information.
4030 TypeLocBuilder TLB;
4033 SpecTL.setElaboratedKeywordLoc(ElaboratedKeywordLoc);
4035 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4036 SpecTL.setTemplateNameLoc(TemplateIILoc);
4037 SpecTL.setLAngleLoc(LAngleLoc);
4038 SpecTL.setRAngleLoc(RAngleLoc);
4039 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4040 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4042 }
4043
4044 QualType SpecTy = CheckTemplateIdType(ElaboratedKeyword, Template,
4045 TemplateIILoc, TemplateArgs);
4046 if (SpecTy.isNull())
4047 return true;
4048
4049 // Build type-source information.
4050 TypeLocBuilder TLB;
4051 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4052 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4053 TemplateIILoc, TemplateArgs);
4054 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4055}
4056
4058 TypeSpecifierType TagSpec,
4059 SourceLocation TagLoc,
4060 CXXScopeSpec &SS,
4061 SourceLocation TemplateKWLoc,
4062 TemplateTy TemplateD,
4063 SourceLocation TemplateLoc,
4064 SourceLocation LAngleLoc,
4065 ASTTemplateArgsPtr TemplateArgsIn,
4066 SourceLocation RAngleLoc) {
4067 if (SS.isInvalid())
4068 return TypeResult(true);
4069
4070 TemplateName Template = TemplateD.get();
4071
4072 // Translate the parser's template argument list in our AST format.
4073 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4074 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4075
4076 // Determine the tag kind
4080
4081 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4082 assert(SS.getScopeRep() == DTN->getQualifier());
4083 QualType T = Context.getDependentTemplateSpecializationType(
4084 Keyword, *DTN, TemplateArgs.arguments());
4085
4086 // Build type-source information.
4087 TypeLocBuilder TLB;
4090 SpecTL.setElaboratedKeywordLoc(TagLoc);
4092 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4093 SpecTL.setTemplateNameLoc(TemplateLoc);
4094 SpecTL.setLAngleLoc(LAngleLoc);
4095 SpecTL.setRAngleLoc(RAngleLoc);
4096 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4097 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4099 }
4100
4102 CheckTemplateIdType(Keyword, Template, TemplateLoc, TemplateArgs);
4103 if (Result.isNull())
4104 return TypeResult(true);
4105
4106 // Check the tag kind
4107 if (const RecordType *RT = Result->getAs<RecordType>()) {
4108 RecordDecl *D = RT->getOriginalDecl();
4109
4110 IdentifierInfo *Id = D->getIdentifier();
4111 assert(Id && "templated class must have an identifier");
4112
4114 TagLoc, Id)) {
4115 Diag(TagLoc, diag::err_use_with_wrong_tag)
4116 << Result
4118 Diag(D->getLocation(), diag::note_previous_use);
4119 }
4120 }
4121
4122 // Provide source-location information for the template specialization.
4123 TypeLocBuilder TLB;
4125 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4126 TemplateArgs);
4128}
4129
4130static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4131 NamedDecl *PrevDecl,
4132 SourceLocation Loc,
4134
4136
4138 unsigned Depth,
4139 unsigned Index) {
4140 switch (Arg.getKind()) {
4148 return false;
4149
4151 QualType Type = Arg.getAsType();
4152 const TemplateTypeParmType *TPT =
4153 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4154 return TPT && !Type.hasQualifiers() &&
4155 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4156 }
4157
4159 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4160 if (!DRE || !DRE->getDecl())
4161 return false;
4162 const NonTypeTemplateParmDecl *NTTP =
4163 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4164 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4165 }
4166
4168 const TemplateTemplateParmDecl *TTP =
4169 dyn_cast_or_null<TemplateTemplateParmDecl>(
4171 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4172 }
4173 llvm_unreachable("unexpected kind of template argument");
4174}
4175
4177 TemplateParameterList *SpecParams,
4179 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4180 return false;
4181
4182 unsigned Depth = Params->getDepth();
4183
4184 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4185 TemplateArgument Arg = Args[I];
4186
4187 // If the parameter is a pack expansion, the argument must be a pack
4188 // whose only element is a pack expansion.
4189 if (Params->getParam(I)->isParameterPack()) {
4190 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4191 !Arg.pack_begin()->isPackExpansion())
4192 return false;
4193 Arg = Arg.pack_begin()->getPackExpansionPattern();
4194 }
4195
4196 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4197 return false;
4198
4199 // For NTTPs further specialization is allowed via deduced types, so
4200 // we need to make sure to only reject here if primary template and
4201 // specialization use the same type for the NTTP.
4202 if (auto *SpecNTTP =
4203 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4204 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4205 if (!NTTP || NTTP->getType().getCanonicalType() !=
4206 SpecNTTP->getType().getCanonicalType())
4207 return false;
4208 }
4209 }
4210
4211 return true;
4212}
4213
4214template<typename PartialSpecDecl>
4215static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4216 if (Partial->getDeclContext()->isDependentContext())
4217 return;
4218
4219 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4220 // for non-substitution-failure issues?
4221 TemplateDeductionInfo Info(Partial->getLocation());
4222 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4223 return;
4224
4225 auto *Template = Partial->getSpecializedTemplate();
4226 S.Diag(Partial->getLocation(),
4227 diag::ext_partial_spec_not_more_specialized_than_primary)
4229
4230 if (Info.hasSFINAEDiagnostic()) {
4234 SmallString<128> SFINAEArgString;
4235 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4236 S.Diag(Diag.first,
4237 diag::note_partial_spec_not_more_specialized_than_primary)
4238 << SFINAEArgString;
4239 }
4240
4242 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4243 Template->getAssociatedConstraints(TemplateAC);
4244 Partial->getAssociatedConstraints(PartialAC);
4246 TemplateAC);
4247}
4248
4249static void
4251 const llvm::SmallBitVector &DeducibleParams) {
4252 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4253 if (!DeducibleParams[I]) {
4254 NamedDecl *Param = TemplateParams->getParam(I);
4255 if (Param->getDeclName())
4256 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4257 << Param->getDeclName();
4258 else
4259 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4260 << "(anonymous)";
4261 }
4262 }
4263}
4264
4265
4266template<typename PartialSpecDecl>
4268 PartialSpecDecl *Partial) {
4269 // C++1z [temp.class.spec]p8: (DR1495)
4270 // - The specialization shall be more specialized than the primary
4271 // template (14.5.5.2).
4273
4274 // C++ [temp.class.spec]p8: (DR1315)
4275 // - Each template-parameter shall appear at least once in the
4276 // template-id outside a non-deduced context.
4277 // C++1z [temp.class.spec.match]p3 (P0127R2)
4278 // If the template arguments of a partial specialization cannot be
4279 // deduced because of the structure of its template-parameter-list
4280 // and the template-id, the program is ill-formed.
4281 auto *TemplateParams = Partial->getTemplateParameters();
4282 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4283 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4284 TemplateParams->getDepth(), DeducibleParams);
4285
4286 if (!DeducibleParams.all()) {
4287 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4288 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4290 << (NumNonDeducible > 1)
4291 << SourceRange(Partial->getLocation(),
4292 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4293 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4294 }
4295}
4296
4301
4306
4308 // C++1z [temp.param]p11:
4309 // A template parameter of a deduction guide template that does not have a
4310 // default-argument shall be deducible from the parameter-type-list of the
4311 // deduction guide template.
4312 auto *TemplateParams = TD->getTemplateParameters();
4313 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4314 MarkDeducedTemplateParameters(TD, DeducibleParams);
4315 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4316 // A parameter pack is deducible (to an empty pack).
4317 auto *Param = TemplateParams->getParam(I);
4318 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4319 DeducibleParams[I] = true;
4320 }
4321
4322 if (!DeducibleParams.all()) {
4323 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4324 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4325 << (NumNonDeducible > 1);
4326 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4327 }
4328}
4329
4332 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4334 // D must be variable template id.
4336 "Variable template specialization is declared with a template id.");
4337
4338 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4339 TemplateArgumentListInfo TemplateArgs =
4340 makeTemplateArgumentListInfo(*this, *TemplateId);
4341 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4342 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4343 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4344
4345 TemplateName Name = TemplateId->Template.get();
4346
4347 // The template-id must name a variable template.
4349 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4350 if (!VarTemplate) {
4351 NamedDecl *FnTemplate;
4352 if (auto *OTS = Name.getAsOverloadedTemplate())
4353 FnTemplate = *OTS->begin();
4354 else
4355 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4356 if (FnTemplate)
4357 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4358 << FnTemplate->getDeclName();
4359 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4361 }
4362
4363 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4364 auto Message = DSA->getMessage();
4365 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4366 << VarTemplate << !Message.empty() << Message;
4367 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4368 }
4369
4370 // Check for unexpanded parameter packs in any of the template arguments.
4371 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4372 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4376 return true;
4377
4378 // Check that the template argument list is well-formed for this
4379 // template.
4381 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4382 /*DefaultArgs=*/{},
4383 /*PartialTemplateArgs=*/false, CTAI,
4384 /*UpdateArgsWithConversions=*/true))
4385 return true;
4386
4387 // Find the variable template (partial) specialization declaration that
4388 // corresponds to these arguments.
4391 TemplateArgs.size(),
4392 CTAI.CanonicalConverted))
4393 return true;
4394
4395 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4396 // we also do them during instantiation.
4397 if (!Name.isDependent() &&
4398 !TemplateSpecializationType::anyDependentTemplateArguments(
4399 TemplateArgs, CTAI.CanonicalConverted)) {
4400 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4401 << VarTemplate->getDeclName();
4403 }
4404
4405 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4406 TemplateParams, CTAI.CanonicalConverted) &&
4407 (!Context.getLangOpts().CPlusPlus20 ||
4408 !TemplateParams->hasAssociatedConstraints())) {
4409 // C++ [temp.class.spec]p9b3:
4410 //
4411 // -- The argument list of the specialization shall not be identical
4412 // to the implicit argument list of the primary template.
4413 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4414 << /*variable template*/ 1
4415 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4416 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4417 // FIXME: Recover from this by treating the declaration as a
4418 // redeclaration of the primary template.
4419 return true;
4420 }
4421 }
4422
4423 void *InsertPos = nullptr;
4424 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4425
4427 PrevDecl = VarTemplate->findPartialSpecialization(
4428 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4429 else
4430 PrevDecl =
4431 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4432
4434
4435 // Check whether we can declare a variable template specialization in
4436 // the current scope.
4437 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4438 TemplateNameLoc,
4440 return true;
4441
4442 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4443 // Since the only prior variable template specialization with these
4444 // arguments was referenced but not declared, reuse that
4445 // declaration node as our own, updating its source location and
4446 // the list of outer template parameters to reflect our new declaration.
4447 Specialization = PrevDecl;
4448 Specialization->setLocation(TemplateNameLoc);
4449 PrevDecl = nullptr;
4450 } else if (IsPartialSpecialization) {
4451 // Create a new class template partial specialization declaration node.
4453 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4456 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4457 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4458 CTAI.CanonicalConverted);
4459 Partial->setTemplateArgsAsWritten(TemplateArgs);
4460
4461 if (!PrevPartial)
4462 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4463 Specialization = Partial;
4464
4465 // If we are providing an explicit specialization of a member variable
4466 // template specialization, make a note of that.
4467 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4468 PrevPartial->setMemberSpecialization();
4469
4471 } else {
4472 // Create a new class template specialization declaration node for
4473 // this explicit specialization or friend declaration.
4475 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4476 VarTemplate, DI->getType(), DI, SC, CTAI.CanonicalConverted);
4477 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4478
4479 if (!PrevDecl)
4480 VarTemplate->AddSpecialization(Specialization, InsertPos);
4481 }
4482
4483 // C++ [temp.expl.spec]p6:
4484 // If a template, a member template or the member of a class template is
4485 // explicitly specialized then that specialization shall be declared
4486 // before the first use of that specialization that would cause an implicit
4487 // instantiation to take place, in every translation unit in which such a
4488 // use occurs; no diagnostic is required.
4489 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4490 bool Okay = false;
4491 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4492 // Is there any previous explicit specialization declaration?
4494 Okay = true;
4495 break;
4496 }
4497 }
4498
4499 if (!Okay) {
4500 SourceRange Range(TemplateNameLoc, RAngleLoc);
4501 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4502 << Name << Range;
4503
4504 Diag(PrevDecl->getPointOfInstantiation(),
4505 diag::note_instantiation_required_here)
4506 << (PrevDecl->getTemplateSpecializationKind() !=
4508 return true;
4509 }
4510 }
4511
4512 Specialization->setLexicalDeclContext(CurContext);
4513
4514 // Add the specialization into its lexical context, so that it can
4515 // be seen when iterating through the list of declarations in that
4516 // context. However, specializations are not found by name lookup.
4517 CurContext->addDecl(Specialization);
4518
4519 // Note that this is an explicit specialization.
4520 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4521
4522 Previous.clear();
4523 if (PrevDecl)
4524 Previous.addDecl(PrevDecl);
4525 else if (Specialization->isStaticDataMember() &&
4526 Specialization->isOutOfLine())
4527 Specialization->setAccess(VarTemplate->getAccess());
4528
4529 return Specialization;
4530}
4531
4532namespace {
4533/// A partial specialization whose template arguments have matched
4534/// a given template-id.
4535struct PartialSpecMatchResult {
4538};
4539
4540// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4541// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4542static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4543 if (Var->getName() != "format_kind" ||
4544 !Var->getDeclContext()->isStdNamespace())
4545 return false;
4546
4547 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4548 // release in which users can access std::format_kind.
4549 // We can use 20250520 as the final date, see the following commits.
4550 // GCC releases/gcc-15 branch:
4551 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4552 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4553 // GCC master branch:
4554 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4555 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4556 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4557}
4558} // end anonymous namespace
4559
4562 SourceLocation TemplateNameLoc,
4563 const TemplateArgumentListInfo &TemplateArgs,
4564 bool SetWrittenArgs) {
4565 assert(Template && "A variable template id without template?");
4566
4567 // Check that the template argument list is well-formed for this template.
4570 Template, TemplateNameLoc,
4571 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4572 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4573 /*UpdateArgsWithConversions=*/true))
4574 return true;
4575
4576 // Produce a placeholder value if the specialization is dependent.
4577 if (Template->getDeclContext()->isDependentContext() ||
4578 TemplateSpecializationType::anyDependentTemplateArguments(
4579 TemplateArgs, CTAI.CanonicalConverted)) {
4580 if (ParsingInitForAutoVars.empty())
4581 return DeclResult();
4582
4583 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4584 const TemplateArgument &Arg2) {
4585 return Context.isSameTemplateArgument(Arg1, Arg2);
4586 };
4587
4588 if (VarDecl *Var = Template->getTemplatedDecl();
4589 ParsingInitForAutoVars.count(Var) &&
4590 // See comments on this function definition
4591 !IsLibstdcxxStdFormatKind(PP, Var) &&
4592 llvm::equal(
4593 CTAI.CanonicalConverted,
4594 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4595 IsSameTemplateArg)) {
4596 Diag(TemplateNameLoc,
4597 diag::err_auto_variable_cannot_appear_in_own_initializer)
4598 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4599 return true;
4600 }
4601
4603 Template->getPartialSpecializations(PartialSpecs);
4604 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4605 if (ParsingInitForAutoVars.count(Partial) &&
4606 llvm::equal(CTAI.CanonicalConverted,
4607 Partial->getTemplateArgs().asArray(),
4608 IsSameTemplateArg)) {
4609 Diag(TemplateNameLoc,
4610 diag::err_auto_variable_cannot_appear_in_own_initializer)
4611 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4612 << Partial->getType();
4613 return true;
4614 }
4615
4616 return DeclResult();
4617 }
4618
4619 // Find the variable template specialization declaration that
4620 // corresponds to these arguments.
4621 void *InsertPos = nullptr;
4623 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4624 checkSpecializationReachability(TemplateNameLoc, Spec);
4625 if (Spec->getType()->isUndeducedType()) {
4626 if (ParsingInitForAutoVars.count(Spec))
4627 Diag(TemplateNameLoc,
4628 diag::err_auto_variable_cannot_appear_in_own_initializer)
4629 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4630 << Spec->getType();
4631 else
4632 // We are substituting the initializer of this variable template
4633 // specialization.
4634 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4635 << Spec << Spec->getType();
4636
4637 return true;
4638 }
4639 // If we already have a variable template specialization, return it.
4640 return Spec;
4641 }
4642
4643 // This is the first time we have referenced this variable template
4644 // specialization. Create the canonical declaration and add it to
4645 // the set of specializations, based on the closest partial specialization
4646 // that it represents. That is,
4647 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4648 const TemplateArgumentList *PartialSpecArgs = nullptr;
4649 bool AmbiguousPartialSpec = false;
4650 typedef PartialSpecMatchResult MatchResult;
4652 SourceLocation PointOfInstantiation = TemplateNameLoc;
4653 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4654 /*ForTakingAddress=*/false);
4655
4656 // 1. Attempt to find the closest partial specialization that this
4657 // specializes, if any.
4658 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4659 // Perhaps better after unification of DeduceTemplateArguments() and
4660 // getMoreSpecializedPartialSpecialization().
4662 Template->getPartialSpecializations(PartialSpecs);
4663
4664 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4665 // C++ [temp.spec.partial.member]p2:
4666 // If the primary member template is explicitly specialized for a given
4667 // (implicit) specialization of the enclosing class template, the partial
4668 // specializations of the member template are ignored for this
4669 // specialization of the enclosing class template. If a partial
4670 // specialization of the member template is explicitly specialized for a
4671 // given (implicit) specialization of the enclosing class template, the
4672 // primary member template and its other partial specializations are still
4673 // considered for this specialization of the enclosing class template.
4674 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4675 !Partial->getMostRecentDecl()->isMemberSpecialization())
4676 continue;
4677
4678 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4679
4681 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4683 // Store the failed-deduction information for use in diagnostics, later.
4684 // TODO: Actually use the failed-deduction info?
4685 FailedCandidates.addCandidate().set(
4688 (void)Result;
4689 } else {
4690 Matched.push_back(PartialSpecMatchResult());
4691 Matched.back().Partial = Partial;
4692 Matched.back().Args = Info.takeSugared();
4693 }
4694 }
4695
4696 if (Matched.size() >= 1) {
4697 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4698 if (Matched.size() == 1) {
4699 // -- If exactly one matching specialization is found, the
4700 // instantiation is generated from that specialization.
4701 // We don't need to do anything for this.
4702 } else {
4703 // -- If more than one matching specialization is found, the
4704 // partial order rules (14.5.4.2) are used to determine
4705 // whether one of the specializations is more specialized
4706 // than the others. If none of the specializations is more
4707 // specialized than all of the other matching
4708 // specializations, then the use of the variable template is
4709 // ambiguous and the program is ill-formed.
4710 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4711 PEnd = Matched.end();
4712 P != PEnd; ++P) {
4713 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4714 PointOfInstantiation) ==
4715 P->Partial)
4716 Best = P;
4717 }
4718
4719 // Determine if the best partial specialization is more specialized than
4720 // the others.
4721 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4722 PEnd = Matched.end();
4723 P != PEnd; ++P) {
4725 P->Partial, Best->Partial,
4726 PointOfInstantiation) != Best->Partial) {
4727 AmbiguousPartialSpec = true;
4728 break;
4729 }
4730 }
4731 }
4732
4733 // Instantiate using the best variable template partial specialization.
4734 InstantiationPattern = Best->Partial;
4735 PartialSpecArgs = Best->Args;
4736 } else {
4737 // -- If no match is found, the instantiation is generated
4738 // from the primary template.
4739 // InstantiationPattern = Template->getTemplatedDecl();
4740 }
4741
4742 // 2. Create the canonical declaration.
4743 // Note that we do not instantiate a definition until we see an odr-use
4744 // in DoMarkVarDeclReferenced().
4745 // FIXME: LateAttrs et al.?
4747 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4748 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4749 if (!Decl)
4750 return true;
4751 if (SetWrittenArgs)
4752 Decl->setTemplateArgsAsWritten(TemplateArgs);
4753
4754 if (AmbiguousPartialSpec) {
4755 // Partial ordering did not produce a clear winner. Complain.
4757 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4758 << Decl;
4759
4760 // Print the matching partial specializations.
4761 for (MatchResult P : Matched)
4762 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4763 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4764 *P.Args);
4765 return true;
4766 }
4767
4769 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4770 Decl->setInstantiationOf(D, PartialSpecArgs);
4771
4772 checkSpecializationReachability(TemplateNameLoc, Decl);
4773
4774 assert(Decl && "No variable template specialization?");
4775 return Decl;
4776}
4777
4779 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4780 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4781 const TemplateArgumentListInfo *TemplateArgs) {
4782
4783 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4784 *TemplateArgs, /*SetWrittenArgs=*/false);
4785 if (Decl.isInvalid())
4786 return ExprError();
4787
4788 if (!Decl.get())
4789 return ExprResult();
4790
4791 VarDecl *Var = cast<VarDecl>(Decl.get());
4794 NameInfo.getLoc());
4795
4796 // Build an ordinary singleton decl ref.
4797 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4798}
4799
4801 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4803 const TemplateArgumentListInfo *TemplateArgs) {
4804 assert(Template && "A variable template id without template?");
4805
4806 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4807 Template->templateParameterKind() !=
4809 return ExprResult();
4810
4811 // Check that the template argument list is well-formed for this template.
4814 Template, TemplateLoc,
4815 // FIXME: TemplateArgs will not be modified because
4816 // UpdateArgsWithConversions is false, however, we should
4817 // CheckTemplateArgumentList to be const-correct.
4818 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4819 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4820 /*UpdateArgsWithConversions=*/false))
4821 return true;
4822
4824 R.addDecl(Template);
4825
4826 // FIXME: We model references to variable template and concept parameters
4827 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4828 // data, can generally be used in the same places and work the same way.
4829 // However, it might be cleaner to use a dedicated AST node in the long run.
4832 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4833 /*KnownDependent=*/false,
4834 /*KnownInstantiationDependent=*/false);
4835}
4836
4838 SourceLocation Loc) {
4839 Diag(Loc, diag::err_template_missing_args)
4840 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4841 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4842 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4843 }
4844}
4845
4847 bool TemplateKeyword,
4848 TemplateDecl *TD,
4849 SourceLocation Loc) {
4850 TemplateName Name = Context.getQualifiedTemplateName(
4851 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4853}
4854
4857 SourceLocation TemplateKWLoc,
4858 const DeclarationNameInfo &ConceptNameInfo,
4859 NamedDecl *FoundDecl,
4860 ConceptDecl *NamedConcept,
4861 const TemplateArgumentListInfo *TemplateArgs) {
4862 assert(NamedConcept && "A concept template id without a template?");
4863
4864 if (NamedConcept->isInvalidDecl())
4865 return ExprError();
4866
4869 NamedConcept, ConceptNameInfo.getLoc(),
4870 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4871 /*DefaultArgs=*/{},
4872 /*PartialTemplateArgs=*/false, CTAI,
4873 /*UpdateArgsWithConversions=*/false))
4874 return ExprError();
4875
4876 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4877
4879 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4880 CTAI.CanonicalConverted);
4881 ConstraintSatisfaction Satisfaction;
4882 bool AreArgsDependent =
4883 TemplateSpecializationType::anyDependentTemplateArguments(
4884 *TemplateArgs, CTAI.CanonicalConverted);
4885 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.CanonicalConverted,
4886 /*Final=*/false);
4888
4891
4892 if (!AreArgsDependent &&
4894 NamedConcept, AssociatedConstraint(NamedConcept->getConstraintExpr()),
4895 MLTAL,
4896 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4897 TemplateArgs->getRAngleLoc()),
4898 Satisfaction))
4899 return ExprError();
4901 Context,
4903 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4906 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4907}
4908
4910 SourceLocation TemplateKWLoc,
4911 LookupResult &R,
4912 bool RequiresADL,
4913 const TemplateArgumentListInfo *TemplateArgs) {
4914 // FIXME: Can we do any checking at this point? I guess we could check the
4915 // template arguments that we have against the template name, if the template
4916 // name refers to a single template. That's not a terribly common case,
4917 // though.
4918 // foo<int> could identify a single function unambiguously
4919 // This approach does NOT work, since f<int>(1);
4920 // gets resolved prior to resorting to overload resolution
4921 // i.e., template<class T> void f(double);
4922 // vs template<class T, class U> void f(U);
4923
4924 // These should be filtered out by our callers.
4925 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4926
4927 // Non-function templates require a template argument list.
4928 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4929 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4931 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4932 return ExprError();
4933 }
4934 }
4935 bool KnownDependent = false;
4936 // In C++1y, check variable template ids.
4937 if (R.getAsSingle<VarTemplateDecl>()) {
4940 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4941 if (Res.isInvalid() || Res.isUsable())
4942 return Res;
4943 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4944 KnownDependent = true;
4945 }
4946
4947 // We don't want lookup warnings at this point.
4949
4950 if (R.getAsSingle<ConceptDecl>()) {
4951 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4953 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4954 }
4955
4956 // Check variable template ids (C++17) and concept template parameters
4957 // (C++26).
4962 TemplateKWLoc, TemplateArgs);
4963
4964 // Function templates
4967 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4968 R.begin(), R.end(), KnownDependent,
4969 /*KnownInstantiationDependent=*/false);
4970 // Model the templates with UnresolvedTemplateTy. The expression should then
4971 // either be transformed in an instantiation or be diagnosed in
4972 // CheckPlaceholderExpr.
4973 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4975 ULE->setType(Context.UnresolvedTemplateTy);
4976
4977 return ULE;
4978}
4979
4981 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4982 const DeclarationNameInfo &NameInfo,
4983 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4984 assert(TemplateArgs || TemplateKWLoc.isValid());
4985
4986 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4987 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4988 /*EnteringContext=*/false, TemplateKWLoc))
4989 return ExprError();
4990
4991 if (R.isAmbiguous())
4992 return ExprError();
4993
4995 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4996
4997 if (R.empty()) {
4999 Diag(NameInfo.getLoc(), diag::err_no_member)
5000 << NameInfo.getName() << DC << SS.getRange();
5001 return ExprError();
5002 }
5003
5004 // If necessary, build an implicit class member access.
5005 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5006 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5007 /*S=*/nullptr);
5008
5009 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5010}
5011
5013 CXXScopeSpec &SS,
5014 SourceLocation TemplateKWLoc,
5015 const UnqualifiedId &Name,
5016 ParsedType ObjectType,
5017 bool EnteringContext,
5019 bool AllowInjectedClassName) {
5020 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5021 Diag(TemplateKWLoc,
5023 diag::warn_cxx98_compat_template_outside_of_template :
5024 diag::ext_template_outside_of_template)
5025 << FixItHint::CreateRemoval(TemplateKWLoc);
5026
5027 if (SS.isInvalid())
5028 return TNK_Non_template;
5029
5030 // Figure out where isTemplateName is going to look.
5031 DeclContext *LookupCtx = nullptr;
5032 if (SS.isNotEmpty())
5033 LookupCtx = computeDeclContext(SS, EnteringContext);
5034 else if (ObjectType)
5035 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5036
5037 // C++0x [temp.names]p5:
5038 // If a name prefixed by the keyword template is not the name of
5039 // a template, the program is ill-formed. [Note: the keyword
5040 // template may not be applied to non-template members of class
5041 // templates. -end note ] [ Note: as is the case with the
5042 // typename prefix, the template prefix is allowed in cases
5043 // where it is not strictly necessary; i.e., when the
5044 // nested-name-specifier or the expression on the left of the ->
5045 // or . is not dependent on a template-parameter, or the use
5046 // does not appear in the scope of a template. -end note]
5047 //
5048 // Note: C++03 was more strict here, because it banned the use of
5049 // the "template" keyword prior to a template-name that was not a
5050 // dependent name. C++ DR468 relaxed this requirement (the
5051 // "template" keyword is now permitted). We follow the C++0x
5052 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5053 bool MemberOfUnknownSpecialization;
5054 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5055 ObjectType, EnteringContext, Result,
5056 MemberOfUnknownSpecialization);
5057 if (TNK != TNK_Non_template) {
5058 // We resolved this to a (non-dependent) template name. Return it.
5059 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5060 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5062 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5063 // C++14 [class.qual]p2:
5064 // In a lookup in which function names are not ignored and the
5065 // nested-name-specifier nominates a class C, if the name specified
5066 // [...] is the injected-class-name of C, [...] the name is instead
5067 // considered to name the constructor
5068 //
5069 // We don't get here if naming the constructor would be valid, so we
5070 // just reject immediately and recover by treating the
5071 // injected-class-name as naming the template.
5072 Diag(Name.getBeginLoc(),
5073 diag::ext_out_of_line_qualified_id_type_names_constructor)
5074 << Name.Identifier
5075 << 0 /*injected-class-name used as template name*/
5076 << TemplateKWLoc.isValid();
5077 }
5078 return TNK;
5079 }
5080
5081 if (!MemberOfUnknownSpecialization) {
5082 // Didn't find a template name, and the lookup wasn't dependent.
5083 // Do the lookup again to determine if this is a "nothing found" case or
5084 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5085 // need to do this.
5087 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5089 // Tell LookupTemplateName that we require a template so that it diagnoses
5090 // cases where it finds a non-template.
5091 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5092 ? RequiredTemplateKind(TemplateKWLoc)
5094 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5095 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5096 !R.isAmbiguous()) {
5097 if (LookupCtx)
5098 Diag(Name.getBeginLoc(), diag::err_no_member)
5099 << DNI.getName() << LookupCtx << SS.getRange();
5100 else
5101 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5102 << DNI.getName() << SS.getRange();
5103 }
5104 return TNK_Non_template;
5105 }
5106
5107 NestedNameSpecifier Qualifier = SS.getScopeRep();
5108
5109 switch (Name.getKind()) {
5111 Result = TemplateTy::make(Context.getDependentTemplateName(
5112 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5114
5116 Result = TemplateTy::make(Context.getDependentTemplateName(
5117 {Qualifier, Name.OperatorFunctionId.Operator,
5118 TemplateKWLoc.isValid()}));
5119 return TNK_Function_template;
5120
5122 // This is a kind of template name, but can never occur in a dependent
5123 // scope (literal operators can only be declared at namespace scope).
5124 break;
5125
5126 default:
5127 break;
5128 }
5129
5130 // This name cannot possibly name a dependent template. Diagnose this now
5131 // rather than building a dependent template name that can never be valid.
5132 Diag(Name.getBeginLoc(),
5133 diag::err_template_kw_refers_to_dependent_non_template)
5135 << TemplateKWLoc.isValid() << TemplateKWLoc;
5136 return TNK_Non_template;
5137}
5138
5141 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5142 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5143 const TemplateArgument &Arg = AL.getArgument();
5145 TypeSourceInfo *TSI = nullptr;
5146
5147 // Check template type parameter.
5148 switch(Arg.getKind()) {
5150 // C++ [temp.arg.type]p1:
5151 // A template-argument for a template-parameter which is a
5152 // type shall be a type-id.
5153 ArgType = Arg.getAsType();
5154 TSI = AL.getTypeSourceInfo();
5155 break;
5158 // We have a template type parameter but the template argument
5159 // is a template without any arguments.
5160 SourceRange SR = AL.getSourceRange();
5163 return true;
5164 }
5166 // We have a template type parameter but the template argument is an
5167 // expression; see if maybe it is missing the "typename" keyword.
5168 CXXScopeSpec SS;
5169 DeclarationNameInfo NameInfo;
5170
5171 if (DependentScopeDeclRefExpr *ArgExpr =
5172 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5173 SS.Adopt(ArgExpr->getQualifierLoc());
5174 NameInfo = ArgExpr->getNameInfo();
5175 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5176 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5177 if (ArgExpr->isImplicitAccess()) {
5178 SS.Adopt(ArgExpr->getQualifierLoc());
5179 NameInfo = ArgExpr->getMemberNameInfo();
5180 }
5181 }
5182
5183 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5184 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5185 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5186
5187 if (Result.getAsSingle<TypeDecl>() ||
5188 Result.wasNotFoundInCurrentInstantiation()) {
5189 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5190 // Suggest that the user add 'typename' before the NNS.
5192 Diag(Loc, getLangOpts().MSVCCompat
5193 ? diag::ext_ms_template_type_arg_missing_typename
5194 : diag::err_template_arg_must_be_type_suggest)
5195 << FixItHint::CreateInsertion(Loc, "typename ");
5197
5198 // Recover by synthesizing a type using the location information that we
5199 // already have.
5200 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5201 SS.getScopeRep(), II);
5202 TypeLocBuilder TLB;
5204 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5206 TL.setNameLoc(NameInfo.getLoc());
5207 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5208
5209 // Overwrite our input TemplateArgumentLoc so that we can recover
5210 // properly.
5213
5214 break;
5215 }
5216 }
5217 // fallthrough
5218 [[fallthrough]];
5219 }
5220 default: {
5221 // We allow instantiating a template with template argument packs when
5222 // building deduction guides.
5223 if (Arg.getKind() == TemplateArgument::Pack &&
5224 CodeSynthesisContexts.back().Kind ==
5226 SugaredConverted.push_back(Arg);
5227 CanonicalConverted.push_back(Arg);
5228 return false;
5229 }
5230 // We have a template type parameter but the template argument
5231 // is not a type.
5232 SourceRange SR = AL.getSourceRange();
5233 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5235
5236 return true;
5237 }
5238 }
5239
5240 if (CheckTemplateArgument(TSI))
5241 return true;
5242
5243 // Objective-C ARC:
5244 // If an explicitly-specified template argument type is a lifetime type
5245 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5246 if (getLangOpts().ObjCAutoRefCount &&
5247 ArgType->isObjCLifetimeType() &&
5248 !ArgType.getObjCLifetime()) {
5249 Qualifiers Qs;
5251 ArgType = Context.getQualifiedType(ArgType, Qs);
5252 }
5253
5254 SugaredConverted.push_back(TemplateArgument(ArgType));
5255 CanonicalConverted.push_back(
5256 TemplateArgument(Context.getCanonicalType(ArgType)));
5257 return false;
5258}
5259
5260/// Substitute template arguments into the default template argument for
5261/// the given template type parameter.
5262///
5263/// \param SemaRef the semantic analysis object for which we are performing
5264/// the substitution.
5265///
5266/// \param Template the template that we are synthesizing template arguments
5267/// for.
5268///
5269/// \param TemplateLoc the location of the template name that started the
5270/// template-id we are checking.
5271///
5272/// \param RAngleLoc the location of the right angle bracket ('>') that
5273/// terminates the template-id.
5274///
5275/// \param Param the template template parameter whose default we are
5276/// substituting into.
5277///
5278/// \param Converted the list of template arguments provided for template
5279/// parameters that precede \p Param in the template parameter list.
5280///
5281/// \param Output the resulting substituted template argument.
5282///
5283/// \returns true if an error occurred.
5285 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5286 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5287 ArrayRef<TemplateArgument> SugaredConverted,
5288 ArrayRef<TemplateArgument> CanonicalConverted,
5289 TemplateArgumentLoc &Output) {
5290 Output = Param->getDefaultArgument();
5291
5292 // If the argument type is dependent, instantiate it now based
5293 // on the previously-computed template arguments.
5294 if (Output.getArgument().isInstantiationDependent()) {
5295 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5296 SugaredConverted,
5297 SourceRange(TemplateLoc, RAngleLoc));
5298 if (Inst.isInvalid())
5299 return true;
5300
5301 // Only substitute for the innermost template argument list.
5302 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5303 /*Final=*/true);
5304 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5305 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5306
5307 bool ForLambdaCallOperator = false;
5308 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5309 ForLambdaCallOperator = Rec->isLambda();
5310 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5311 !ForLambdaCallOperator);
5312
5313 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5314 Param->getDefaultArgumentLoc(),
5315 Param->getDeclName()))
5316 return true;
5317 }
5318
5319 return false;
5320}
5321
5322/// Substitute template arguments into the default template argument for
5323/// the given non-type template parameter.
5324///
5325/// \param SemaRef the semantic analysis object for which we are performing
5326/// the substitution.
5327///
5328/// \param Template the template that we are synthesizing template arguments
5329/// for.
5330///
5331/// \param TemplateLoc the location of the template name that started the
5332/// template-id we are checking.
5333///
5334/// \param RAngleLoc the location of the right angle bracket ('>') that
5335/// terminates the template-id.
5336///
5337/// \param Param the non-type template parameter whose default we are
5338/// substituting into.
5339///
5340/// \param Converted the list of template arguments provided for template
5341/// parameters that precede \p Param in the template parameter list.
5342///
5343/// \returns the substituted template argument, or NULL if an error occurred.
5345 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5346 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5347 ArrayRef<TemplateArgument> SugaredConverted,
5348 ArrayRef<TemplateArgument> CanonicalConverted,
5349 TemplateArgumentLoc &Output) {
5350 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5351 SugaredConverted,
5352 SourceRange(TemplateLoc, RAngleLoc));
5353 if (Inst.isInvalid())
5354 return true;
5355
5356 // Only substitute for the innermost template argument list.
5357 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5358 /*Final=*/true);
5359 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5360 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5361
5362 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5363 EnterExpressionEvaluationContext ConstantEvaluated(
5365 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5366 TemplateArgLists, Output);
5367}
5368
5369/// Substitute template arguments into the default template argument for
5370/// the given template template parameter.
5371///
5372/// \param SemaRef the semantic analysis object for which we are performing
5373/// the substitution.
5374///
5375/// \param Template the template that we are synthesizing template arguments
5376/// for.
5377///
5378/// \param TemplateLoc the location of the template name that started the
5379/// template-id we are checking.
5380///
5381/// \param RAngleLoc the location of the right angle bracket ('>') that
5382/// terminates the template-id.
5383///
5384/// \param Param the template template parameter whose default we are
5385/// substituting into.
5386///
5387/// \param Converted the list of template arguments provided for template
5388/// parameters that precede \p Param in the template parameter list.
5389///
5390/// \param QualifierLoc Will be set to the nested-name-specifier (with
5391/// source-location information) that precedes the template name.
5392///
5393/// \returns the substituted template argument, or NULL if an error occurred.
5395 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5396 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5398 ArrayRef<TemplateArgument> SugaredConverted,
5399 ArrayRef<TemplateArgument> CanonicalConverted,
5400 NestedNameSpecifierLoc &QualifierLoc) {
5402 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5403 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5404 if (Inst.isInvalid())
5405 return TemplateName();
5406
5407 // Only substitute for the innermost template argument list.
5408 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5409 /*Final=*/true);
5410 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5411 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5412
5413 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5414
5415 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5416 QualifierLoc = A.getTemplateQualifierLoc();
5417 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5419 A.getTemplateNameLoc(), TemplateArgLists);
5420}
5421
5423 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5424 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5425 ArrayRef<TemplateArgument> SugaredConverted,
5426 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5427 HasDefaultArg = false;
5428
5429 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5430 if (!hasReachableDefaultArgument(TypeParm))
5431 return TemplateArgumentLoc();
5432
5433 HasDefaultArg = true;
5434 TemplateArgumentLoc Output;
5435 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5436 RAngleLoc, TypeParm, SugaredConverted,
5437 CanonicalConverted, Output))
5438 return TemplateArgumentLoc();
5439 return Output;
5440 }
5441
5442 if (NonTypeTemplateParmDecl *NonTypeParm
5443 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5444 if (!hasReachableDefaultArgument(NonTypeParm))
5445 return TemplateArgumentLoc();
5446
5447 HasDefaultArg = true;
5448 TemplateArgumentLoc Output;
5449 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5450 RAngleLoc, NonTypeParm, SugaredConverted,
5451 CanonicalConverted, Output))
5452 return TemplateArgumentLoc();
5453 return Output;
5454 }
5455
5456 TemplateTemplateParmDecl *TempTempParm
5458 if (!hasReachableDefaultArgument(TempTempParm))
5459 return TemplateArgumentLoc();
5460
5461 HasDefaultArg = true;
5462 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5463 NestedNameSpecifierLoc QualifierLoc;
5465 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5466 SugaredConverted, CanonicalConverted, QualifierLoc);
5467 if (TName.isNull())
5468 return TemplateArgumentLoc();
5469
5470 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5471 QualifierLoc, A.getTemplateNameLoc());
5472}
5473
5474/// Convert a template-argument that we parsed as a type into a template, if
5475/// possible. C++ permits injected-class-names to perform dual service as
5476/// template template arguments and as template type arguments.
5479 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5480 if (!TagLoc)
5481 return TemplateArgumentLoc();
5482
5483 // If this type was written as an injected-class-name, it can be used as a
5484 // template template argument.
5485 // If this type was written as an injected-class-name, it may have been
5486 // converted to a RecordType during instantiation. If the RecordType is
5487 // *not* wrapped in a TemplateSpecializationType and denotes a class
5488 // template specialization, it must have come from an injected-class-name.
5489
5490 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5491 if (Name.isNull())
5492 return TemplateArgumentLoc();
5493
5494 return TemplateArgumentLoc(Context, Name,
5495 /*TemplateKWLoc=*/SourceLocation(),
5496 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5497}
5498
5501 SourceLocation TemplateLoc,
5502 SourceLocation RAngleLoc,
5503 unsigned ArgumentPackIndex,
5506 // Check template type parameters.
5507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5508 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5509 CTAI.CanonicalConverted);
5510
5511 const TemplateArgument &Arg = ArgLoc.getArgument();
5512 // Check non-type template parameters.
5513 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5514 // Do substitution on the type of the non-type template parameter
5515 // with the template arguments we've seen thus far. But if the
5516 // template has a dependent context then we cannot substitute yet.
5517 QualType NTTPType = NTTP->getType();
5518 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5519 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5520
5521 if (NTTPType->isInstantiationDependentType() &&
5523 !Template->getDeclContext()->isDependentContext()) {
5524 // Do substitution on the type of the non-type template parameter.
5525 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5526 CTAI.SugaredConverted,
5527 SourceRange(TemplateLoc, RAngleLoc));
5528 if (Inst.isInvalid())
5529 return true;
5530
5532 /*Final=*/true);
5533 // If the parameter is a pack expansion, expand this slice of the pack.
5534 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5535 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5536 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5537 NTTP->getDeclName());
5538 } else {
5539 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5540 NTTP->getDeclName());
5541 }
5542
5543 // If that worked, check the non-type template parameter type
5544 // for validity.
5545 if (!NTTPType.isNull())
5546 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5547 NTTP->getLocation());
5548 if (NTTPType.isNull())
5549 return true;
5550 }
5551
5552 auto checkExpr = [&](Expr *E) -> Expr * {
5553 TemplateArgument SugaredResult, CanonicalResult;
5554 unsigned CurSFINAEErrors = NumSFINAEErrors;
5556 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5557 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5558 // If the current template argument causes an error, give up now.
5559 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5560 return nullptr;
5561 CTAI.SugaredConverted.push_back(SugaredResult);
5562 CTAI.CanonicalConverted.push_back(CanonicalResult);
5563 return Res.get();
5564 };
5565
5566 switch (Arg.getKind()) {
5568 llvm_unreachable("Should never see a NULL template argument here");
5569
5571 Expr *E = Arg.getAsExpr();
5572 Expr *R = checkExpr(E);
5573 if (!R)
5574 return true;
5575 // If the resulting expression is new, then use it in place of the
5576 // old expression in the template argument.
5577 if (R != E) {
5578 TemplateArgument TA(R, /*IsCanonical=*/false);
5579 ArgLoc = TemplateArgumentLoc(TA, R);
5580 }
5581 break;
5582 }
5583
5584 // As for the converted NTTP kinds, they still might need another
5585 // conversion, as the new corresponding parameter might be different.
5586 // Ideally, we would always perform substitution starting with sugared types
5587 // and never need these, as we would still have expressions. Since these are
5588 // needed so rarely, it's probably a better tradeoff to just convert them
5589 // back to expressions.
5594 // FIXME: StructuralValue is untested here.
5595 ExprResult R =
5597 assert(R.isUsable());
5598 if (!checkExpr(R.get()))
5599 return true;
5600 break;
5601 }
5602
5605 // We were given a template template argument. It may not be ill-formed;
5606 // see below.
5609 // We have a template argument such as \c T::template X, which we
5610 // parsed as a template template argument. However, since we now
5611 // know that we need a non-type template argument, convert this
5612 // template name into an expression.
5613
5614 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5615 ArgLoc.getTemplateNameLoc());
5616
5617 CXXScopeSpec SS;
5618 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5619 // FIXME: the template-template arg was a DependentTemplateName,
5620 // so it was provided with a template keyword. However, its source
5621 // location is not stored in the template argument structure.
5622 SourceLocation TemplateKWLoc;
5624 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5625 nullptr);
5626
5627 // If we parsed the template argument as a pack expansion, create a
5628 // pack expansion expression.
5631 if (E.isInvalid())
5632 return true;
5633 }
5634
5635 TemplateArgument SugaredResult, CanonicalResult;
5637 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5638 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5639 if (E.isInvalid())
5640 return true;
5641
5642 CTAI.SugaredConverted.push_back(SugaredResult);
5643 CTAI.CanonicalConverted.push_back(CanonicalResult);
5644 break;
5645 }
5646
5647 // We have a template argument that actually does refer to a class
5648 // template, alias template, or template template parameter, and
5649 // therefore cannot be a non-type template argument.
5650 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5651 << ArgLoc.getSourceRange();
5653
5654 return true;
5655
5657 // We have a non-type template parameter but the template
5658 // argument is a type.
5659
5660 // C++ [temp.arg]p2:
5661 // In a template-argument, an ambiguity between a type-id and
5662 // an expression is resolved to a type-id, regardless of the
5663 // form of the corresponding template-parameter.
5664 //
5665 // We warn specifically about this case, since it can be rather
5666 // confusing for users.
5667 QualType T = Arg.getAsType();
5668 SourceRange SR = ArgLoc.getSourceRange();
5669 if (T->isFunctionType())
5670 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5671 else
5672 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5674 return true;
5675 }
5676
5678 llvm_unreachable("Caller must expand template argument packs");
5679 }
5680
5681 return false;
5682 }
5683
5684
5685 // Check template template parameters.
5687
5688 TemplateParameterList *Params = TempParm->getTemplateParameters();
5689 if (TempParm->isExpandedParameterPack())
5690 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5691
5692 // Substitute into the template parameter list of the template
5693 // template parameter, since previously-supplied template arguments
5694 // may appear within the template template parameter.
5695 //
5696 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5697 {
5698 // Set up a template instantiation context.
5700 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5701 CTAI.SugaredConverted,
5702 SourceRange(TemplateLoc, RAngleLoc));
5703 if (Inst.isInvalid())
5704 return true;
5705
5706 Params = SubstTemplateParams(
5707 Params, CurContext,
5709 /*Final=*/true),
5710 /*EvaluateConstraints=*/false);
5711 if (!Params)
5712 return true;
5713 }
5714
5715 // C++1z [temp.local]p1: (DR1004)
5716 // When [the injected-class-name] is used [...] as a template-argument for
5717 // a template template-parameter [...] it refers to the class template
5718 // itself.
5719 if (Arg.getKind() == TemplateArgument::Type) {
5721 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5722 if (!ConvertedArg.getArgument().isNull())
5723 ArgLoc = ConvertedArg;
5724 }
5725
5726 switch (Arg.getKind()) {
5728 llvm_unreachable("Should never see a NULL template argument here");
5729
5732 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5733 CTAI.PartialOrdering,
5734 &CTAI.StrictPackMatch))
5735 return true;
5736
5737 CTAI.SugaredConverted.push_back(Arg);
5738 CTAI.CanonicalConverted.push_back(
5739 Context.getCanonicalTemplateArgument(Arg));
5740 break;
5741
5744 auto Kind = 0;
5745 switch (TempParm->templateParameterKind()) {
5747 Kind = 1;
5748 break;
5750 Kind = 2;
5751 break;
5752 default:
5753 break;
5754 }
5755
5756 // We have a template template parameter but the template
5757 // argument does not refer to a template.
5758 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5759 << Kind << getLangOpts().CPlusPlus11;
5760 return true;
5761 }
5762
5767 llvm_unreachable("non-type argument with template template parameter");
5768
5770 llvm_unreachable("Caller must expand template argument packs");
5771 }
5772
5773 return false;
5774}
5775
5776/// Diagnose a missing template argument.
5777template<typename TemplateParmDecl>
5779 TemplateDecl *TD,
5780 const TemplateParmDecl *D,
5782 // Dig out the most recent declaration of the template parameter; there may be
5783 // declarations of the template that are more recent than TD.
5785 ->getTemplateParameters()
5786 ->getParam(D->getIndex()));
5787
5788 // If there's a default argument that's not reachable, diagnose that we're
5789 // missing a module import.
5791 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5793 D->getDefaultArgumentLoc(), Modules,
5795 /*Recover*/true);
5796 return true;
5797 }
5798
5799 // FIXME: If there's a more recent default argument that *is* visible,
5800 // diagnose that it was declared too late.
5801
5803
5804 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5805 << /*not enough args*/0
5807 << TD;
5808 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5809 return true;
5810}
5811
5812/// Check that the given template argument list is well-formed
5813/// for specializing the given template.
5815 TemplateDecl *Template, SourceLocation TemplateLoc,
5816 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5817 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5818 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5819
5821 *ConstraintsNotSatisfied = false;
5822
5823 // Make a copy of the template arguments for processing. Only make the
5824 // changes at the end when successful in matching the arguments to the
5825 // template.
5826 TemplateArgumentListInfo NewArgs = TemplateArgs;
5827
5829
5830 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5831
5832 // C++23 [temp.arg.general]p1:
5833 // [...] The type and form of each template-argument specified in
5834 // a template-id shall match the type and form specified for the
5835 // corresponding parameter declared by the template in its
5836 // template-parameter-list.
5837 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5838 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5839 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5840 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5841 LocalInstantiationScope InstScope(*this, true);
5842 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5843 ParamEnd = Params->end(),
5844 Param = ParamBegin;
5845 Param != ParamEnd;
5846 /* increment in loop */) {
5847 if (size_t ParamIdx = Param - ParamBegin;
5848 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5849 // All written arguments should have been consumed by this point.
5850 assert(ArgIdx == NumArgs && "bad default argument deduction");
5851 if (ParamIdx == DefaultArgs.StartPos) {
5852 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5853 // Default arguments from a DeducedTemplateName are already converted.
5854 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5855 CTAI.SugaredConverted.push_back(DefArg);
5856 CTAI.CanonicalConverted.push_back(
5857 Context.getCanonicalTemplateArgument(DefArg));
5858 ++Param;
5859 }
5860 continue;
5861 }
5862 }
5863
5864 // If we have an expanded parameter pack, make sure we don't have too
5865 // many arguments.
5866 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5867 if (*Expansions == SugaredArgumentPack.size()) {
5868 // We're done with this parameter pack. Pack up its arguments and add
5869 // them to the list.
5870 CTAI.SugaredConverted.push_back(
5871 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5872 SugaredArgumentPack.clear();
5873
5874 CTAI.CanonicalConverted.push_back(
5875 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5876 CanonicalArgumentPack.clear();
5877
5878 // This argument is assigned to the next parameter.
5879 ++Param;
5880 continue;
5881 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5882 // Not enough arguments for this parameter pack.
5883 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5884 << /*not enough args*/0
5886 << Template;
5888 return true;
5889 }
5890 }
5891
5892 // Check for builtins producing template packs in this context, we do not
5893 // support them yet.
5894 if (const NonTypeTemplateParmDecl *NTTP =
5895 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5896 NTTP && NTTP->isPackExpansion()) {
5897 auto TL = NTTP->getTypeSourceInfo()
5898 ->getTypeLoc()
5901 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5902 for (const auto &UPP : Unexpanded) {
5903 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5904 if (!TST)
5905 continue;
5906 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5907 // Expanding a built-in pack in this context is not yet supported.
5908 Diag(TL.getEllipsisLoc(),
5909 diag::err_unsupported_builtin_template_pack_expansion)
5910 << TST->getTemplateName();
5911 return true;
5912 }
5913 }
5914
5915 if (ArgIdx < NumArgs) {
5916 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5917 bool NonPackParameter =
5918 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5919 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5920
5921 if (ArgIsExpansion && CTAI.MatchingTTP) {
5922 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5923 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5924 ++Param) {
5925 TemplateArgument &Arg = Args[Param - First];
5926 Arg = ArgLoc.getArgument();
5927 if (!(*Param)->isTemplateParameterPack() ||
5928 getExpandedPackSize(*Param))
5929 Arg = Arg.getPackExpansionPattern();
5930 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5931 SaveAndRestore _1(CTAI.PartialOrdering, false);
5932 SaveAndRestore _2(CTAI.MatchingTTP, true);
5933 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5934 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5936 return true;
5937 Arg = NewArgLoc.getArgument();
5938 CTAI.CanonicalConverted.back().setIsDefaulted(
5939 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
5940 CTAI.CanonicalConverted,
5941 Params->getDepth()));
5942 }
5943 ArgLoc =
5945 ArgLoc.getLocInfo());
5946 } else {
5947 SaveAndRestore _1(CTAI.PartialOrdering, false);
5948 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5949 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5951 return true;
5952 CTAI.CanonicalConverted.back().setIsDefaulted(
5953 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
5954 *Param, CTAI.CanonicalConverted,
5955 Params->getDepth()));
5956 if (ArgIsExpansion && NonPackParameter) {
5957 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5958 // alias template or concept, and it's not part of a parameter pack.
5959 // This can't be canonicalized, so reject it now.
5961 Diag(ArgLoc.getLocation(),
5962 diag::err_template_expansion_into_fixed_list)
5963 << (isa<ConceptDecl>(Template) ? 1 : 0)
5964 << ArgLoc.getSourceRange();
5966 return true;
5967 }
5968 }
5969 }
5970
5971 // We're now done with this argument.
5972 ++ArgIdx;
5973
5974 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
5975 // Directly convert the remaining arguments, because we don't know what
5976 // parameters they'll match up with.
5977
5978 if (!SugaredArgumentPack.empty()) {
5979 // If we were part way through filling in an expanded parameter pack,
5980 // fall back to just producing individual arguments.
5981 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
5982 SugaredArgumentPack.begin(),
5983 SugaredArgumentPack.end());
5984 SugaredArgumentPack.clear();
5985
5986 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
5987 CanonicalArgumentPack.begin(),
5988 CanonicalArgumentPack.end());
5989 CanonicalArgumentPack.clear();
5990 }
5991
5992 while (ArgIdx < NumArgs) {
5993 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5994 CTAI.SugaredConverted.push_back(Arg);
5995 CTAI.CanonicalConverted.push_back(
5996 Context.getCanonicalTemplateArgument(Arg));
5997 ++ArgIdx;
5998 }
5999
6000 return false;
6001 }
6002
6003 if ((*Param)->isTemplateParameterPack()) {
6004 // The template parameter was a template parameter pack, so take the
6005 // deduced argument and place it on the argument pack. Note that we
6006 // stay on the same template parameter so that we can deduce more
6007 // arguments.
6008 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6009 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6010 } else {
6011 // Move to the next template parameter.
6012 ++Param;
6013 }
6014 continue;
6015 }
6016
6017 // If we're checking a partial template argument list, we're done.
6018 if (PartialTemplateArgs) {
6019 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6020 CTAI.SugaredConverted.push_back(
6021 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6022 CTAI.CanonicalConverted.push_back(
6023 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6024 }
6025 return false;
6026 }
6027
6028 // If we have a template parameter pack with no more corresponding
6029 // arguments, just break out now and we'll fill in the argument pack below.
6030 if ((*Param)->isTemplateParameterPack()) {
6031 assert(!getExpandedPackSize(*Param) &&
6032 "Should have dealt with this already");
6033
6034 // A non-expanded parameter pack before the end of the parameter list
6035 // only occurs for an ill-formed template parameter list, unless we've
6036 // got a partial argument list for a function template, so just bail out.
6037 if (Param + 1 != ParamEnd) {
6038 assert(
6039 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6040 "Concept templates must have parameter packs at the end.");
6041 return true;
6042 }
6043
6044 CTAI.SugaredConverted.push_back(
6045 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6046 SugaredArgumentPack.clear();
6047
6048 CTAI.CanonicalConverted.push_back(
6049 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6050 CanonicalArgumentPack.clear();
6051
6052 ++Param;
6053 continue;
6054 }
6055
6056 // Check whether we have a default argument.
6057 bool HasDefaultArg;
6058
6059 // Retrieve the default template argument from the template
6060 // parameter. For each kind of template parameter, we substitute the
6061 // template arguments provided thus far and any "outer" template arguments
6062 // (when the template parameter was part of a nested template) into
6063 // the default argument.
6065 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6066 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6067
6068 if (Arg.getArgument().isNull()) {
6069 if (!HasDefaultArg) {
6070 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6071 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6072 NewArgs);
6073 if (NonTypeTemplateParmDecl *NTTP =
6074 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6075 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6076 NewArgs);
6077 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6079 NewArgs);
6080 }
6081 return true;
6082 }
6083
6084 // Introduce an instantiation record that describes where we are using
6085 // the default template argument. We're not actually instantiating a
6086 // template here, we just create this object to put a note into the
6087 // context stack.
6088 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6089 CTAI.SugaredConverted,
6090 SourceRange(TemplateLoc, RAngleLoc));
6091 if (Inst.isInvalid())
6092 return true;
6093
6094 SaveAndRestore _1(CTAI.PartialOrdering, false);
6095 SaveAndRestore _2(CTAI.MatchingTTP, false);
6096 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6097 // Check the default template argument.
6098 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6099 CTAI, CTAK_Specified))
6100 return true;
6101
6102 CTAI.SugaredConverted.back().setIsDefaulted(true);
6103 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6104
6105 // Core issue 150 (assumed resolution): if this is a template template
6106 // parameter, keep track of the default template arguments from the
6107 // template definition.
6108 if (isTemplateTemplateParameter)
6109 NewArgs.addArgument(Arg);
6110
6111 // Move to the next template parameter and argument.
6112 ++Param;
6113 ++ArgIdx;
6114 }
6115
6116 // If we're performing a partial argument substitution, allow any trailing
6117 // pack expansions; they might be empty. This can happen even if
6118 // PartialTemplateArgs is false (the list of arguments is complete but
6119 // still dependent).
6120 if (CTAI.MatchingTTP ||
6122 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6123 while (ArgIdx < NumArgs &&
6124 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6125 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6126 CTAI.SugaredConverted.push_back(Arg);
6127 CTAI.CanonicalConverted.push_back(
6128 Context.getCanonicalTemplateArgument(Arg));
6129 }
6130 }
6131
6132 // If we have any leftover arguments, then there were too many arguments.
6133 // Complain and fail.
6134 if (ArgIdx < NumArgs) {
6135 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6136 << /*too many args*/1
6138 << Template
6139 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6141 return true;
6142 }
6143
6144 // No problems found with the new argument list, propagate changes back
6145 // to caller.
6146 if (UpdateArgsWithConversions)
6147 TemplateArgs = std::move(NewArgs);
6148
6149 if (!PartialTemplateArgs) {
6150 // Setup the context/ThisScope for the case where we are needing to
6151 // re-instantiate constraints outside of normal instantiation.
6152 DeclContext *NewContext = Template->getDeclContext();
6153
6154 // If this template is in a template, make sure we extract the templated
6155 // decl.
6156 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6157 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6158 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6159
6160 Qualifiers ThisQuals;
6161 if (const auto *Method =
6162 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6163 ThisQuals = Method->getMethodQualifiers();
6164
6165 ContextRAII Context(*this, NewContext);
6166 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6167
6169 Template, NewContext, /*Final=*/false, CTAI.CanonicalConverted,
6170 /*RelativeToPrimary=*/true,
6171 /*Pattern=*/nullptr,
6172 /*ForConceptInstantiation=*/true);
6174 Template, MLTAL,
6175 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6178 return true;
6179 }
6180 }
6181
6182 return false;
6183}
6184
6185namespace {
6186 class UnnamedLocalNoLinkageFinder
6187 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6188 {
6189 Sema &S;
6190 SourceRange SR;
6191
6193
6194 public:
6195 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6196
6197 bool Visit(QualType T) {
6198 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6199 }
6200
6201#define TYPE(Class, Parent) \
6202 bool Visit##Class##Type(const Class##Type *);
6203#define ABSTRACT_TYPE(Class, Parent) \
6204 bool Visit##Class##Type(const Class##Type *) { return false; }
6205#define NON_CANONICAL_TYPE(Class, Parent) \
6206 bool Visit##Class##Type(const Class##Type *) { return false; }
6207#include "clang/AST/TypeNodes.inc"
6208
6209 bool VisitTagDecl(const TagDecl *Tag);
6210 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6211 };
6212} // end anonymous namespace
6213
6214bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6215 return false;
6216}
6217
6218bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6219 return Visit(T->getElementType());
6220}
6221
6222bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6223 return Visit(T->getPointeeType());
6224}
6225
6226bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6227 const BlockPointerType* T) {
6228 return Visit(T->getPointeeType());
6229}
6230
6231bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6232 const LValueReferenceType* T) {
6233 return Visit(T->getPointeeType());
6234}
6235
6236bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6237 const RValueReferenceType* T) {
6238 return Visit(T->getPointeeType());
6239}
6240
6241bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6242 const MemberPointerType *T) {
6243 if (Visit(T->getPointeeType()))
6244 return true;
6245 if (auto *RD = T->getMostRecentCXXRecordDecl())
6246 return VisitTagDecl(RD);
6247 return VisitNestedNameSpecifier(T->getQualifier());
6248}
6249
6250bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6251 const ConstantArrayType* T) {
6252 return Visit(T->getElementType());
6253}
6254
6255bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6256 const IncompleteArrayType* T) {
6257 return Visit(T->getElementType());
6258}
6259
6260bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6261 const VariableArrayType* T) {
6262 return Visit(T->getElementType());
6263}
6264
6265bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6266 const DependentSizedArrayType* T) {
6267 return Visit(T->getElementType());
6268}
6269
6270bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6272 return Visit(T->getElementType());
6273}
6274
6275bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6276 const DependentSizedMatrixType *T) {
6277 return Visit(T->getElementType());
6278}
6279
6280bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6282 return Visit(T->getPointeeType());
6283}
6284
6285bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6286 return Visit(T->getElementType());
6287}
6288
6289bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6290 const DependentVectorType *T) {
6291 return Visit(T->getElementType());
6292}
6293
6294bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6295 return Visit(T->getElementType());
6296}
6297
6298bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6299 const ConstantMatrixType *T) {
6300 return Visit(T->getElementType());
6301}
6302
6303bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6304 const FunctionProtoType* T) {
6305 for (const auto &A : T->param_types()) {
6306 if (Visit(A))
6307 return true;
6308 }
6309
6310 return Visit(T->getReturnType());
6311}
6312
6313bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6314 const FunctionNoProtoType* T) {
6315 return Visit(T->getReturnType());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6319 const UnresolvedUsingType*) {
6320 return false;
6321}
6322
6323bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6324 return false;
6325}
6326
6327bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6328 return Visit(T->getUnmodifiedType());
6329}
6330
6331bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6332 return false;
6333}
6334
6335bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6336 const PackIndexingType *) {
6337 return false;
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6341 const UnaryTransformType*) {
6342 return false;
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6346 return Visit(T->getDeducedType());
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6350 const DeducedTemplateSpecializationType *T) {
6351 return Visit(T->getDeducedType());
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6355 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6359 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6363 const TemplateTypeParmType*) {
6364 return false;
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6368 const SubstTemplateTypeParmPackType *) {
6369 return false;
6370}
6371
6372bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6373 const SubstBuiltinTemplatePackType *) {
6374 return false;
6375}
6376
6377bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6378 const TemplateSpecializationType*) {
6379 return false;
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6383 const InjectedClassNameType* T) {
6384 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6385}
6386
6387bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6388 const DependentNameType* T) {
6389 return VisitNestedNameSpecifier(T->getQualifier());
6390}
6391
6392bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6393 const DependentTemplateSpecializationType* T) {
6394 return VisitNestedNameSpecifier(T->getDependentTemplateName().getQualifier());
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6398 const PackExpansionType* T) {
6399 return Visit(T->getPattern());
6400}
6401
6402bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6403 return false;
6404}
6405
6406bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6407 const ObjCInterfaceType *) {
6408 return false;
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6412 const ObjCObjectPointerType *) {
6413 return false;
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6417 return Visit(T->getValueType());
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6421 return false;
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6429 const ArrayParameterType *T) {
6430 return VisitConstantArrayType(T);
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6434 const DependentBitIntType *T) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6439 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6440 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6441 ? diag::warn_cxx98_compat_template_arg_local_type
6442 : diag::ext_template_arg_local_type)
6443 << S.Context.getCanonicalTagType(Tag) << SR;
6444 return true;
6445 }
6446
6447 if (!Tag->hasNameForLinkage()) {
6448 S.Diag(SR.getBegin(),
6449 S.getLangOpts().CPlusPlus11 ?
6450 diag::warn_cxx98_compat_template_arg_unnamed_type :
6451 diag::ext_template_arg_unnamed_type) << SR;
6452 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6453 return true;
6454 }
6455
6456 return false;
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6460 NestedNameSpecifier NNS) {
6461 switch (NNS.getKind()) {
6466 return false;
6468 return Visit(QualType(NNS.getAsType(), 0));
6469 }
6470 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6474 const HLSLAttributedResourceType *T) {
6475 if (T->hasContainedType() && Visit(T->getContainedType()))
6476 return true;
6477 return Visit(T->getWrappedType());
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6481 const HLSLInlineSpirvType *T) {
6482 for (auto &Operand : T->getOperands())
6483 if (Operand.isConstant() && Operand.isLiteral())
6484 if (Visit(Operand.getResultType()))
6485 return true;
6486 return false;
6487}
6488
6490 assert(ArgInfo && "invalid TypeSourceInfo");
6491 QualType Arg = ArgInfo->getType();
6492 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6493 QualType CanonArg = Context.getCanonicalType(Arg);
6494
6495 if (CanonArg->isVariablyModifiedType()) {
6496 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6497 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6498 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6499 }
6500
6501 // C++03 [temp.arg.type]p2:
6502 // A local type, a type with no linkage, an unnamed type or a type
6503 // compounded from any of these types shall not be used as a
6504 // template-argument for a template type-parameter.
6505 //
6506 // C++11 allows these, and even in C++03 we allow them as an extension with
6507 // a warning.
6508 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6509 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6510 (void)Finder.Visit(CanonArg);
6511 }
6512
6513 return false;
6514}
6515
6521
6522/// Determine whether the given template argument is a null pointer
6523/// value of the appropriate type.
6526 QualType ParamType, Expr *Arg,
6527 Decl *Entity = nullptr) {
6528 if (Arg->isValueDependent() || Arg->isTypeDependent())
6529 return NPV_NotNullPointer;
6530
6531 // dllimport'd entities aren't constant but are available inside of template
6532 // arguments.
6533 if (Entity && Entity->hasAttr<DLLImportAttr>())
6534 return NPV_NotNullPointer;
6535
6536 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6537 llvm_unreachable(
6538 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6539
6540 if (!S.getLangOpts().CPlusPlus11)
6541 return NPV_NotNullPointer;
6542
6543 // Determine whether we have a constant expression.
6545 if (ArgRV.isInvalid())
6546 return NPV_Error;
6547 Arg = ArgRV.get();
6548
6549 Expr::EvalResult EvalResult;
6551 EvalResult.Diag = &Notes;
6552 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6553 EvalResult.HasSideEffects) {
6554 SourceLocation DiagLoc = Arg->getExprLoc();
6555
6556 // If our only note is the usual "invalid subexpression" note, just point
6557 // the caret at its location rather than producing an essentially
6558 // redundant note.
6559 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6560 diag::note_invalid_subexpr_in_const_expr) {
6561 DiagLoc = Notes[0].first;
6562 Notes.clear();
6563 }
6564
6565 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6566 << Arg->getType() << Arg->getSourceRange();
6567 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6568 S.Diag(Notes[I].first, Notes[I].second);
6569
6571 return NPV_Error;
6572 }
6573
6574 // C++11 [temp.arg.nontype]p1:
6575 // - an address constant expression of type std::nullptr_t
6576 if (Arg->getType()->isNullPtrType())
6577 return NPV_NullPointer;
6578
6579 // - a constant expression that evaluates to a null pointer value (4.10); or
6580 // - a constant expression that evaluates to a null member pointer value
6581 // (4.11); or
6582 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6583 (EvalResult.Val.isMemberPointer() &&
6584 !EvalResult.Val.getMemberPointerDecl())) {
6585 // If our expression has an appropriate type, we've succeeded.
6586 bool ObjCLifetimeConversion;
6587 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6588 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6589 ObjCLifetimeConversion))
6590 return NPV_NullPointer;
6591
6592 // The types didn't match, but we know we got a null pointer; complain,
6593 // then recover as if the types were correct.
6594 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6595 << Arg->getType() << ParamType << Arg->getSourceRange();
6597 return NPV_NullPointer;
6598 }
6599
6600 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6601 // We found a pointer that isn't null, but doesn't refer to an object.
6602 // We could just return NPV_NotNullPointer, but we can print a better
6603 // message with the information we have here.
6604 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6605 << EvalResult.Val.getAsString(S.Context, ParamType);
6607 return NPV_Error;
6608 }
6609
6610 // If we don't have a null pointer value, but we do have a NULL pointer
6611 // constant, suggest a cast to the appropriate type.
6613 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6614 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6615 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6617 ")");
6619 return NPV_NullPointer;
6620 }
6621
6622 // FIXME: If we ever want to support general, address-constant expressions
6623 // as non-type template arguments, we should return the ExprResult here to
6624 // be interpreted by the caller.
6625 return NPV_NotNullPointer;
6626}
6627
6628/// Checks whether the given template argument is compatible with its
6629/// template parameter.
6630static bool
6632 QualType ParamType, Expr *ArgIn,
6633 Expr *Arg, QualType ArgType) {
6634 bool ObjCLifetimeConversion;
6635 if (ParamType->isPointerType() &&
6636 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6637 S.IsQualificationConversion(ArgType, ParamType, false,
6638 ObjCLifetimeConversion)) {
6639 // For pointer-to-object types, qualification conversions are
6640 // permitted.
6641 } else {
6642 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6643 if (!ParamRef->getPointeeType()->isFunctionType()) {
6644 // C++ [temp.arg.nontype]p5b3:
6645 // For a non-type template-parameter of type reference to
6646 // object, no conversions apply. The type referred to by the
6647 // reference may be more cv-qualified than the (otherwise
6648 // identical) type of the template- argument. The
6649 // template-parameter is bound directly to the
6650 // template-argument, which shall be an lvalue.
6651
6652 // FIXME: Other qualifiers?
6653 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6654 unsigned ArgQuals = ArgType.getCVRQualifiers();
6655
6656 if ((ParamQuals | ArgQuals) != ParamQuals) {
6657 S.Diag(Arg->getBeginLoc(),
6658 diag::err_template_arg_ref_bind_ignores_quals)
6659 << ParamType << Arg->getType() << Arg->getSourceRange();
6661 return true;
6662 }
6663 }
6664 }
6665
6666 // At this point, the template argument refers to an object or
6667 // function with external linkage. We now need to check whether the
6668 // argument and parameter types are compatible.
6669 if (!S.Context.hasSameUnqualifiedType(ArgType,
6670 ParamType.getNonReferenceType())) {
6671 // We can't perform this conversion or binding.
6672 if (ParamType->isReferenceType())
6673 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6674 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6675 else
6676 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6677 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6679 return true;
6680 }
6681 }
6682
6683 return false;
6684}
6685
6686/// Checks whether the given template argument is the address
6687/// of an object or function according to C++ [temp.arg.nontype]p1.
6689 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6690 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6691 bool Invalid = false;
6692 Expr *Arg = ArgIn;
6693 QualType ArgType = Arg->getType();
6694
6695 bool AddressTaken = false;
6696 SourceLocation AddrOpLoc;
6697 if (S.getLangOpts().MicrosoftExt) {
6698 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6699 // dereference and address-of operators.
6700 Arg = Arg->IgnoreParenCasts();
6701
6702 bool ExtWarnMSTemplateArg = false;
6703 UnaryOperatorKind FirstOpKind;
6704 SourceLocation FirstOpLoc;
6705 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6706 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6707 if (UnOpKind == UO_Deref)
6708 ExtWarnMSTemplateArg = true;
6709 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6710 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6711 if (!AddrOpLoc.isValid()) {
6712 FirstOpKind = UnOpKind;
6713 FirstOpLoc = UnOp->getOperatorLoc();
6714 }
6715 } else
6716 break;
6717 }
6718 if (FirstOpLoc.isValid()) {
6719 if (ExtWarnMSTemplateArg)
6720 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6721 << ArgIn->getSourceRange();
6722
6723 if (FirstOpKind == UO_AddrOf)
6724 AddressTaken = true;
6725 else if (Arg->getType()->isPointerType()) {
6726 // We cannot let pointers get dereferenced here, that is obviously not a
6727 // constant expression.
6728 assert(FirstOpKind == UO_Deref);
6729 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6730 << Arg->getSourceRange();
6731 }
6732 }
6733 } else {
6734 // See through any implicit casts we added to fix the type.
6735 Arg = Arg->IgnoreImpCasts();
6736
6737 // C++ [temp.arg.nontype]p1:
6738 //
6739 // A template-argument for a non-type, non-template
6740 // template-parameter shall be one of: [...]
6741 //
6742 // -- the address of an object or function with external
6743 // linkage, including function templates and function
6744 // template-ids but excluding non-static class members,
6745 // expressed as & id-expression where the & is optional if
6746 // the name refers to a function or array, or if the
6747 // corresponding template-parameter is a reference; or
6748
6749 // In C++98/03 mode, give an extension warning on any extra parentheses.
6750 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6751 bool ExtraParens = false;
6752 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6753 if (!Invalid && !ExtraParens) {
6754 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6755 << Arg->getSourceRange();
6756 ExtraParens = true;
6757 }
6758
6759 Arg = Parens->getSubExpr();
6760 }
6761
6762 while (SubstNonTypeTemplateParmExpr *subst =
6763 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6764 Arg = subst->getReplacement()->IgnoreImpCasts();
6765
6766 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6767 if (UnOp->getOpcode() == UO_AddrOf) {
6768 Arg = UnOp->getSubExpr();
6769 AddressTaken = true;
6770 AddrOpLoc = UnOp->getOperatorLoc();
6771 }
6772 }
6773
6774 while (SubstNonTypeTemplateParmExpr *subst =
6775 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6776 Arg = subst->getReplacement()->IgnoreImpCasts();
6777 }
6778
6779 ValueDecl *Entity = nullptr;
6780 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6781 Entity = DRE->getDecl();
6782 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6783 Entity = CUE->getGuidDecl();
6784
6785 // If our parameter has pointer type, check for a null template value.
6786 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6787 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6788 Entity)) {
6789 case NPV_NullPointer:
6790 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6791 SugaredConverted = TemplateArgument(ParamType,
6792 /*isNullPtr=*/true);
6793 CanonicalConverted =
6795 /*isNullPtr=*/true);
6796 return false;
6797
6798 case NPV_Error:
6799 return true;
6800
6801 case NPV_NotNullPointer:
6802 break;
6803 }
6804 }
6805
6806 // Stop checking the precise nature of the argument if it is value dependent,
6807 // it should be checked when instantiated.
6808 if (Arg->isValueDependent()) {
6809 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6810 CanonicalConverted =
6811 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6812 return false;
6813 }
6814
6815 if (!Entity) {
6816 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6817 << Arg->getSourceRange();
6819 return true;
6820 }
6821
6822 // Cannot refer to non-static data members
6823 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6824 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6825 << Entity << Arg->getSourceRange();
6827 return true;
6828 }
6829
6830 // Cannot refer to non-static member functions
6831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6832 if (!Method->isStatic()) {
6833 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6834 << Method << Arg->getSourceRange();
6836 return true;
6837 }
6838 }
6839
6840 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6841 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6842 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6843
6844 // A non-type template argument must refer to an object or function.
6845 if (!Func && !Var && !Guid) {
6846 // We found something, but we don't know specifically what it is.
6847 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6848 << Arg->getSourceRange();
6849 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6850 return true;
6851 }
6852
6853 // Address / reference template args must have external linkage in C++98.
6854 if (Entity->getFormalLinkage() == Linkage::Internal) {
6855 S.Diag(Arg->getBeginLoc(),
6856 S.getLangOpts().CPlusPlus11
6857 ? diag::warn_cxx98_compat_template_arg_object_internal
6858 : diag::ext_template_arg_object_internal)
6859 << !Func << Entity << Arg->getSourceRange();
6860 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6861 << !Func;
6862 } else if (!Entity->hasLinkage()) {
6863 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6864 << !Func << Entity << Arg->getSourceRange();
6865 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6866 << !Func;
6867 return true;
6868 }
6869
6870 if (Var) {
6871 // A value of reference type is not an object.
6872 if (Var->getType()->isReferenceType()) {
6873 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6874 << Var->getType() << Arg->getSourceRange();
6876 return true;
6877 }
6878
6879 // A template argument must have static storage duration.
6880 if (Var->getTLSKind()) {
6881 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6882 << Arg->getSourceRange();
6883 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6884 return true;
6885 }
6886 }
6887
6888 if (AddressTaken && ParamType->isReferenceType()) {
6889 // If we originally had an address-of operator, but the
6890 // parameter has reference type, complain and (if things look
6891 // like they will work) drop the address-of operator.
6892 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6893 ParamType.getNonReferenceType())) {
6894 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6895 << ParamType;
6897 return true;
6898 }
6899
6900 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6901 << ParamType
6902 << FixItHint::CreateRemoval(AddrOpLoc);
6904
6905 ArgType = Entity->getType();
6906 }
6907
6908 // If the template parameter has pointer type, either we must have taken the
6909 // address or the argument must decay to a pointer.
6910 if (!AddressTaken && ParamType->isPointerType()) {
6911 if (Func) {
6912 // Function-to-pointer decay.
6913 ArgType = S.Context.getPointerType(Func->getType());
6914 } else if (Entity->getType()->isArrayType()) {
6915 // Array-to-pointer decay.
6916 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6917 } else {
6918 // If the template parameter has pointer type but the address of
6919 // this object was not taken, complain and (possibly) recover by
6920 // taking the address of the entity.
6921 ArgType = S.Context.getPointerType(Entity->getType());
6922 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6923 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6924 << ParamType;
6926 return true;
6927 }
6928
6929 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6930 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6931
6933 }
6934 }
6935
6936 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6937 Arg, ArgType))
6938 return true;
6939
6940 // Create the template argument.
6941 SugaredConverted = TemplateArgument(Entity, ParamType);
6942 CanonicalConverted =
6944 S.Context.getCanonicalType(ParamType));
6945 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6946 return false;
6947}
6948
6949/// Checks whether the given template argument is a pointer to
6950/// member constant according to C++ [temp.arg.nontype]p1.
6952 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6953 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6954 bool Invalid = false;
6955
6956 Expr *Arg = ResultArg;
6957 bool ObjCLifetimeConversion;
6958
6959 // C++ [temp.arg.nontype]p1:
6960 //
6961 // A template-argument for a non-type, non-template
6962 // template-parameter shall be one of: [...]
6963 //
6964 // -- a pointer to member expressed as described in 5.3.1.
6965 DeclRefExpr *DRE = nullptr;
6966
6967 // In C++98/03 mode, give an extension warning on any extra parentheses.
6968 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6969 bool ExtraParens = false;
6970 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6971 if (!Invalid && !ExtraParens) {
6972 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6973 << Arg->getSourceRange();
6974 ExtraParens = true;
6975 }
6976
6977 Arg = Parens->getSubExpr();
6978 }
6979
6980 while (SubstNonTypeTemplateParmExpr *subst =
6981 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6982 Arg = subst->getReplacement()->IgnoreImpCasts();
6983
6984 // A pointer-to-member constant written &Class::member.
6985 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6986 if (UnOp->getOpcode() == UO_AddrOf) {
6987 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6988 if (DRE && !DRE->getQualifier())
6989 DRE = nullptr;
6990 }
6991 }
6992 // A constant of pointer-to-member type.
6993 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6994 ValueDecl *VD = DRE->getDecl();
6995 if (VD->getType()->isMemberPointerType()) {
6997 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6998 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6999 CanonicalConverted =
7000 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7001 } else {
7002 SugaredConverted = TemplateArgument(VD, ParamType);
7003 CanonicalConverted =
7005 S.Context.getCanonicalType(ParamType));
7006 }
7007 return Invalid;
7008 }
7009 }
7010
7011 DRE = nullptr;
7012 }
7013
7014 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7015
7016 // Check for a null pointer value.
7017 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7018 Entity)) {
7019 case NPV_Error:
7020 return true;
7021 case NPV_NullPointer:
7022 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7023 SugaredConverted = TemplateArgument(ParamType,
7024 /*isNullPtr*/ true);
7025 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7026 /*isNullPtr*/ true);
7027 return false;
7028 case NPV_NotNullPointer:
7029 break;
7030 }
7031
7032 if (S.IsQualificationConversion(ResultArg->getType(),
7033 ParamType.getNonReferenceType(), false,
7034 ObjCLifetimeConversion)) {
7035 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7036 ResultArg->getValueKind())
7037 .get();
7038 } else if (!S.Context.hasSameUnqualifiedType(
7039 ResultArg->getType(), ParamType.getNonReferenceType())) {
7040 // We can't perform this conversion.
7041 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7042 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7044 return true;
7045 }
7046
7047 if (!DRE)
7048 return S.Diag(Arg->getBeginLoc(),
7049 diag::err_template_arg_not_pointer_to_member_form)
7050 << Arg->getSourceRange();
7051
7052 if (isa<FieldDecl>(DRE->getDecl()) ||
7054 isa<CXXMethodDecl>(DRE->getDecl())) {
7055 assert((isa<FieldDecl>(DRE->getDecl()) ||
7058 ->isImplicitObjectMemberFunction()) &&
7059 "Only non-static member pointers can make it here");
7060
7061 // Okay: this is the address of a non-static member, and therefore
7062 // a member pointer constant.
7063 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7064 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7065 CanonicalConverted =
7066 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7067 } else {
7068 ValueDecl *D = DRE->getDecl();
7069 SugaredConverted = TemplateArgument(D, ParamType);
7070 CanonicalConverted =
7072 S.Context.getCanonicalType(ParamType));
7073 }
7074 return Invalid;
7075 }
7076
7077 // We found something else, but we don't know specifically what it is.
7078 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7079 << Arg->getSourceRange();
7080 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7081 return true;
7082}
7083
7084/// Check a template argument against its corresponding
7085/// non-type template parameter.
7086///
7087/// This routine implements the semantics of C++ [temp.arg.nontype].
7088/// If an error occurred, it returns ExprError(); otherwise, it
7089/// returns the converted template argument. \p ParamType is the
7090/// type of the non-type template parameter after it has been instantiated.
7092 Expr *Arg,
7093 TemplateArgument &SugaredConverted,
7094 TemplateArgument &CanonicalConverted,
7095 bool StrictCheck,
7097 SourceLocation StartLoc = Arg->getBeginLoc();
7098 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7099 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7100 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7101 DeductionArg = NewDeductionArg;
7102 if (ArgPE) {
7103 // Recreate a pack expansion if we unwrapped one.
7104 Arg = new (Context) PackExpansionExpr(
7105 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7106 } else {
7107 Arg = DeductionArg;
7108 }
7109 };
7110
7111 // If the parameter type somehow involves auto, deduce the type now.
7112 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7113 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7114 // During template argument deduction, we allow 'decltype(auto)' to
7115 // match an arbitrary dependent argument.
7116 // FIXME: The language rules don't say what happens in this case.
7117 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7118 // expression is merely instantiation-dependent; is this enough?
7119 if (DeductionArg->isTypeDependent()) {
7120 auto *AT = dyn_cast<AutoType>(DeducedT);
7121 if (AT && AT->isDecltypeAuto()) {
7122 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7123 CanonicalConverted = TemplateArgument(
7124 Context.getCanonicalTemplateArgument(SugaredConverted));
7125 return Arg;
7126 }
7127 }
7128
7129 // When checking a deduced template argument, deduce from its type even if
7130 // the type is dependent, in order to check the types of non-type template
7131 // arguments line up properly in partial ordering.
7132 TypeSourceInfo *TSI =
7133 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7135 InitializedEntity Entity =
7138 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7139 Expr *Inits[1] = {DeductionArg};
7140 ParamType =
7141 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7142 if (ParamType.isNull())
7143 return ExprError();
7144 } else {
7145 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7146 Param->getTemplateDepth() + 1);
7147 ParamType = QualType();
7149 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7150 /*DependentDeduction=*/true,
7151 // We do not check constraints right now because the
7152 // immediately-declared constraint of the auto type is
7153 // also an associated constraint, and will be checked
7154 // along with the other associated constraints after
7155 // checking the template argument list.
7156 /*IgnoreConstraints=*/true);
7158 return ExprError();
7160 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7161 Diag(Arg->getExprLoc(),
7162 diag::err_non_type_template_parm_type_deduction_failure)
7163 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7164 << Arg->getSourceRange();
7165 }
7167 return ExprError();
7168 }
7169 }
7170 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7171 // an error. The error message normally references the parameter
7172 // declaration, but here we'll pass the argument location because that's
7173 // where the parameter type is deduced.
7174 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7175 if (ParamType.isNull()) {
7177 return ExprError();
7178 }
7179 }
7180
7181 // We should have already dropped all cv-qualifiers by now.
7182 assert(!ParamType.hasQualifiers() &&
7183 "non-type template parameter type cannot be qualified");
7184
7185 // If either the parameter has a dependent type or the argument is
7186 // type-dependent, there's nothing we can check now.
7187 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7188 // Force the argument to the type of the parameter to maintain invariants.
7190 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7191 ParamType->isLValueReferenceType() ? VK_LValue
7192 : ParamType->isRValueReferenceType() ? VK_XValue
7193 : VK_PRValue);
7194 if (E.isInvalid())
7195 return ExprError();
7196 setDeductionArg(E.get());
7197 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7198 CanonicalConverted = TemplateArgument(
7199 Context.getCanonicalTemplateArgument(SugaredConverted));
7200 return Arg;
7201 }
7202
7203 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7204 if (CTAK == CTAK_Deduced && !StrictCheck &&
7205 (ParamType->isReferenceType()
7206 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7207 DeductionArg->getType())
7208 : !Context.hasSameUnqualifiedType(ParamType,
7209 DeductionArg->getType()))) {
7210 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7211 // we should actually be checking the type of the template argument in P,
7212 // not the type of the template argument deduced from A, against the
7213 // template parameter type.
7214 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7215 << Arg->getType() << ParamType.getUnqualifiedType();
7217 return ExprError();
7218 }
7219
7220 // If the argument is a pack expansion, we don't know how many times it would
7221 // expand. If we continue checking the argument, this will make the template
7222 // definition ill-formed if it would be ill-formed for any number of
7223 // expansions during instantiation time. When partial ordering or matching
7224 // template template parameters, this is exactly what we want. Otherwise, the
7225 // normal template rules apply: we accept the template if it would be valid
7226 // for any number of expansions (i.e. none).
7227 if (ArgPE && !StrictCheck) {
7228 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7229 CanonicalConverted = TemplateArgument(
7230 Context.getCanonicalTemplateArgument(SugaredConverted));
7231 return Arg;
7232 }
7233
7234 // Avoid making a copy when initializing a template parameter of class type
7235 // from a template parameter object of the same type. This is going beyond
7236 // the standard, but is required for soundness: in
7237 // template<A a> struct X { X *p; X<a> *q; };
7238 // ... we need p and q to have the same type.
7239 //
7240 // Similarly, don't inject a call to a copy constructor when initializing
7241 // from a template parameter of the same type.
7242 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7243 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7244 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7245 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7246 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7247
7248 SugaredConverted = TemplateArgument(TPO, ParamType);
7249 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7250 ParamType.getCanonicalType());
7251 return Arg;
7252 }
7254 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7255 CanonicalConverted =
7256 Context.getCanonicalTemplateArgument(SugaredConverted);
7257 return Arg;
7258 }
7259 }
7260
7261 // The initialization of the parameter from the argument is
7262 // a constant-evaluated context.
7265
7266 bool IsConvertedConstantExpression = true;
7267 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7269 StartLoc, /*DirectInit=*/false, DeductionArg);
7270 Expr *Inits[1] = {DeductionArg};
7271 InitializedEntity Entity =
7273 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7275 if (Result.isInvalid() || !Result.get())
7276 return ExprError();
7278 if (Result.isInvalid() || !Result.get())
7279 return ExprError();
7280 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7281 /*DiscardedValue=*/false,
7282 /*IsConstexpr=*/true,
7283 /*IsTemplateArgument=*/true)
7284 .get());
7285 IsConvertedConstantExpression = false;
7286 }
7287
7288 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7289 // C++17 [temp.arg.nontype]p1:
7290 // A template-argument for a non-type template parameter shall be
7291 // a converted constant expression of the type of the template-parameter.
7292 APValue Value;
7293 ExprResult ArgResult;
7294 if (IsConvertedConstantExpression) {
7296 DeductionArg, ParamType,
7297 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7298 assert(!ArgResult.isUnset());
7299 if (ArgResult.isInvalid()) {
7301 return ExprError();
7302 }
7303 } else {
7304 ArgResult = DeductionArg;
7305 }
7306
7307 // For a value-dependent argument, CheckConvertedConstantExpression is
7308 // permitted (and expected) to be unable to determine a value.
7309 if (ArgResult.get()->isValueDependent()) {
7310 setDeductionArg(ArgResult.get());
7311 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7312 CanonicalConverted =
7313 Context.getCanonicalTemplateArgument(SugaredConverted);
7314 return Arg;
7315 }
7316
7317 APValue PreNarrowingValue;
7319 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7320 false, PreNarrowingValue);
7321 if (ArgResult.isInvalid())
7322 return ExprError();
7323 setDeductionArg(ArgResult.get());
7324
7325 if (Value.isLValue()) {
7326 APValue::LValueBase Base = Value.getLValueBase();
7327 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7328 // For a non-type template-parameter of pointer or reference type,
7329 // the value of the constant expression shall not refer to
7330 assert(ParamType->isPointerOrReferenceType() ||
7331 ParamType->isNullPtrType());
7332 // -- a temporary object
7333 // -- a string literal
7334 // -- the result of a typeid expression, or
7335 // -- a predefined __func__ variable
7336 if (Base &&
7337 (!VD ||
7339 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7340 << Arg->getSourceRange();
7341 return ExprError();
7342 }
7343
7344 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7345 VD->getType()->isArrayType() &&
7346 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7347 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7348 if (ArgPE) {
7349 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7350 CanonicalConverted =
7351 Context.getCanonicalTemplateArgument(SugaredConverted);
7352 } else {
7353 SugaredConverted = TemplateArgument(VD, ParamType);
7354 CanonicalConverted =
7356 ParamType.getCanonicalType());
7357 }
7358 return Arg;
7359 }
7360
7361 // -- a subobject [until C++20]
7362 if (!getLangOpts().CPlusPlus20) {
7363 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7364 Value.isLValueOnePastTheEnd()) {
7365 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7366 << Value.getAsString(Context, ParamType);
7367 return ExprError();
7368 }
7369 assert((VD || !ParamType->isReferenceType()) &&
7370 "null reference should not be a constant expression");
7371 assert((!VD || !ParamType->isNullPtrType()) &&
7372 "non-null value of type nullptr_t?");
7373 }
7374 }
7375
7376 if (Value.isAddrLabelDiff())
7377 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7378
7379 if (ArgPE) {
7380 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7381 CanonicalConverted =
7382 Context.getCanonicalTemplateArgument(SugaredConverted);
7383 } else {
7384 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7385 CanonicalConverted =
7387 }
7388 return Arg;
7389 }
7390
7391 // C++ [temp.arg.nontype]p5:
7392 // The following conversions are performed on each expression used
7393 // as a non-type template-argument. If a non-type
7394 // template-argument cannot be converted to the type of the
7395 // corresponding template-parameter then the program is
7396 // ill-formed.
7397 if (ParamType->isIntegralOrEnumerationType()) {
7398 // C++11:
7399 // -- for a non-type template-parameter of integral or
7400 // enumeration type, conversions permitted in a converted
7401 // constant expression are applied.
7402 //
7403 // C++98:
7404 // -- for a non-type template-parameter of integral or
7405 // enumeration type, integral promotions (4.5) and integral
7406 // conversions (4.7) are applied.
7407
7408 if (getLangOpts().CPlusPlus11) {
7409 // C++ [temp.arg.nontype]p1:
7410 // A template-argument for a non-type, non-template template-parameter
7411 // shall be one of:
7412 //
7413 // -- for a non-type template-parameter of integral or enumeration
7414 // type, a converted constant expression of the type of the
7415 // template-parameter; or
7416 llvm::APSInt Value;
7418 DeductionArg, ParamType, Value, CCEKind::TemplateArg);
7419 if (ArgResult.isInvalid())
7420 return ExprError();
7421 setDeductionArg(ArgResult.get());
7422
7423 // We can't check arbitrary value-dependent arguments.
7424 if (DeductionArg->isValueDependent()) {
7425 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7426 CanonicalConverted =
7427 Context.getCanonicalTemplateArgument(SugaredConverted);
7428 return Arg;
7429 }
7430
7431 // Widen the argument value to sizeof(parameter type). This is almost
7432 // always a no-op, except when the parameter type is bool. In
7433 // that case, this may extend the argument from 1 bit to 8 bits.
7434 QualType IntegerType = ParamType;
7435 if (const auto *ED = IntegerType->getAsEnumDecl())
7436 IntegerType = ED->getIntegerType();
7437 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7438 ? Context.getIntWidth(IntegerType)
7439 : Context.getTypeSize(IntegerType));
7440
7441 if (ArgPE) {
7442 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7443 CanonicalConverted =
7444 Context.getCanonicalTemplateArgument(SugaredConverted);
7445 } else {
7446 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7447 CanonicalConverted = TemplateArgument(
7448 Context, Value, Context.getCanonicalType(ParamType));
7449 }
7450 return Arg;
7451 }
7452
7453 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7454 if (ArgResult.isInvalid())
7455 return ExprError();
7456 DeductionArg = ArgResult.get();
7457
7458 QualType ArgType = DeductionArg->getType();
7459
7460 // C++ [temp.arg.nontype]p1:
7461 // A template-argument for a non-type, non-template
7462 // template-parameter shall be one of:
7463 //
7464 // -- an integral constant-expression of integral or enumeration
7465 // type; or
7466 // -- the name of a non-type template-parameter; or
7467 llvm::APSInt Value;
7468 if (!ArgType->isIntegralOrEnumerationType()) {
7469 Diag(StartLoc, diag::err_template_arg_not_integral_or_enumeral)
7470 << ArgType << DeductionArg->getSourceRange();
7472 return ExprError();
7473 } else if (!DeductionArg->isValueDependent()) {
7474 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7475 QualType T;
7476
7477 public:
7478 TmplArgICEDiagnoser(QualType T) : T(T) { }
7479
7480 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7481 SourceLocation Loc) override {
7482 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7483 }
7484 } Diagnoser(ArgType);
7485
7486 DeductionArg =
7487 VerifyIntegerConstantExpression(DeductionArg, &Value, Diagnoser)
7488 .get();
7489 if (!DeductionArg)
7490 return ExprError();
7491 }
7492
7493 // From here on out, all we care about is the unqualified form
7494 // of the argument type.
7495 ArgType = ArgType.getUnqualifiedType();
7496
7497 // Try to convert the argument to the parameter's type.
7498 if (Context.hasSameType(ParamType, ArgType)) {
7499 // Okay: no conversion necessary
7500 } else if (ParamType->isBooleanType()) {
7501 // This is an integral-to-boolean conversion.
7502 DeductionArg =
7503 ImpCastExprToType(DeductionArg, ParamType, CK_IntegralToBoolean)
7504 .get();
7505 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7506 !ParamType->isEnumeralType()) {
7507 // This is an integral promotion or conversion.
7508 DeductionArg =
7509 ImpCastExprToType(DeductionArg, ParamType, CK_IntegralCast).get();
7510 } else {
7511 // We can't perform this conversion.
7512 Diag(StartLoc, diag::err_template_arg_not_convertible)
7513 << DeductionArg->getType() << ParamType
7514 << DeductionArg->getSourceRange();
7516 return ExprError();
7517 }
7518 setDeductionArg(DeductionArg);
7519
7520 // Add the value of this argument to the list of converted
7521 // arguments. We use the bitwidth and signedness of the template
7522 // parameter.
7523 if (DeductionArg->isValueDependent()) {
7524 // The argument is value-dependent. Create a new
7525 // TemplateArgument with the converted expression.
7526 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7527 CanonicalConverted =
7528 Context.getCanonicalTemplateArgument(SugaredConverted);
7529 return Arg;
7530 }
7531
7532 QualType IntegerType = ParamType;
7533 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7534 IntegerType = ED->getIntegerType();
7535 }
7536
7537 if (ParamType->isBooleanType()) {
7538 // Value must be zero or one.
7539 Value = Value != 0;
7540 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7541 if (Value.getBitWidth() != AllowedBits)
7542 Value = Value.extOrTrunc(AllowedBits);
7543 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7544 } else {
7545 llvm::APSInt OldValue = Value;
7546
7547 // Coerce the template argument's value to the value it will have
7548 // based on the template parameter's type.
7549 unsigned AllowedBits = IntegerType->isBitIntType()
7550 ? Context.getIntWidth(IntegerType)
7551 : Context.getTypeSize(IntegerType);
7552 if (Value.getBitWidth() != AllowedBits)
7553 Value = Value.extOrTrunc(AllowedBits);
7554 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7555
7556 // Complain if an unsigned parameter received a negative value.
7557 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7558 (OldValue.isSigned() && OldValue.isNegative())) {
7559 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7560 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7561 << Arg->getSourceRange();
7563 }
7564
7565 // Complain if we overflowed the template parameter's type.
7566 unsigned RequiredBits;
7567 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7568 RequiredBits = OldValue.getActiveBits();
7569 else if (OldValue.isUnsigned())
7570 RequiredBits = OldValue.getActiveBits() + 1;
7571 else
7572 RequiredBits = OldValue.getSignificantBits();
7573 if (RequiredBits > AllowedBits) {
7574 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7575 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7576 << Arg->getSourceRange();
7578 }
7579 }
7580
7581 if (ArgPE) {
7582 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7583 CanonicalConverted =
7584 Context.getCanonicalTemplateArgument(SugaredConverted);
7585 } else {
7586 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7587 SugaredConverted = TemplateArgument(Context, Value, T);
7588 CanonicalConverted =
7589 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7590 }
7591 return Arg;
7592 }
7593
7594 QualType ArgType = DeductionArg->getType();
7595 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7596
7597 // Handle pointer-to-function, reference-to-function, and
7598 // pointer-to-member-function all in (roughly) the same way.
7599 if (// -- For a non-type template-parameter of type pointer to
7600 // function, only the function-to-pointer conversion (4.3) is
7601 // applied. If the template-argument represents a set of
7602 // overloaded functions (or a pointer to such), the matching
7603 // function is selected from the set (13.4).
7604 (ParamType->isPointerType() &&
7605 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7606 // -- For a non-type template-parameter of type reference to
7607 // function, no conversions apply. If the template-argument
7608 // represents a set of overloaded functions, the matching
7609 // function is selected from the set (13.4).
7610 (ParamType->isReferenceType() &&
7611 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7612 // -- For a non-type template-parameter of type pointer to
7613 // member function, no conversions apply. If the
7614 // template-argument represents a set of overloaded member
7615 // functions, the matching member function is selected from
7616 // the set (13.4).
7617 (ParamType->isMemberPointerType() &&
7618 ParamType->castAs<MemberPointerType>()->getPointeeType()
7619 ->isFunctionType())) {
7620
7621 if (DeductionArg->getType() == Context.OverloadTy) {
7622 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7623 true,
7624 FoundResult)) {
7625 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7626 return ExprError();
7627
7628 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7629 if (Res.isInvalid())
7630 return ExprError();
7631 DeductionArg = Res.get();
7632 ArgType = Arg->getType();
7633 } else
7634 return ExprError();
7635 }
7636 setDeductionArg(DeductionArg);
7637
7638 if (!ParamType->isMemberPointerType()) {
7640 *this, Param, ParamType, Arg, SugaredConverted,
7641 CanonicalConverted))
7642 return ExprError();
7643 return Arg;
7644 }
7645
7647 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7648 return ExprError();
7649 return Arg;
7650 }
7651
7652 setDeductionArg(DeductionArg);
7653
7654 if (ParamType->isPointerType()) {
7655 // -- for a non-type template-parameter of type pointer to
7656 // object, qualification conversions (4.4) and the
7657 // array-to-pointer conversion (4.2) are applied.
7658 // C++0x also allows a value of std::nullptr_t.
7659 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7660 "Only object pointers allowed here");
7661
7662 // FIXME: Deal with pack expansions here.
7664 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7665 return ExprError();
7666 return Arg;
7667 }
7668
7669 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7670 // -- For a non-type template-parameter of type reference to
7671 // object, no conversions apply. The type referred to by the
7672 // reference may be more cv-qualified than the (otherwise
7673 // identical) type of the template-argument. The
7674 // template-parameter is bound directly to the
7675 // template-argument, which must be an lvalue.
7676 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7677 "Only object references allowed here");
7678
7679 // FIXME: Deal with pack expansions here.
7680 if (Arg->getType() == Context.OverloadTy) {
7682 ParamRefType->getPointeeType(),
7683 true,
7684 FoundResult)) {
7685 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7686 return ExprError();
7687 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7688 if (Res.isInvalid())
7689 return ExprError();
7690 Arg = Res.get();
7691 ArgType = Arg->getType();
7692 } else
7693 return ExprError();
7694 }
7695
7697 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7698 return ExprError();
7699 return Arg;
7700 }
7701
7702 // Deal with parameters of type std::nullptr_t.
7703 if (ParamType->isNullPtrType()) {
7704 if (DeductionArg->isTypeDependent() || DeductionArg->isValueDependent()) {
7705 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7706 CanonicalConverted =
7707 Context.getCanonicalTemplateArgument(SugaredConverted);
7708 return Arg;
7709 }
7710
7711 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType,
7712 DeductionArg)) {
7713 case NPV_NotNullPointer:
7714 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7715 << DeductionArg->getType() << ParamType;
7717 return ExprError();
7718
7719 case NPV_Error:
7720 return ExprError();
7721
7722 case NPV_NullPointer:
7723 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7724 if (ArgPE) {
7725 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7726 CanonicalConverted =
7727 Context.getCanonicalTemplateArgument(SugaredConverted);
7728 } else {
7729 SugaredConverted = TemplateArgument(ParamType,
7730 /*isNullPtr=*/true);
7731 CanonicalConverted =
7732 TemplateArgument(Context.getCanonicalType(ParamType),
7733 /*isNullPtr=*/true);
7734 }
7735 return Arg;
7736 }
7737 }
7738
7739 // -- For a non-type template-parameter of type pointer to data
7740 // member, qualification conversions (4.4) are applied.
7741 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7742
7743 // FIXME: Deal with pack expansions here.
7745 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7746 return ExprError();
7747 return Arg;
7748}
7749
7753
7756 const TemplateArgumentLoc &Arg) {
7757 // C++0x [temp.arg.template]p1:
7758 // A template-argument for a template template-parameter shall be
7759 // the name of a class template or an alias template, expressed as an
7760 // id-expression. When the template-argument names a class template, only
7761 // primary class templates are considered when matching the
7762 // template template argument with the corresponding parameter;
7763 // partial specializations are not considered even if their
7764 // parameter lists match that of the template template parameter.
7765 //
7766
7768 unsigned DiagFoundKind = 0;
7769
7770 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7771 switch (TTP->templateParameterKind()) {
7773 DiagFoundKind = 3;
7774 break;
7776 DiagFoundKind = 2;
7777 break;
7778 default:
7779 DiagFoundKind = 1;
7780 break;
7781 }
7782 Kind = TTP->templateParameterKind();
7783 } else if (isa<ConceptDecl>(Template)) {
7785 DiagFoundKind = 3;
7786 } else if (isa<FunctionTemplateDecl>(Template)) {
7788 DiagFoundKind = 0;
7789 } else if (isa<VarTemplateDecl>(Template)) {
7791 DiagFoundKind = 2;
7792 } else if (isa<ClassTemplateDecl>(Template) ||
7796 DiagFoundKind = 1;
7797 } else {
7798 assert(false && "Unexpected Decl");
7799 }
7800
7801 if (Kind == Param->templateParameterKind()) {
7802 return true;
7803 }
7804
7805 unsigned DiagKind = 0;
7806 switch (Param->templateParameterKind()) {
7808 DiagKind = 2;
7809 break;
7811 DiagKind = 1;
7812 break;
7813 default:
7814 DiagKind = 0;
7815 break;
7816 }
7817 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7818 << DiagKind;
7819 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7820 << DiagFoundKind << Template;
7821 return false;
7822}
7823
7824/// Check a template argument against its corresponding
7825/// template template parameter.
7826///
7827/// This routine implements the semantics of C++ [temp.arg.template].
7828/// It returns true if an error occurred, and false otherwise.
7830 TemplateParameterList *Params,
7832 bool PartialOrdering,
7833 bool *StrictPackMatch) {
7835 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7836 if (!Template) {
7837 // Any dependent template name is fine.
7838 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7839 return false;
7840 }
7841
7842 if (Template->isInvalidDecl())
7843 return true;
7844
7846 return true;
7847 }
7848
7849 // C++1z [temp.arg.template]p3: (DR 150)
7850 // A template-argument matches a template template-parameter P when P
7851 // is at least as specialized as the template-argument A.
7853 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7854 PartialOrdering, StrictPackMatch))
7855 return true;
7856 // P2113
7857 // C++20[temp.func.order]p2
7858 // [...] If both deductions succeed, the partial ordering selects the
7859 // more constrained template (if one exists) as determined below.
7860 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7861 Params->getAssociatedConstraints(ParamsAC);
7862 // C++20[temp.arg.template]p3
7863 // [...] In this comparison, if P is unconstrained, the constraints on A
7864 // are not considered.
7865 if (ParamsAC.empty())
7866 return false;
7867
7868 Template->getAssociatedConstraints(TemplateAC);
7869
7870 bool IsParamAtLeastAsConstrained;
7871 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7872 IsParamAtLeastAsConstrained))
7873 return true;
7874 if (!IsParamAtLeastAsConstrained) {
7875 Diag(Arg.getLocation(),
7876 diag::err_template_template_parameter_not_at_least_as_constrained)
7877 << Template << Param << Arg.getSourceRange();
7878 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7879 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7881 TemplateAC);
7882 return true;
7883 }
7884 return false;
7885}
7886
7888 unsigned HereDiagID,
7889 unsigned ExternalDiagID) {
7890 if (Decl.getLocation().isValid())
7891 return S.Diag(Decl.getLocation(), HereDiagID);
7892
7893 SmallString<128> Str;
7894 llvm::raw_svector_ostream Out(Str);
7896 PP.TerseOutput = 1;
7897 Decl.print(Out, PP);
7898 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7899}
7900
7902 std::optional<SourceRange> ParamRange) {
7904 noteLocation(*this, Decl, diag::note_template_decl_here,
7905 diag::note_template_decl_external);
7906 if (ParamRange && ParamRange->isValid()) {
7907 assert(Decl.getLocation().isValid() &&
7908 "Parameter range has location when Decl does not");
7909 DB << *ParamRange;
7910 }
7911}
7912
7914 noteLocation(*this, Decl, diag::note_template_param_here,
7915 diag::note_template_param_external);
7916}
7917
7918/// Given a non-type template argument that refers to a
7919/// declaration and the type of its corresponding non-type template
7920/// parameter, produce an expression that properly refers to that
7921/// declaration.
7923 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7925 // C++ [temp.param]p8:
7926 //
7927 // A non-type template-parameter of type "array of T" or
7928 // "function returning T" is adjusted to be of type "pointer to
7929 // T" or "pointer to function returning T", respectively.
7930 if (ParamType->isArrayType())
7931 ParamType = Context.getArrayDecayedType(ParamType);
7932 else if (ParamType->isFunctionType())
7933 ParamType = Context.getPointerType(ParamType);
7934
7935 // For a NULL non-type template argument, return nullptr casted to the
7936 // parameter's type.
7937 if (Arg.getKind() == TemplateArgument::NullPtr) {
7938 return ImpCastExprToType(
7939 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7940 ParamType,
7941 ParamType->getAs<MemberPointerType>()
7942 ? CK_NullToMemberPointer
7943 : CK_NullToPointer);
7944 }
7945 assert(Arg.getKind() == TemplateArgument::Declaration &&
7946 "Only declaration template arguments permitted here");
7947
7948 ValueDecl *VD = Arg.getAsDecl();
7949
7950 CXXScopeSpec SS;
7951 if (ParamType->isMemberPointerType()) {
7952 // If this is a pointer to member, we need to use a qualified name to
7953 // form a suitable pointer-to-member constant.
7954 assert(VD->getDeclContext()->isRecord() &&
7955 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7957 CanQualType ClassType =
7958 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7959 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7960 SS.MakeTrivial(Context, Qualifier, Loc);
7961 }
7962
7964 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7965 if (RefExpr.isInvalid())
7966 return ExprError();
7967
7968 // For a pointer, the argument declaration is the pointee. Take its address.
7969 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7970 if (ParamType->isPointerType() && !ElemT.isNull() &&
7971 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7972 // Decay an array argument if we want a pointer to its first element.
7973 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7974 if (RefExpr.isInvalid())
7975 return ExprError();
7976 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7977 // For any other pointer, take the address (or form a pointer-to-member).
7978 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7979 if (RefExpr.isInvalid())
7980 return ExprError();
7981 } else if (ParamType->isRecordType()) {
7982 assert(isa<TemplateParamObjectDecl>(VD) &&
7983 "arg for class template param not a template parameter object");
7984 // No conversions apply in this case.
7985 return RefExpr;
7986 } else {
7987 assert(ParamType->isReferenceType() &&
7988 "unexpected type for decl template argument");
7989 if (NonTypeTemplateParmDecl *NTTP =
7990 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7991 QualType TemplateParamType = NTTP->getType();
7992 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7993 if (AT && AT->isDecltypeAuto()) {
7995 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7996 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7997 /*PackIndex=*/std::nullopt,
7998 /*RefParam=*/true, /*Final=*/true);
7999 }
8000 }
8001 }
8002
8003 // At this point we should have the right value category.
8004 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8005 "value kind mismatch for non-type template argument");
8006
8007 // The type of the template parameter can differ from the type of the
8008 // argument in various ways; convert it now if necessary.
8009 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8010 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8011 CastKind CK;
8012 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8013 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
8014 CK = CK_NoOp;
8015 } else if (ParamType->isVoidPointerType() &&
8016 RefExpr.get()->getType()->isPointerType()) {
8017 CK = CK_BitCast;
8018 } else {
8019 // FIXME: Pointers to members can need conversion derived-to-base or
8020 // base-to-derived conversions. We currently don't retain enough
8021 // information to convert properly (we need to track a cast path or
8022 // subobject number in the template argument).
8023 llvm_unreachable(
8024 "unexpected conversion required for non-type template argument");
8025 }
8026 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8027 RefExpr.get()->getValueKind());
8028 }
8029
8030 return RefExpr;
8031}
8032
8033/// Construct a new expression that refers to the given
8034/// integral template argument with the given source-location
8035/// information.
8036///
8037/// This routine takes care of the mapping from an integral template
8038/// argument (which may have any integral type) to the appropriate
8039/// literal value.
8041 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8042 assert(OrigT->isIntegralOrEnumerationType());
8043
8044 // If this is an enum type that we're instantiating, we need to use an integer
8045 // type the same size as the enumerator. We don't want to build an
8046 // IntegerLiteral with enum type. The integer type of an enum type can be of
8047 // any integral type with C++11 enum classes, make sure we create the right
8048 // type of literal for it.
8049 QualType T = OrigT;
8050 if (const auto *ED = OrigT->getAsEnumDecl())
8051 T = ED->getIntegerType();
8052
8053 Expr *E;
8054 if (T->isAnyCharacterType()) {
8056 if (T->isWideCharType())
8058 else if (T->isChar8Type() && S.getLangOpts().Char8)
8060 else if (T->isChar16Type())
8062 else if (T->isChar32Type())
8064 else
8066
8067 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8068 } else if (T->isBooleanType()) {
8069 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8070 } else {
8071 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8072 }
8073
8074 if (OrigT->isEnumeralType()) {
8075 // FIXME: This is a hack. We need a better way to handle substituted
8076 // non-type template parameters.
8077 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8078 nullptr, S.CurFPFeatureOverrides(),
8079 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8080 Loc, Loc);
8081 }
8082
8083 return E;
8084}
8085
8087 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8088 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8089 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8090 ILE->setType(T);
8091 return ILE;
8092 };
8093
8094 switch (Val.getKind()) {
8096 // This cannot occur in a template argument at all.
8097 case APValue::Array:
8098 case APValue::Struct:
8099 case APValue::Union:
8100 // These can only occur within a template parameter object, which is
8101 // represented as a TemplateArgument::Declaration.
8102 llvm_unreachable("unexpected template argument value");
8103
8104 case APValue::Int:
8106 Loc);
8107
8108 case APValue::Float:
8109 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8110 T, Loc);
8111
8114 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8115 Val.getFixedPoint().getScale());
8116
8117 case APValue::ComplexInt: {
8118 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8120 S, ElemT, Val.getComplexIntReal(), Loc),
8122 S, ElemT, Val.getComplexIntImag(), Loc)});
8123 }
8124
8125 case APValue::ComplexFloat: {
8126 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8127 return MakeInitList(
8129 ElemT, Loc),
8131 ElemT, Loc)});
8132 }
8133
8134 case APValue::Vector: {
8135 QualType ElemT = T->castAs<VectorType>()->getElementType();
8137 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8139 S, ElemT, Val.getVectorElt(I), Loc));
8140 return MakeInitList(Elts);
8141 }
8142
8143 case APValue::None:
8145 llvm_unreachable("Unexpected APValue kind.");
8146 case APValue::LValue:
8148 // There isn't necessarily a valid equivalent source-level syntax for
8149 // these; in particular, a naive lowering might violate access control.
8150 // So for now we lower to a ConstantExpr holding the value, wrapped around
8151 // an OpaqueValueExpr.
8152 // FIXME: We should have a better representation for this.
8154 if (T->isReferenceType()) {
8155 T = T->getPointeeType();
8156 VK = VK_LValue;
8157 }
8158 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8159 return ConstantExpr::Create(S.Context, OVE, Val);
8160 }
8161 llvm_unreachable("Unhandled APValue::ValueKind enum");
8162}
8163
8166 SourceLocation Loc) {
8167 switch (Arg.getKind()) {
8173 llvm_unreachable("not a non-type template argument");
8174
8176 return Arg.getAsExpr();
8177
8181 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8182
8185 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8186
8189 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8190 }
8191 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8192}
8193
8194/// Match two template parameters within template parameter lists.
8196 Sema &S, NamedDecl *New,
8197 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8198 const NamedDecl *OldInstFrom, bool Complain,
8200 // Check the actual kind (type, non-type, template).
8201 if (Old->getKind() != New->getKind()) {
8202 if (Complain) {
8203 unsigned NextDiag = diag::err_template_param_different_kind;
8204 if (TemplateArgLoc.isValid()) {
8205 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8206 NextDiag = diag::note_template_param_different_kind;
8207 }
8208 S.Diag(New->getLocation(), NextDiag)
8209 << (Kind != Sema::TPL_TemplateMatch);
8210 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8211 << (Kind != Sema::TPL_TemplateMatch);
8212 }
8213
8214 return false;
8215 }
8216
8217 // Check that both are parameter packs or neither are parameter packs.
8218 // However, if we are matching a template template argument to a
8219 // template template parameter, the template template parameter can have
8220 // a parameter pack where the template template argument does not.
8221 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8222 if (Complain) {
8223 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8224 if (TemplateArgLoc.isValid()) {
8225 S.Diag(TemplateArgLoc,
8226 diag::err_template_arg_template_params_mismatch);
8227 NextDiag = diag::note_template_parameter_pack_non_pack;
8228 }
8229
8230 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8232 : 2;
8233 S.Diag(New->getLocation(), NextDiag)
8234 << ParamKind << New->isParameterPack();
8235 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8236 << ParamKind << Old->isParameterPack();
8237 }
8238
8239 return false;
8240 }
8241 // For non-type template parameters, check the type of the parameter.
8242 if (NonTypeTemplateParmDecl *OldNTTP =
8243 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8245
8246 // If we are matching a template template argument to a template
8247 // template parameter and one of the non-type template parameter types
8248 // is dependent, then we must wait until template instantiation time
8249 // to actually compare the arguments.
8251 (!OldNTTP->getType()->isDependentType() &&
8252 !NewNTTP->getType()->isDependentType())) {
8253 // C++20 [temp.over.link]p6:
8254 // Two [non-type] template-parameters are equivalent [if] they have
8255 // equivalent types ignoring the use of type-constraints for
8256 // placeholder types
8257 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8258 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8259 if (!S.Context.hasSameType(OldType, NewType)) {
8260 if (Complain) {
8261 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8262 if (TemplateArgLoc.isValid()) {
8263 S.Diag(TemplateArgLoc,
8264 diag::err_template_arg_template_params_mismatch);
8265 NextDiag = diag::note_template_nontype_parm_different_type;
8266 }
8267 S.Diag(NewNTTP->getLocation(), NextDiag)
8268 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8269 S.Diag(OldNTTP->getLocation(),
8270 diag::note_template_nontype_parm_prev_declaration)
8271 << OldNTTP->getType();
8272 }
8273 return false;
8274 }
8275 }
8276 }
8277 // For template template parameters, check the template parameter types.
8278 // The template parameter lists of template template
8279 // parameters must agree.
8280 else if (TemplateTemplateParmDecl *OldTTP =
8281 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8283 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8284 return false;
8286 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8287 OldTTP->getTemplateParameters(), Complain,
8290 : Kind),
8291 TemplateArgLoc))
8292 return false;
8293 }
8294
8298 const Expr *NewC = nullptr, *OldC = nullptr;
8299
8301 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8302 NewC = TC->getImmediatelyDeclaredConstraint();
8303 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8304 OldC = TC->getImmediatelyDeclaredConstraint();
8305 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8306 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8307 ->getPlaceholderTypeConstraint())
8308 NewC = E;
8309 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8310 ->getPlaceholderTypeConstraint())
8311 OldC = E;
8312 } else
8313 llvm_unreachable("unexpected template parameter type");
8314
8315 auto Diagnose = [&] {
8316 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8317 diag::err_template_different_type_constraint);
8318 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8319 diag::note_template_prev_declaration) << /*declaration*/0;
8320 };
8321
8322 if (!NewC != !OldC) {
8323 if (Complain)
8324 Diagnose();
8325 return false;
8326 }
8327
8328 if (NewC) {
8329 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8330 NewC)) {
8331 if (Complain)
8332 Diagnose();
8333 return false;
8334 }
8335 }
8336 }
8337
8338 return true;
8339}
8340
8341/// Diagnose a known arity mismatch when comparing template argument
8342/// lists.
8343static
8348 SourceLocation TemplateArgLoc) {
8349 unsigned NextDiag = diag::err_template_param_list_different_arity;
8350 if (TemplateArgLoc.isValid()) {
8351 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8352 NextDiag = diag::note_template_param_list_different_arity;
8353 }
8354 S.Diag(New->getTemplateLoc(), NextDiag)
8355 << (New->size() > Old->size())
8356 << (Kind != Sema::TPL_TemplateMatch)
8357 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8358 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8359 << (Kind != Sema::TPL_TemplateMatch)
8360 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8361}
8362
8365 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8366 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8367 if (Old->size() != New->size()) {
8368 if (Complain)
8370 TemplateArgLoc);
8371
8372 return false;
8373 }
8374
8375 // C++0x [temp.arg.template]p3:
8376 // A template-argument matches a template template-parameter (call it P)
8377 // when each of the template parameters in the template-parameter-list of
8378 // the template-argument's corresponding class template or alias template
8379 // (call it A) matches the corresponding template parameter in the
8380 // template-parameter-list of P. [...]
8381 TemplateParameterList::iterator NewParm = New->begin();
8382 TemplateParameterList::iterator NewParmEnd = New->end();
8383 for (TemplateParameterList::iterator OldParm = Old->begin(),
8384 OldParmEnd = Old->end();
8385 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8386 if (NewParm == NewParmEnd) {
8387 if (Complain)
8389 TemplateArgLoc);
8390 return false;
8391 }
8392 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8393 OldInstFrom, Complain, Kind,
8394 TemplateArgLoc))
8395 return false;
8396 }
8397
8398 // Make sure we exhausted all of the arguments.
8399 if (NewParm != NewParmEnd) {
8400 if (Complain)
8402 TemplateArgLoc);
8403
8404 return false;
8405 }
8406
8407 if (Kind != TPL_TemplateParamsEquivalent) {
8408 const Expr *NewRC = New->getRequiresClause();
8409 const Expr *OldRC = Old->getRequiresClause();
8410
8411 auto Diagnose = [&] {
8412 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8413 diag::err_template_different_requires_clause);
8414 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8415 diag::note_template_prev_declaration) << /*declaration*/0;
8416 };
8417
8418 if (!NewRC != !OldRC) {
8419 if (Complain)
8420 Diagnose();
8421 return false;
8422 }
8423
8424 if (NewRC) {
8425 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8426 NewRC)) {
8427 if (Complain)
8428 Diagnose();
8429 return false;
8430 }
8431 }
8432 }
8433
8434 return true;
8435}
8436
8437bool
8439 if (!S)
8440 return false;
8441
8442 // Find the nearest enclosing declaration scope.
8443 S = S->getDeclParent();
8444
8445 // C++ [temp.pre]p6: [P2096]
8446 // A template, explicit specialization, or partial specialization shall not
8447 // have C linkage.
8448 DeclContext *Ctx = S->getEntity();
8449 if (Ctx && Ctx->isExternCContext()) {
8450 SourceRange Range =
8451 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8452 ? TemplateParams->getParam(0)->getSourceRange()
8453 : TemplateParams->getSourceRange();
8454 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8455 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8456 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8457 return true;
8458 }
8459 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8460
8461 // C++ [temp]p2:
8462 // A template-declaration can appear only as a namespace scope or
8463 // class scope declaration.
8464 // C++ [temp.expl.spec]p3:
8465 // An explicit specialization may be declared in any scope in which the
8466 // corresponding primary template may be defined.
8467 // C++ [temp.class.spec]p6: [P2096]
8468 // A partial specialization may be declared in any scope in which the
8469 // corresponding primary template may be defined.
8470 if (Ctx) {
8471 if (Ctx->isFileContext())
8472 return false;
8473 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8474 // C++ [temp.mem]p2:
8475 // A local class shall not have member templates.
8476 if (RD->isLocalClass())
8477 return Diag(TemplateParams->getTemplateLoc(),
8478 diag::err_template_inside_local_class)
8479 << TemplateParams->getSourceRange();
8480 else
8481 return false;
8482 }
8483 }
8484
8485 return Diag(TemplateParams->getTemplateLoc(),
8486 diag::err_template_outside_namespace_or_class_scope)
8487 << TemplateParams->getSourceRange();
8488}
8489
8490/// Determine what kind of template specialization the given declaration
8491/// is.
8493 if (!D)
8494 return TSK_Undeclared;
8495
8496 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8497 return Record->getTemplateSpecializationKind();
8498 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8499 return Function->getTemplateSpecializationKind();
8500 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8501 return Var->getTemplateSpecializationKind();
8502
8503 return TSK_Undeclared;
8504}
8505
8506/// Check whether a specialization is well-formed in the current
8507/// context.
8508///
8509/// This routine determines whether a template specialization can be declared
8510/// in the current context (C++ [temp.expl.spec]p2).
8511///
8512/// \param S the semantic analysis object for which this check is being
8513/// performed.
8514///
8515/// \param Specialized the entity being specialized or instantiated, which
8516/// may be a kind of template (class template, function template, etc.) or
8517/// a member of a class template (member function, static data member,
8518/// member class).
8519///
8520/// \param PrevDecl the previous declaration of this entity, if any.
8521///
8522/// \param Loc the location of the explicit specialization or instantiation of
8523/// this entity.
8524///
8525/// \param IsPartialSpecialization whether this is a partial specialization of
8526/// a class template.
8527///
8528/// \returns true if there was an error that we cannot recover from, false
8529/// otherwise.
8531 NamedDecl *Specialized,
8532 NamedDecl *PrevDecl,
8533 SourceLocation Loc,
8535 // Keep these "kind" numbers in sync with the %select statements in the
8536 // various diagnostics emitted by this routine.
8537 int EntityKind = 0;
8538 if (isa<ClassTemplateDecl>(Specialized))
8539 EntityKind = IsPartialSpecialization? 1 : 0;
8540 else if (isa<VarTemplateDecl>(Specialized))
8541 EntityKind = IsPartialSpecialization ? 3 : 2;
8542 else if (isa<FunctionTemplateDecl>(Specialized))
8543 EntityKind = 4;
8544 else if (isa<CXXMethodDecl>(Specialized))
8545 EntityKind = 5;
8546 else if (isa<VarDecl>(Specialized))
8547 EntityKind = 6;
8548 else if (isa<RecordDecl>(Specialized))
8549 EntityKind = 7;
8550 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8551 EntityKind = 8;
8552 else {
8553 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8554 << S.getLangOpts().CPlusPlus11;
8555 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8556 return true;
8557 }
8558
8559 // C++ [temp.expl.spec]p2:
8560 // An explicit specialization may be declared in any scope in which
8561 // the corresponding primary template may be defined.
8563 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8564 << Specialized;
8565 return true;
8566 }
8567
8568 // C++ [temp.class.spec]p6:
8569 // A class template partial specialization may be declared in any
8570 // scope in which the primary template may be defined.
8571 DeclContext *SpecializedContext =
8572 Specialized->getDeclContext()->getRedeclContext();
8574
8575 // Make sure that this redeclaration (or definition) occurs in the same
8576 // scope or an enclosing namespace.
8577 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8578 : DC->Equals(SpecializedContext))) {
8579 if (isa<TranslationUnitDecl>(SpecializedContext))
8580 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8581 << EntityKind << Specialized;
8582 else {
8583 auto *ND = cast<NamedDecl>(SpecializedContext);
8584 int Diag = diag::err_template_spec_redecl_out_of_scope;
8585 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8586 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8587 S.Diag(Loc, Diag) << EntityKind << Specialized
8588 << ND << isa<CXXRecordDecl>(ND);
8589 }
8590
8591 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8592
8593 // Don't allow specializing in the wrong class during error recovery.
8594 // Otherwise, things can go horribly wrong.
8595 if (DC->isRecord())
8596 return true;
8597 }
8598
8599 return false;
8600}
8601
8603 if (!E->isTypeDependent())
8604 return SourceLocation();
8605 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8606 Checker.TraverseStmt(E);
8607 if (Checker.MatchLoc.isInvalid())
8608 return E->getSourceRange();
8609 return Checker.MatchLoc;
8610}
8611
8612static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8613 if (!TL.getType()->isDependentType())
8614 return SourceLocation();
8615 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8616 Checker.TraverseTypeLoc(TL);
8617 if (Checker.MatchLoc.isInvalid())
8618 return TL.getSourceRange();
8619 return Checker.MatchLoc;
8620}
8621
8622/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8623/// that checks non-type template partial specialization arguments.
8625 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8626 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8627 for (unsigned I = 0; I != NumArgs; ++I) {
8628 if (Args[I].getKind() == TemplateArgument::Pack) {
8630 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8631 Args[I].pack_size(), IsDefaultArgument))
8632 return true;
8633
8634 continue;
8635 }
8636
8637 if (Args[I].getKind() != TemplateArgument::Expression)
8638 continue;
8639
8640 Expr *ArgExpr = Args[I].getAsExpr();
8641
8642 // We can have a pack expansion of any of the bullets below.
8643 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8644 ArgExpr = Expansion->getPattern();
8645
8646 // Strip off any implicit casts we added as part of type checking.
8647 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8648 ArgExpr = ICE->getSubExpr();
8649
8650 // C++ [temp.class.spec]p8:
8651 // A non-type argument is non-specialized if it is the name of a
8652 // non-type parameter. All other non-type arguments are
8653 // specialized.
8654 //
8655 // Below, we check the two conditions that only apply to
8656 // specialized non-type arguments, so skip any non-specialized
8657 // arguments.
8658 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8659 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8660 continue;
8661
8662 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8663 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8664 continue;
8665 }
8666
8667 // C++ [temp.class.spec]p9:
8668 // Within the argument list of a class template partial
8669 // specialization, the following restrictions apply:
8670 // -- A partially specialized non-type argument expression
8671 // shall not involve a template parameter of the partial
8672 // specialization except when the argument expression is a
8673 // simple identifier.
8674 // -- The type of a template parameter corresponding to a
8675 // specialized non-type argument shall not be dependent on a
8676 // parameter of the specialization.
8677 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8678 // We implement a compromise between the original rules and DR1315:
8679 // -- A specialized non-type template argument shall not be
8680 // type-dependent and the corresponding template parameter
8681 // shall have a non-dependent type.
8682 SourceRange ParamUseRange =
8683 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8684 if (ParamUseRange.isValid()) {
8685 if (IsDefaultArgument) {
8686 S.Diag(TemplateNameLoc,
8687 diag::err_dependent_non_type_arg_in_partial_spec);
8688 S.Diag(ParamUseRange.getBegin(),
8689 diag::note_dependent_non_type_default_arg_in_partial_spec)
8690 << ParamUseRange;
8691 } else {
8692 S.Diag(ParamUseRange.getBegin(),
8693 diag::err_dependent_non_type_arg_in_partial_spec)
8694 << ParamUseRange;
8695 }
8696 return true;
8697 }
8698
8699 ParamUseRange = findTemplateParameter(
8700 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8701 if (ParamUseRange.isValid()) {
8702 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8703 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8704 << Param->getType();
8706 return true;
8707 }
8708 }
8709
8710 return false;
8711}
8712
8714 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8715 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8716 // We have to be conservative when checking a template in a dependent
8717 // context.
8718 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8719 return false;
8720
8721 TemplateParameterList *TemplateParams =
8722 PrimaryTemplate->getTemplateParameters();
8723 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8725 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8726 if (!Param)
8727 continue;
8728
8729 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8730 Param, &TemplateArgs[I],
8731 1, I >= NumExplicit))
8732 return true;
8733 }
8734
8735 return false;
8736}
8737
8739 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8740 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8742 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8743 assert(TUK != TagUseKind::Reference && "References are not specializations");
8744
8745 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8746 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8747 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8748
8749 // Find the class template we're specializing
8750 TemplateName Name = TemplateId.Template.get();
8752 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8753
8754 if (!ClassTemplate) {
8755 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8756 << (Name.getAsTemplateDecl() &&
8758 return true;
8759 }
8760
8761 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8762 auto Message = DSA->getMessage();
8763 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8764 << ClassTemplate << !Message.empty() << Message;
8765 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8766 }
8767
8768 if (S->isTemplateParamScope())
8769 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8770
8771 DeclContext *DC = ClassTemplate->getDeclContext();
8772
8773 bool isMemberSpecialization = false;
8774 bool isPartialSpecialization = false;
8775
8776 if (SS.isSet()) {
8777 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8778 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8779 TemplateNameLoc, &TemplateId,
8780 /*IsMemberSpecialization=*/false))
8781 return true;
8782 }
8783
8784 // Check the validity of the template headers that introduce this
8785 // template.
8786 // FIXME: We probably shouldn't complain about these headers for
8787 // friend declarations.
8788 bool Invalid = false;
8789 TemplateParameterList *TemplateParams =
8791 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8792 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8793 if (Invalid)
8794 return true;
8795
8796 // Check that we can declare a template specialization here.
8797 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8798 return true;
8799
8800 if (TemplateParams && DC->isDependentContext()) {
8801 ContextRAII SavedContext(*this, DC);
8803 return true;
8804 }
8805
8806 if (TemplateParams && TemplateParams->size() > 0) {
8807 isPartialSpecialization = true;
8808
8809 if (TUK == TagUseKind::Friend) {
8810 Diag(KWLoc, diag::err_partial_specialization_friend)
8811 << SourceRange(LAngleLoc, RAngleLoc);
8812 return true;
8813 }
8814
8815 // C++ [temp.class.spec]p10:
8816 // The template parameter list of a specialization shall not
8817 // contain default template argument values.
8818 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8819 Decl *Param = TemplateParams->getParam(I);
8820 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8821 if (TTP->hasDefaultArgument()) {
8822 Diag(TTP->getDefaultArgumentLoc(),
8823 diag::err_default_arg_in_partial_spec);
8824 TTP->removeDefaultArgument();
8825 }
8826 } else if (NonTypeTemplateParmDecl *NTTP
8827 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8828 if (NTTP->hasDefaultArgument()) {
8829 Diag(NTTP->getDefaultArgumentLoc(),
8830 diag::err_default_arg_in_partial_spec)
8831 << NTTP->getDefaultArgument().getSourceRange();
8832 NTTP->removeDefaultArgument();
8833 }
8834 } else {
8836 if (TTP->hasDefaultArgument()) {
8838 diag::err_default_arg_in_partial_spec)
8840 TTP->removeDefaultArgument();
8841 }
8842 }
8843 }
8844 } else if (TemplateParams) {
8845 if (TUK == TagUseKind::Friend)
8846 Diag(KWLoc, diag::err_template_spec_friend)
8848 SourceRange(TemplateParams->getTemplateLoc(),
8849 TemplateParams->getRAngleLoc()))
8850 << SourceRange(LAngleLoc, RAngleLoc);
8851 } else {
8852 assert(TUK == TagUseKind::Friend &&
8853 "should have a 'template<>' for this decl");
8854 }
8855
8856 // Check that the specialization uses the same tag kind as the
8857 // original template.
8859 assert(Kind != TagTypeKind::Enum &&
8860 "Invalid enum tag in class template spec!");
8861 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8862 TUK == TagUseKind::Definition, KWLoc,
8863 ClassTemplate->getIdentifier())) {
8864 Diag(KWLoc, diag::err_use_with_wrong_tag)
8865 << ClassTemplate
8867 ClassTemplate->getTemplatedDecl()->getKindName());
8868 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8869 diag::note_previous_use);
8870 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8871 }
8872
8873 // Translate the parser's template argument list in our AST format.
8874 TemplateArgumentListInfo TemplateArgs =
8875 makeTemplateArgumentListInfo(*this, TemplateId);
8876
8877 // Check for unexpanded parameter packs in any of the template arguments.
8878 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8879 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8880 isPartialSpecialization
8883 return true;
8884
8885 // Check that the template argument list is well-formed for this
8886 // template.
8888 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8889 /*DefaultArgs=*/{},
8890 /*PartialTemplateArgs=*/false, CTAI,
8891 /*UpdateArgsWithConversions=*/true))
8892 return true;
8893
8894 // Find the class template (partial) specialization declaration that
8895 // corresponds to these arguments.
8896 if (isPartialSpecialization) {
8898 TemplateArgs.size(),
8899 CTAI.CanonicalConverted))
8900 return true;
8901
8902 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8903 // also do it during instantiation.
8904 if (!Name.isDependent() &&
8905 !TemplateSpecializationType::anyDependentTemplateArguments(
8906 TemplateArgs, CTAI.CanonicalConverted)) {
8907 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8908 << ClassTemplate->getDeclName();
8909 isPartialSpecialization = false;
8910 Invalid = true;
8911 }
8912 }
8913
8914 void *InsertPos = nullptr;
8915 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8916
8917 if (isPartialSpecialization)
8918 PrevDecl = ClassTemplate->findPartialSpecialization(
8919 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8920 else
8921 PrevDecl =
8922 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8923
8925
8926 // Check whether we can declare a class template specialization in
8927 // the current scope.
8928 if (TUK != TagUseKind::Friend &&
8930 TemplateNameLoc,
8931 isPartialSpecialization))
8932 return true;
8933
8934 if (!isPartialSpecialization) {
8935 // Create a new class template specialization declaration node for
8936 // this explicit specialization or friend declaration.
8938 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8939 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8940 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8942 if (TemplateParameterLists.size() > 0) {
8943 Specialization->setTemplateParameterListsInfo(Context,
8944 TemplateParameterLists);
8945 }
8946
8947 if (!PrevDecl)
8948 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8949 } else {
8951 Context.getCanonicalTemplateSpecializationType(
8952 TemplateName(ClassTemplate->getCanonicalDecl()),
8953 CTAI.CanonicalConverted));
8954 if (Context.hasSameType(
8955 CanonType,
8956 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8957 (!Context.getLangOpts().CPlusPlus20 ||
8958 !TemplateParams->hasAssociatedConstraints())) {
8959 // C++ [temp.class.spec]p9b3:
8960 //
8961 // -- The argument list of the specialization shall not be identical
8962 // to the implicit argument list of the primary template.
8963 //
8964 // This rule has since been removed, because it's redundant given DR1495,
8965 // but we keep it because it produces better diagnostics and recovery.
8966 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8967 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8968 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8969 return CheckClassTemplate(
8970 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8971 TemplateNameLoc, Attr, TemplateParams, AS_none,
8972 /*ModulePrivateLoc=*/SourceLocation(),
8973 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8974 TemplateParameterLists.data());
8975 }
8976
8977 // Create a new class template partial specialization declaration node.
8979 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8982 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8983 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8984 Partial->setTemplateArgsAsWritten(TemplateArgs);
8985 SetNestedNameSpecifier(*this, Partial, SS);
8986 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8988 Context, TemplateParameterLists.drop_back(1));
8989 }
8990
8991 if (!PrevPartial)
8992 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8993 Specialization = Partial;
8994
8995 // If we are providing an explicit specialization of a member class
8996 // template specialization, make a note of that.
8997 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8998 PrevPartial->setMemberSpecialization();
8999
9001 }
9002
9003 // C++ [temp.expl.spec]p6:
9004 // If a template, a member template or the member of a class template is
9005 // explicitly specialized then that specialization shall be declared
9006 // before the first use of that specialization that would cause an implicit
9007 // instantiation to take place, in every translation unit in which such a
9008 // use occurs; no diagnostic is required.
9009 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9010 bool Okay = false;
9011 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9012 // Is there any previous explicit specialization declaration?
9014 Okay = true;
9015 break;
9016 }
9017 }
9018
9019 if (!Okay) {
9020 SourceRange Range(TemplateNameLoc, RAngleLoc);
9021 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9022 << Context.getCanonicalTagType(Specialization) << Range;
9023
9024 Diag(PrevDecl->getPointOfInstantiation(),
9025 diag::note_instantiation_required_here)
9026 << (PrevDecl->getTemplateSpecializationKind()
9028 return true;
9029 }
9030 }
9031
9032 // If this is not a friend, note that this is an explicit specialization.
9033 if (TUK != TagUseKind::Friend)
9034 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9035
9036 // Check that this isn't a redefinition of this specialization.
9037 if (TUK == TagUseKind::Definition) {
9038 RecordDecl *Def = Specialization->getDefinition();
9039 NamedDecl *Hidden = nullptr;
9040 bool HiddenDefVisible = false;
9041 if (Def && SkipBody &&
9042 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9043 SkipBody->ShouldSkip = true;
9044 SkipBody->Previous = Def;
9045 if (!HiddenDefVisible && Hidden)
9047 } else if (Def) {
9048 SourceRange Range(TemplateNameLoc, RAngleLoc);
9049 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9050 Diag(Def->getLocation(), diag::note_previous_definition);
9051 Specialization->setInvalidDecl();
9052 return true;
9053 }
9054 }
9055
9058
9059 // Add alignment attributes if necessary; these attributes are checked when
9060 // the ASTContext lays out the structure.
9061 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9062 if (LangOpts.HLSL)
9063 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9066 }
9067
9068 if (ModulePrivateLoc.isValid())
9069 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9070 << (isPartialSpecialization? 1 : 0)
9071 << FixItHint::CreateRemoval(ModulePrivateLoc);
9072
9073 // C++ [temp.expl.spec]p9:
9074 // A template explicit specialization is in the scope of the
9075 // namespace in which the template was defined.
9076 //
9077 // We actually implement this paragraph where we set the semantic
9078 // context (in the creation of the ClassTemplateSpecializationDecl),
9079 // but we also maintain the lexical context where the actual
9080 // definition occurs.
9081 Specialization->setLexicalDeclContext(CurContext);
9082
9083 // We may be starting the definition of this specialization.
9084 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9085 Specialization->startDefinition();
9086
9087 if (TUK == TagUseKind::Friend) {
9088 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9089 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9090 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9092 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9093 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9094
9095 // Build the fully-sugared type for this class template
9096 // specialization as the user wrote in the specialization
9097 // itself. This means that we'll pretty-print the type retrieved
9098 // from the specialization's declaration the way that the user
9099 // actually wrote the specialization, rather than formatting the
9100 // name based on the "canonical" representation used to store the
9101 // template arguments in the specialization.
9103 TemplateNameLoc,
9104 WrittenTy,
9105 /*FIXME:*/KWLoc);
9106 Friend->setAccess(AS_public);
9107 CurContext->addDecl(Friend);
9108 } else {
9109 // Add the specialization into its lexical context, so that it can
9110 // be seen when iterating through the list of declarations in that
9111 // context. However, specializations are not found by name lookup.
9112 CurContext->addDecl(Specialization);
9113 }
9114
9115 if (SkipBody && SkipBody->ShouldSkip)
9116 return SkipBody->Previous;
9117
9118 Specialization->setInvalidDecl(Invalid);
9120 return Specialization;
9121}
9122
9124 MultiTemplateParamsArg TemplateParameterLists,
9125 Declarator &D) {
9126 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9127 ActOnDocumentableDecl(NewDecl);
9128 return NewDecl;
9129}
9130
9132 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9133 const IdentifierInfo *Name, SourceLocation NameLoc) {
9134 DeclContext *DC = CurContext;
9135
9136 if (!DC->getRedeclContext()->isFileContext()) {
9137 Diag(NameLoc,
9138 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9139 return nullptr;
9140 }
9141
9142 if (TemplateParameterLists.size() > 1) {
9143 Diag(NameLoc, diag::err_concept_extra_headers);
9144 return nullptr;
9145 }
9146
9147 TemplateParameterList *Params = TemplateParameterLists.front();
9148
9149 if (Params->size() == 0) {
9150 Diag(NameLoc, diag::err_concept_no_parameters);
9151 return nullptr;
9152 }
9153
9154 // Ensure that the parameter pack, if present, is the last parameter in the
9155 // template.
9156 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9157 ParamEnd = Params->end();
9158 ParamIt != ParamEnd; ++ParamIt) {
9159 Decl const *Param = *ParamIt;
9160 if (Param->isParameterPack()) {
9161 if (++ParamIt == ParamEnd)
9162 break;
9163 Diag(Param->getLocation(),
9164 diag::err_template_param_pack_must_be_last_template_parameter);
9165 return nullptr;
9166 }
9167 }
9168
9169 ConceptDecl *NewDecl =
9170 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9171
9172 if (NewDecl->hasAssociatedConstraints()) {
9173 // C++2a [temp.concept]p4:
9174 // A concept shall not have associated constraints.
9175 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9176 NewDecl->setInvalidDecl();
9177 }
9178
9179 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9180 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9182 LookupName(Previous, S);
9183 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9184 /*AllowInlineNamespace*/ false);
9185
9186 // We cannot properly handle redeclarations until we parse the constraint
9187 // expression, so only inject the name if we are sure we are not redeclaring a
9188 // symbol
9189 if (Previous.empty())
9190 PushOnScopeChains(NewDecl, S, true);
9191
9192 return NewDecl;
9193}
9194
9196 bool Found = false;
9198 while (F.hasNext()) {
9199 NamedDecl *D = F.next();
9200 if (D == C) {
9201 F.erase();
9202 Found = true;
9203 break;
9204 }
9205 }
9206 F.done();
9207 return Found;
9208}
9209
9212 Expr *ConstraintExpr,
9213 const ParsedAttributesView &Attrs) {
9214 assert(!C->hasDefinition() && "Concept already defined");
9215 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9216 C->setInvalidDecl();
9217 return nullptr;
9218 }
9219 C->setDefinition(ConstraintExpr);
9220 ProcessDeclAttributeList(S, C, Attrs);
9221
9222 // Check for conflicting previous declaration.
9223 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9224 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9226 LookupName(Previous, S);
9227 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9228 /*AllowInlineNamespace*/ false);
9229 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9230 bool AddToScope = true;
9231 CheckConceptRedefinition(C, Previous, AddToScope);
9232
9234 if (!WasAlreadyAdded && AddToScope)
9235 PushOnScopeChains(C, S);
9236
9237 return C;
9238}
9239
9241 LookupResult &Previous, bool &AddToScope) {
9242 AddToScope = true;
9243
9244 if (Previous.empty())
9245 return;
9246
9247 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9248 if (!OldConcept) {
9249 auto *Old = Previous.getRepresentativeDecl();
9250 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9251 << NewDecl->getDeclName();
9252 notePreviousDefinition(Old, NewDecl->getLocation());
9253 AddToScope = false;
9254 return;
9255 }
9256 // Check if we can merge with a concept declaration.
9257 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9258 if (!IsSame) {
9259 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9260 << NewDecl->getDeclName();
9261 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9262 AddToScope = false;
9263 return;
9264 }
9265 if (hasReachableDefinition(OldConcept) &&
9266 IsRedefinitionInModule(NewDecl, OldConcept)) {
9267 Diag(NewDecl->getLocation(), diag::err_redefinition)
9268 << NewDecl->getDeclName();
9269 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9270 AddToScope = false;
9271 return;
9272 }
9273 if (!Previous.isSingleResult()) {
9274 // FIXME: we should produce an error in case of ambig and failed lookups.
9275 // Other decls (e.g. namespaces) also have this shortcoming.
9276 return;
9277 }
9278 // We unwrap canonical decl late to check for module visibility.
9279 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9280}
9281
9283 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9284 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9285 Diag(Loc, diag::err_recursive_concept) << CE;
9286 Diag(CE->getLocation(), diag::note_declared_at);
9287 return true;
9288 }
9289 // Concept template parameters don't have a definition and can't
9290 // be defined recursively.
9291 return false;
9292}
9293
9294/// \brief Strips various properties off an implicit instantiation
9295/// that has just been explicitly specialized.
9296static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9297 if (MinGW || (isa<FunctionDecl>(D) &&
9298 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9299 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9300
9301 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9302 FD->setInlineSpecified(false);
9303}
9304
9305/// Compute the diagnostic location for an explicit instantiation
9306// declaration or definition.
9308 NamedDecl* D, SourceLocation PointOfInstantiation) {
9309 // Explicit instantiations following a specialization have no effect and
9310 // hence no PointOfInstantiation. In that case, walk decl backwards
9311 // until a valid name loc is found.
9312 SourceLocation PrevDiagLoc = PointOfInstantiation;
9313 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9314 Prev = Prev->getPreviousDecl()) {
9315 PrevDiagLoc = Prev->getLocation();
9316 }
9317 assert(PrevDiagLoc.isValid() &&
9318 "Explicit instantiation without point of instantiation?");
9319 return PrevDiagLoc;
9320}
9321
9322bool
9325 NamedDecl *PrevDecl,
9327 SourceLocation PrevPointOfInstantiation,
9328 bool &HasNoEffect) {
9329 HasNoEffect = false;
9330
9331 switch (NewTSK) {
9332 case TSK_Undeclared:
9334 assert(
9335 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9336 "previous declaration must be implicit!");
9337 return false;
9338
9340 switch (PrevTSK) {
9341 case TSK_Undeclared:
9343 // Okay, we're just specializing something that is either already
9344 // explicitly specialized or has merely been mentioned without any
9345 // instantiation.
9346 return false;
9347
9349 if (PrevPointOfInstantiation.isInvalid()) {
9350 // The declaration itself has not actually been instantiated, so it is
9351 // still okay to specialize it.
9353 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9354 return false;
9355 }
9356 // Fall through
9357 [[fallthrough]];
9358
9361 assert((PrevTSK == TSK_ImplicitInstantiation ||
9362 PrevPointOfInstantiation.isValid()) &&
9363 "Explicit instantiation without point of instantiation?");
9364
9365 // C++ [temp.expl.spec]p6:
9366 // If a template, a member template or the member of a class template
9367 // is explicitly specialized then that specialization shall be declared
9368 // before the first use of that specialization that would cause an
9369 // implicit instantiation to take place, in every translation unit in
9370 // which such a use occurs; no diagnostic is required.
9371 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9372 // Is there any previous explicit specialization declaration?
9374 return false;
9375 }
9376
9377 Diag(NewLoc, diag::err_specialization_after_instantiation)
9378 << PrevDecl;
9379 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9380 << (PrevTSK != TSK_ImplicitInstantiation);
9381
9382 return true;
9383 }
9384 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9385
9387 switch (PrevTSK) {
9389 // This explicit instantiation declaration is redundant (that's okay).
9390 HasNoEffect = true;
9391 return false;
9392
9393 case TSK_Undeclared:
9395 // We're explicitly instantiating something that may have already been
9396 // implicitly instantiated; that's fine.
9397 return false;
9398
9400 // C++0x [temp.explicit]p4:
9401 // For a given set of template parameters, if an explicit instantiation
9402 // of a template appears after a declaration of an explicit
9403 // specialization for that template, the explicit instantiation has no
9404 // effect.
9405 HasNoEffect = true;
9406 return false;
9407
9409 // C++0x [temp.explicit]p10:
9410 // If an entity is the subject of both an explicit instantiation
9411 // declaration and an explicit instantiation definition in the same
9412 // translation unit, the definition shall follow the declaration.
9413 Diag(NewLoc,
9414 diag::err_explicit_instantiation_declaration_after_definition);
9415
9416 // Explicit instantiations following a specialization have no effect and
9417 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9418 // until a valid name loc is found.
9419 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9420 diag::note_explicit_instantiation_definition_here);
9421 HasNoEffect = true;
9422 return false;
9423 }
9424 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9425
9427 switch (PrevTSK) {
9428 case TSK_Undeclared:
9430 // We're explicitly instantiating something that may have already been
9431 // implicitly instantiated; that's fine.
9432 return false;
9433
9435 // C++ DR 259, C++0x [temp.explicit]p4:
9436 // For a given set of template parameters, if an explicit
9437 // instantiation of a template appears after a declaration of
9438 // an explicit specialization for that template, the explicit
9439 // instantiation has no effect.
9440 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9441 << PrevDecl;
9442 Diag(PrevDecl->getLocation(),
9443 diag::note_previous_template_specialization);
9444 HasNoEffect = true;
9445 return false;
9446
9448 // We're explicitly instantiating a definition for something for which we
9449 // were previously asked to suppress instantiations. That's fine.
9450
9451 // C++0x [temp.explicit]p4:
9452 // For a given set of template parameters, if an explicit instantiation
9453 // of a template appears after a declaration of an explicit
9454 // specialization for that template, the explicit instantiation has no
9455 // effect.
9456 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9457 // Is there any previous explicit specialization declaration?
9459 HasNoEffect = true;
9460 break;
9461 }
9462 }
9463
9464 return false;
9465
9467 // C++0x [temp.spec]p5:
9468 // For a given template and a given set of template-arguments,
9469 // - an explicit instantiation definition shall appear at most once
9470 // in a program,
9471
9472 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9473 Diag(NewLoc, (getLangOpts().MSVCCompat)
9474 ? diag::ext_explicit_instantiation_duplicate
9475 : diag::err_explicit_instantiation_duplicate)
9476 << PrevDecl;
9477 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9478 diag::note_previous_explicit_instantiation);
9479 HasNoEffect = true;
9480 return false;
9481 }
9482 }
9483
9484 llvm_unreachable("Missing specialization/instantiation case?");
9485}
9486
9488 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9490 // Remove anything from Previous that isn't a function template in
9491 // the correct context.
9492 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9493 LookupResult::Filter F = Previous.makeFilter();
9494 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9495 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9496 while (F.hasNext()) {
9497 NamedDecl *D = F.next()->getUnderlyingDecl();
9498 if (!isa<FunctionTemplateDecl>(D)) {
9499 F.erase();
9500 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9501 continue;
9502 }
9503
9504 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9506 F.erase();
9507 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9508 continue;
9509 }
9510 }
9511 F.done();
9512
9513 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9514 if (Previous.empty()) {
9515 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9516 << IsFriend;
9517 for (auto &P : DiscardedCandidates)
9518 Diag(P.second->getLocation(),
9519 diag::note_dependent_function_template_spec_discard_reason)
9520 << P.first << IsFriend;
9521 return true;
9522 }
9523
9525 ExplicitTemplateArgs);
9526 return false;
9527}
9528
9530 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9531 LookupResult &Previous, bool QualifiedFriend) {
9532 // The set of function template specializations that could match this
9533 // explicit function template specialization.
9534 UnresolvedSet<8> Candidates;
9535 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9536 /*ForTakingAddress=*/false);
9537
9538 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9539 ConvertedTemplateArgs;
9540
9541 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9542 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9543 I != E; ++I) {
9544 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9545 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9546 // Only consider templates found within the same semantic lookup scope as
9547 // FD.
9548 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9550 continue;
9551
9552 QualType FT = FD->getType();
9553 // C++11 [dcl.constexpr]p8:
9554 // A constexpr specifier for a non-static member function that is not
9555 // a constructor declares that member function to be const.
9556 //
9557 // When matching a constexpr member function template specialization
9558 // against the primary template, we don't yet know whether the
9559 // specialization has an implicit 'const' (because we don't know whether
9560 // it will be a static member function until we know which template it
9561 // specializes). This rule was removed in C++14.
9562 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9563 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9565 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9566 if (OldMD && OldMD->isConst()) {
9567 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9569 EPI.TypeQuals.addConst();
9570 FT = Context.getFunctionType(FPT->getReturnType(),
9571 FPT->getParamTypes(), EPI);
9572 }
9573 }
9574
9576 if (ExplicitTemplateArgs)
9577 Args = *ExplicitTemplateArgs;
9578
9579 // C++ [temp.expl.spec]p11:
9580 // A trailing template-argument can be left unspecified in the
9581 // template-id naming an explicit function template specialization
9582 // provided it can be deduced from the function argument type.
9583 // Perform template argument deduction to determine whether we may be
9584 // specializing this template.
9585 // FIXME: It is somewhat wasteful to build
9586 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9587 FunctionDecl *Specialization = nullptr;
9589 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9590 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9592 // Template argument deduction failed; record why it failed, so
9593 // that we can provide nifty diagnostics.
9594 FailedCandidates.addCandidate().set(
9595 I.getPair(), FunTmpl->getTemplatedDecl(),
9596 MakeDeductionFailureInfo(Context, TDK, Info));
9597 (void)TDK;
9598 continue;
9599 }
9600
9601 // Target attributes are part of the cuda function signature, so
9602 // the deduced template's cuda target must match that of the
9603 // specialization. Given that C++ template deduction does not
9604 // take target attributes into account, we reject candidates
9605 // here that have a different target.
9606 if (LangOpts.CUDA &&
9607 CUDA().IdentifyTarget(Specialization,
9608 /* IgnoreImplicitHDAttr = */ true) !=
9609 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9610 FailedCandidates.addCandidate().set(
9611 I.getPair(), FunTmpl->getTemplatedDecl(),
9614 continue;
9615 }
9616
9617 // Record this candidate.
9618 if (ExplicitTemplateArgs)
9619 ConvertedTemplateArgs[Specialization] = std::move(Args);
9620 Candidates.addDecl(Specialization, I.getAccess());
9621 }
9622 }
9623
9624 // For a qualified friend declaration (with no explicit marker to indicate
9625 // that a template specialization was intended), note all (template and
9626 // non-template) candidates.
9627 if (QualifiedFriend && Candidates.empty()) {
9628 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9629 << FD->getDeclName() << FDLookupContext;
9630 // FIXME: We should form a single candidate list and diagnose all
9631 // candidates at once, to get proper sorting and limiting.
9632 for (auto *OldND : Previous) {
9633 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9634 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9635 }
9636 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9637 return true;
9638 }
9639
9640 // Find the most specialized function template.
9642 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9643 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9644 PDiag(diag::err_function_template_spec_ambiguous)
9645 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9646 PDiag(diag::note_function_template_spec_matched));
9647
9648 if (Result == Candidates.end())
9649 return true;
9650
9651 // Ignore access information; it doesn't figure into redeclaration checking.
9653
9654 if (const auto *PT = Specialization->getPrimaryTemplate();
9655 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9656 auto Message = DSA->getMessage();
9657 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9658 << PT << !Message.empty() << Message;
9659 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9660 }
9661
9662 // C++23 [except.spec]p13:
9663 // An exception specification is considered to be needed when:
9664 // - [...]
9665 // - the exception specification is compared to that of another declaration
9666 // (e.g., an explicit specialization or an overriding virtual function);
9667 // - [...]
9668 //
9669 // The exception specification of a defaulted function is evaluated as
9670 // described above only when needed; similarly, the noexcept-specifier of a
9671 // specialization of a function template or member function of a class
9672 // template is instantiated only when needed.
9673 //
9674 // The standard doesn't specify what the "comparison with another declaration"
9675 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9676 // not state which properties of an explicit specialization must match the
9677 // primary template.
9678 //
9679 // We assume that an explicit specialization must correspond with (per
9680 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9681 // the declaration produced by substitution into the function template.
9682 //
9683 // Since the determination whether two function declarations correspond does
9684 // not consider exception specification, we only need to instantiate it once
9685 // we determine the primary template when comparing types per
9686 // [basic.link]p11.1.
9687 auto *SpecializationFPT =
9688 Specialization->getType()->castAs<FunctionProtoType>();
9689 // If the function has a dependent exception specification, resolve it after
9690 // we have selected the primary template so we can check whether it matches.
9691 if (getLangOpts().CPlusPlus17 &&
9692 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9693 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9694 return true;
9695
9697 = Specialization->getTemplateSpecializationInfo();
9698 assert(SpecInfo && "Function template specialization info missing?");
9699
9700 // Note: do not overwrite location info if previous template
9701 // specialization kind was explicit.
9703 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9704 Specialization->setLocation(FD->getLocation());
9705 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9706 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9707 // function can differ from the template declaration with respect to
9708 // the constexpr specifier.
9709 // FIXME: We need an update record for this AST mutation.
9710 // FIXME: What if there are multiple such prior declarations (for instance,
9711 // from different modules)?
9712 Specialization->setConstexprKind(FD->getConstexprKind());
9713 }
9714
9715 // FIXME: Check if the prior specialization has a point of instantiation.
9716 // If so, we have run afoul of .
9717
9718 // If this is a friend declaration, then we're not really declaring
9719 // an explicit specialization.
9720 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9721
9722 // Check the scope of this explicit specialization.
9723 if (!isFriend &&
9725 Specialization->getPrimaryTemplate(),
9727 false))
9728 return true;
9729
9730 // C++ [temp.expl.spec]p6:
9731 // If a template, a member template or the member of a class template is
9732 // explicitly specialized then that specialization shall be declared
9733 // before the first use of that specialization that would cause an implicit
9734 // instantiation to take place, in every translation unit in which such a
9735 // use occurs; no diagnostic is required.
9736 bool HasNoEffect = false;
9737 if (!isFriend &&
9742 SpecInfo->getPointOfInstantiation(),
9743 HasNoEffect))
9744 return true;
9745
9746 // Mark the prior declaration as an explicit specialization, so that later
9747 // clients know that this is an explicit specialization.
9748 // A dependent friend specialization which has a definition should be treated
9749 // as explicit specialization, despite being invalid.
9750 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9751 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9752 // Since explicit specializations do not inherit '=delete' from their
9753 // primary function template - check if the 'specialization' that was
9754 // implicitly generated (during template argument deduction for partial
9755 // ordering) from the most specialized of all the function templates that
9756 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9757 // first check that it was implicitly generated during template argument
9758 // deduction by making sure it wasn't referenced, and then reset the deleted
9759 // flag to not-deleted, so that we can inherit that information from 'FD'.
9760 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9761 !Specialization->getCanonicalDecl()->isReferenced()) {
9762 // FIXME: This assert will not hold in the presence of modules.
9763 assert(
9764 Specialization->getCanonicalDecl() == Specialization &&
9765 "This must be the only existing declaration of this specialization");
9766 // FIXME: We need an update record for this AST mutation.
9767 Specialization->setDeletedAsWritten(false);
9768 }
9769 // FIXME: We need an update record for this AST mutation.
9772 }
9773
9774 // Turn the given function declaration into a function template
9775 // specialization, with the template arguments from the previous
9776 // specialization.
9777 // Take copies of (semantic and syntactic) template argument lists.
9779 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9780 FD->setFunctionTemplateSpecialization(
9781 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9783 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9784
9785 // A function template specialization inherits the target attributes
9786 // of its template. (We require the attributes explicitly in the
9787 // code to match, but a template may have implicit attributes by
9788 // virtue e.g. of being constexpr, and it passes these implicit
9789 // attributes on to its specializations.)
9790 if (LangOpts.CUDA)
9791 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9792
9793 // The "previous declaration" for this function template specialization is
9794 // the prior function template specialization.
9795 Previous.clear();
9796 Previous.addDecl(Specialization);
9797 return false;
9798}
9799
9800bool
9802 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9803 "Only for non-template members");
9804
9805 // Try to find the member we are instantiating.
9806 NamedDecl *FoundInstantiation = nullptr;
9807 NamedDecl *Instantiation = nullptr;
9808 NamedDecl *InstantiatedFrom = nullptr;
9809 MemberSpecializationInfo *MSInfo = nullptr;
9810
9811 if (Previous.empty()) {
9812 // Nowhere to look anyway.
9813 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9814 UnresolvedSet<8> Candidates;
9815 for (NamedDecl *Candidate : Previous) {
9816 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9817 // Ignore any candidates that aren't member functions.
9818 if (!Method)
9819 continue;
9820
9821 QualType Adjusted = Function->getType();
9822 if (!hasExplicitCallingConv(Adjusted))
9823 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9824 // Ignore any candidates with the wrong type.
9825 // This doesn't handle deduced return types, but both function
9826 // declarations should be undeduced at this point.
9827 // FIXME: The exception specification should probably be ignored when
9828 // comparing the types.
9829 if (!Context.hasSameType(Adjusted, Method->getType()))
9830 continue;
9831
9832 // Ignore any candidates with unsatisfied constraints.
9833 if (ConstraintSatisfaction Satisfaction;
9834 Method->getTrailingRequiresClause() &&
9835 (CheckFunctionConstraints(Method, Satisfaction,
9836 /*UsageLoc=*/Member->getLocation(),
9837 /*ForOverloadResolution=*/true) ||
9838 !Satisfaction.IsSatisfied))
9839 continue;
9840
9841 Candidates.addDecl(Candidate);
9842 }
9843
9844 // If we have no viable candidates left after filtering, we are done.
9845 if (Candidates.empty())
9846 return false;
9847
9848 // Find the function that is more constrained than every other function it
9849 // has been compared to.
9850 UnresolvedSetIterator Best = Candidates.begin();
9851 CXXMethodDecl *BestMethod = nullptr;
9852 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9853 I != E; ++I) {
9854 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9855 if (I == Best ||
9856 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9857 Best = I;
9858 BestMethod = Method;
9859 }
9860 }
9861
9862 FoundInstantiation = *Best;
9863 Instantiation = BestMethod;
9864 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9865 MSInfo = BestMethod->getMemberSpecializationInfo();
9866
9867 // Make sure the best candidate is more constrained than all of the others.
9868 bool Ambiguous = false;
9869 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9870 I != E; ++I) {
9871 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9872 if (I != Best &&
9873 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9874 Ambiguous = true;
9875 break;
9876 }
9877 }
9878
9879 if (Ambiguous) {
9880 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9881 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9882 for (NamedDecl *Candidate : Candidates) {
9883 Candidate = Candidate->getUnderlyingDecl();
9884 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9885 << Candidate;
9886 }
9887 return true;
9888 }
9889 } else if (isa<VarDecl>(Member)) {
9890 VarDecl *PrevVar;
9891 if (Previous.isSingleResult() &&
9892 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9893 if (PrevVar->isStaticDataMember()) {
9894 FoundInstantiation = Previous.getRepresentativeDecl();
9895 Instantiation = PrevVar;
9896 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9897 MSInfo = PrevVar->getMemberSpecializationInfo();
9898 }
9899 } else if (isa<RecordDecl>(Member)) {
9900 CXXRecordDecl *PrevRecord;
9901 if (Previous.isSingleResult() &&
9902 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9903 FoundInstantiation = Previous.getRepresentativeDecl();
9904 Instantiation = PrevRecord;
9905 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9906 MSInfo = PrevRecord->getMemberSpecializationInfo();
9907 }
9908 } else if (isa<EnumDecl>(Member)) {
9909 EnumDecl *PrevEnum;
9910 if (Previous.isSingleResult() &&
9911 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9912 FoundInstantiation = Previous.getRepresentativeDecl();
9913 Instantiation = PrevEnum;
9914 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9915 MSInfo = PrevEnum->getMemberSpecializationInfo();
9916 }
9917 }
9918
9919 if (!Instantiation) {
9920 // There is no previous declaration that matches. Since member
9921 // specializations are always out-of-line, the caller will complain about
9922 // this mismatch later.
9923 return false;
9924 }
9925
9926 // A member specialization in a friend declaration isn't really declaring
9927 // an explicit specialization, just identifying a specific (possibly implicit)
9928 // specialization. Don't change the template specialization kind.
9929 //
9930 // FIXME: Is this really valid? Other compilers reject.
9931 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9932 // Preserve instantiation information.
9933 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9934 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9935 cast<CXXMethodDecl>(InstantiatedFrom),
9937 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9938 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9939 cast<CXXRecordDecl>(InstantiatedFrom),
9941 }
9942
9943 Previous.clear();
9944 Previous.addDecl(FoundInstantiation);
9945 return false;
9946 }
9947
9948 // Make sure that this is a specialization of a member.
9949 if (!InstantiatedFrom) {
9950 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9951 << Member;
9952 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9953 return true;
9954 }
9955
9956 // C++ [temp.expl.spec]p6:
9957 // If a template, a member template or the member of a class template is
9958 // explicitly specialized then that specialization shall be declared
9959 // before the first use of that specialization that would cause an implicit
9960 // instantiation to take place, in every translation unit in which such a
9961 // use occurs; no diagnostic is required.
9962 assert(MSInfo && "Member specialization info missing?");
9963
9964 bool HasNoEffect = false;
9967 Instantiation,
9969 MSInfo->getPointOfInstantiation(),
9970 HasNoEffect))
9971 return true;
9972
9973 // Check the scope of this explicit specialization.
9975 InstantiatedFrom,
9976 Instantiation, Member->getLocation(),
9977 false))
9978 return true;
9979
9980 // Note that this member specialization is an "instantiation of" the
9981 // corresponding member of the original template.
9982 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9983 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9984 if (InstantiationFunction->getTemplateSpecializationKind() ==
9986 // Explicit specializations of member functions of class templates do not
9987 // inherit '=delete' from the member function they are specializing.
9988 if (InstantiationFunction->isDeleted()) {
9989 // FIXME: This assert will not hold in the presence of modules.
9990 assert(InstantiationFunction->getCanonicalDecl() ==
9991 InstantiationFunction);
9992 // FIXME: We need an update record for this AST mutation.
9993 InstantiationFunction->setDeletedAsWritten(false);
9994 }
9995 }
9996
9997 MemberFunction->setInstantiationOfMemberFunction(
9999 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10000 MemberVar->setInstantiationOfStaticDataMember(
10001 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10002 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10003 MemberClass->setInstantiationOfMemberClass(
10005 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10006 MemberEnum->setInstantiationOfMemberEnum(
10007 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10008 } else {
10009 llvm_unreachable("unknown member specialization kind");
10010 }
10011
10012 // Save the caller the trouble of having to figure out which declaration
10013 // this specialization matches.
10014 Previous.clear();
10015 Previous.addDecl(FoundInstantiation);
10016 return false;
10017}
10018
10019/// Complete the explicit specialization of a member of a class template by
10020/// updating the instantiated member to be marked as an explicit specialization.
10021///
10022/// \param OrigD The member declaration instantiated from the template.
10023/// \param Loc The location of the explicit specialization of the member.
10024template<typename DeclT>
10025static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10026 SourceLocation Loc) {
10027 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10028 return;
10029
10030 // FIXME: Inform AST mutation listeners of this AST mutation.
10031 // FIXME: If there are multiple in-class declarations of the member (from
10032 // multiple modules, or a declaration and later definition of a member type),
10033 // should we update all of them?
10034 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10035 OrigD->setLocation(Loc);
10036}
10037
10040 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10041 if (Instantiation == Member)
10042 return;
10043
10044 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10045 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10046 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10047 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10048 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10049 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10050 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10051 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10052 else
10053 llvm_unreachable("unknown member specialization kind");
10054}
10055
10056/// Check the scope of an explicit instantiation.
10057///
10058/// \returns true if a serious error occurs, false otherwise.
10060 SourceLocation InstLoc,
10061 bool WasQualifiedName) {
10063 DeclContext *CurContext = S.CurContext->getRedeclContext();
10064
10065 if (CurContext->isRecord()) {
10066 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10067 << D;
10068 return true;
10069 }
10070
10071 // C++11 [temp.explicit]p3:
10072 // An explicit instantiation shall appear in an enclosing namespace of its
10073 // template. If the name declared in the explicit instantiation is an
10074 // unqualified name, the explicit instantiation shall appear in the
10075 // namespace where its template is declared or, if that namespace is inline
10076 // (7.3.1), any namespace from its enclosing namespace set.
10077 //
10078 // This is DR275, which we do not retroactively apply to C++98/03.
10079 if (WasQualifiedName) {
10080 if (CurContext->Encloses(OrigContext))
10081 return false;
10082 } else {
10083 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10084 return false;
10085 }
10086
10087 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10088 if (WasQualifiedName)
10089 S.Diag(InstLoc,
10090 S.getLangOpts().CPlusPlus11?
10091 diag::err_explicit_instantiation_out_of_scope :
10092 diag::warn_explicit_instantiation_out_of_scope_0x)
10093 << D << NS;
10094 else
10095 S.Diag(InstLoc,
10096 S.getLangOpts().CPlusPlus11?
10097 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10098 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10099 << D << NS;
10100 } else
10101 S.Diag(InstLoc,
10102 S.getLangOpts().CPlusPlus11?
10103 diag::err_explicit_instantiation_must_be_global :
10104 diag::warn_explicit_instantiation_must_be_global_0x)
10105 << D;
10106 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10107 return false;
10108}
10109
10110/// Common checks for whether an explicit instantiation of \p D is valid.
10112 SourceLocation InstLoc,
10113 bool WasQualifiedName,
10115 // C++ [temp.explicit]p13:
10116 // An explicit instantiation declaration shall not name a specialization of
10117 // a template with internal linkage.
10120 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10121 return true;
10122 }
10123
10124 // C++11 [temp.explicit]p3: [DR 275]
10125 // An explicit instantiation shall appear in an enclosing namespace of its
10126 // template.
10127 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10128 return true;
10129
10130 return false;
10131}
10132
10133/// Determine whether the given scope specifier has a template-id in it.
10135 // C++11 [temp.explicit]p3:
10136 // If the explicit instantiation is for a member function, a member class
10137 // or a static data member of a class template specialization, the name of
10138 // the class template specialization in the qualified-id for the member
10139 // name shall be a simple-template-id.
10140 //
10141 // C++98 has the same restriction, just worded differently.
10142 for (NestedNameSpecifier NNS = SS.getScopeRep();
10144 /**/) {
10145 const Type *T = NNS.getAsType();
10147 return true;
10148 NNS = T->getPrefix();
10149 }
10150 return false;
10151}
10152
10153/// Make a dllexport or dllimport attr on a class template specialization take
10154/// effect.
10157 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10158 assert(A && "dllExportImportClassTemplateSpecialization called "
10159 "on Def without dllexport or dllimport");
10160
10161 // We reject explicit instantiations in class scope, so there should
10162 // never be any delayed exported classes to worry about.
10163 assert(S.DelayedDllExportClasses.empty() &&
10164 "delayed exports present at explicit instantiation");
10166
10167 // Propagate attribute to base class templates.
10168 for (auto &B : Def->bases()) {
10169 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10170 B.getType()->getAsCXXRecordDecl()))
10172 }
10173
10175}
10176
10178 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10179 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10180 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10181 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10182 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10183 // Find the class template we're specializing
10184 TemplateName Name = TemplateD.get();
10185 TemplateDecl *TD = Name.getAsTemplateDecl();
10186 // Check that the specialization uses the same tag kind as the
10187 // original template.
10189 assert(Kind != TagTypeKind::Enum &&
10190 "Invalid enum tag in class template explicit instantiation!");
10191
10192 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10193
10194 if (!ClassTemplate) {
10195 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10196 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10197 Diag(TD->getLocation(), diag::note_previous_use);
10198 return true;
10199 }
10200
10201 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10202 Kind, /*isDefinition*/false, KWLoc,
10203 ClassTemplate->getIdentifier())) {
10204 Diag(KWLoc, diag::err_use_with_wrong_tag)
10205 << ClassTemplate
10207 ClassTemplate->getTemplatedDecl()->getKindName());
10208 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10209 diag::note_previous_use);
10210 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10211 }
10212
10213 // C++0x [temp.explicit]p2:
10214 // There are two forms of explicit instantiation: an explicit instantiation
10215 // definition and an explicit instantiation declaration. An explicit
10216 // instantiation declaration begins with the extern keyword. [...]
10217 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10220
10222 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10223 // Check for dllexport class template instantiation declarations,
10224 // except for MinGW mode.
10225 for (const ParsedAttr &AL : Attr) {
10226 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10227 Diag(ExternLoc,
10228 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10229 Diag(AL.getLoc(), diag::note_attribute);
10230 break;
10231 }
10232 }
10233
10234 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10235 Diag(ExternLoc,
10236 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10237 Diag(A->getLocation(), diag::note_attribute);
10238 }
10239 }
10240
10241 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10242 // instantiation declarations for most purposes.
10243 bool DLLImportExplicitInstantiationDef = false;
10245 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10246 // Check for dllimport class template instantiation definitions.
10247 bool DLLImport =
10248 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10249 for (const ParsedAttr &AL : Attr) {
10250 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10251 DLLImport = true;
10252 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10253 // dllexport trumps dllimport here.
10254 DLLImport = false;
10255 break;
10256 }
10257 }
10258 if (DLLImport) {
10260 DLLImportExplicitInstantiationDef = true;
10261 }
10262 }
10263
10264 // Translate the parser's template argument list in our AST format.
10265 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10266 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10267
10268 // Check that the template argument list is well-formed for this
10269 // template.
10271 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10272 /*DefaultArgs=*/{}, false, CTAI,
10273 /*UpdateArgsWithConversions=*/true,
10274 /*ConstraintsNotSatisfied=*/nullptr))
10275 return true;
10276
10277 // Find the class template specialization declaration that
10278 // corresponds to these arguments.
10279 void *InsertPos = nullptr;
10281 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10282
10283 TemplateSpecializationKind PrevDecl_TSK
10284 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10285
10286 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10287 Context.getTargetInfo().getTriple().isOSCygMing()) {
10288 // Check for dllexport class template instantiation definitions in MinGW
10289 // mode, if a previous declaration of the instantiation was seen.
10290 for (const ParsedAttr &AL : Attr) {
10291 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10292 Diag(AL.getLoc(),
10293 diag::warn_attribute_dllexport_explicit_instantiation_def);
10294 break;
10295 }
10296 }
10297 }
10298
10299 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10300 SS.isSet(), TSK))
10301 return true;
10302
10304
10305 bool HasNoEffect = false;
10306 if (PrevDecl) {
10307 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10308 PrevDecl, PrevDecl_TSK,
10309 PrevDecl->getPointOfInstantiation(),
10310 HasNoEffect))
10311 return PrevDecl;
10312
10313 // Even though HasNoEffect == true means that this explicit instantiation
10314 // has no effect on semantics, we go on to put its syntax in the AST.
10315
10316 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10317 PrevDecl_TSK == TSK_Undeclared) {
10318 // Since the only prior class template specialization with these
10319 // arguments was referenced but not declared, reuse that
10320 // declaration node as our own, updating the source location
10321 // for the template name to reflect our new declaration.
10322 // (Other source locations will be updated later.)
10323 Specialization = PrevDecl;
10324 Specialization->setLocation(TemplateNameLoc);
10325 PrevDecl = nullptr;
10326 }
10327
10328 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10329 DLLImportExplicitInstantiationDef) {
10330 // The new specialization might add a dllimport attribute.
10331 HasNoEffect = false;
10332 }
10333 }
10334
10335 if (!Specialization) {
10336 // Create a new class template specialization declaration node for
10337 // this explicit specialization.
10339 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10340 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10342
10343 // A MSInheritanceAttr attached to the previous declaration must be
10344 // propagated to the new node prior to instantiation.
10345 if (PrevDecl) {
10346 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10347 auto *Clone = A->clone(getASTContext());
10348 Clone->setInherited(true);
10349 Specialization->addAttr(Clone);
10350 Consumer.AssignInheritanceModel(Specialization);
10351 }
10352 }
10353
10354 if (!HasNoEffect && !PrevDecl) {
10355 // Insert the new specialization.
10356 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10357 }
10358 }
10359
10360 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10361
10362 // Set source locations for keywords.
10363 Specialization->setExternKeywordLoc(ExternLoc);
10364 Specialization->setTemplateKeywordLoc(TemplateLoc);
10365 Specialization->setBraceRange(SourceRange());
10366
10367 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10370
10371 // Add the explicit instantiation into its lexical context. However,
10372 // since explicit instantiations are never found by name lookup, we
10373 // just put it into the declaration context directly.
10374 Specialization->setLexicalDeclContext(CurContext);
10375 CurContext->addDecl(Specialization);
10376
10377 // Syntax is now OK, so return if it has no other effect on semantics.
10378 if (HasNoEffect) {
10379 // Set the template specialization kind.
10380 Specialization->setTemplateSpecializationKind(TSK);
10381 return Specialization;
10382 }
10383
10384 // C++ [temp.explicit]p3:
10385 // A definition of a class template or class member template
10386 // shall be in scope at the point of the explicit instantiation of
10387 // the class template or class member template.
10388 //
10389 // This check comes when we actually try to perform the
10390 // instantiation.
10392 = cast_or_null<ClassTemplateSpecializationDecl>(
10393 Specialization->getDefinition());
10394 if (!Def)
10396 /*Complain=*/true,
10397 CTAI.StrictPackMatch);
10398 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10399 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10400 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10401 }
10402
10403 // Instantiate the members of this class template specialization.
10404 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10405 Specialization->getDefinition());
10406 if (Def) {
10408 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10409 // TSK_ExplicitInstantiationDefinition
10410 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10412 DLLImportExplicitInstantiationDef)) {
10413 // FIXME: Need to notify the ASTMutationListener that we did this.
10415
10416 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10417 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10418 // An explicit instantiation definition can add a dll attribute to a
10419 // template with a previous instantiation declaration. MinGW doesn't
10420 // allow this.
10421 auto *A = cast<InheritableAttr>(
10423 A->setInherited(true);
10424 Def->addAttr(A);
10426 }
10427 }
10428
10429 // Fix a TSK_ImplicitInstantiation followed by a
10430 // TSK_ExplicitInstantiationDefinition
10431 bool NewlyDLLExported =
10432 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10433 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10434 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10435 // An explicit instantiation definition can add a dll attribute to a
10436 // template with a previous implicit instantiation. MinGW doesn't allow
10437 // this. We limit clang to only adding dllexport, to avoid potentially
10438 // strange codegen behavior. For example, if we extend this conditional
10439 // to dllimport, and we have a source file calling a method on an
10440 // implicitly instantiated template class instance and then declaring a
10441 // dllimport explicit instantiation definition for the same template
10442 // class, the codegen for the method call will not respect the dllimport,
10443 // while it will with cl. The Def will already have the DLL attribute,
10444 // since the Def and Specialization will be the same in the case of
10445 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10446 // attribute to the Specialization; we just need to make it take effect.
10447 assert(Def == Specialization &&
10448 "Def and Specialization should match for implicit instantiation");
10450 }
10451
10452 // In MinGW mode, export the template instantiation if the declaration
10453 // was marked dllexport.
10454 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10455 Context.getTargetInfo().getTriple().isOSCygMing() &&
10456 PrevDecl->hasAttr<DLLExportAttr>()) {
10458 }
10459
10460 // Set the template specialization kind. Make sure it is set before
10461 // instantiating the members which will trigger ASTConsumer callbacks.
10462 Specialization->setTemplateSpecializationKind(TSK);
10463 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10464 } else {
10465
10466 // Set the template specialization kind.
10467 Specialization->setTemplateSpecializationKind(TSK);
10468 }
10469
10470 return Specialization;
10471}
10472
10475 SourceLocation TemplateLoc, unsigned TagSpec,
10476 SourceLocation KWLoc, CXXScopeSpec &SS,
10477 IdentifierInfo *Name, SourceLocation NameLoc,
10478 const ParsedAttributesView &Attr) {
10479
10480 bool Owned = false;
10481 bool IsDependent = false;
10482 Decl *TagD =
10483 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10484 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10485 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10486 false, TypeResult(), /*IsTypeSpecifier*/ false,
10487 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10488 .get();
10489 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10490
10491 if (!TagD)
10492 return true;
10493
10494 TagDecl *Tag = cast<TagDecl>(TagD);
10495 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10496
10497 if (Tag->isInvalidDecl())
10498 return true;
10499
10501 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10502 if (!Pattern) {
10503 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10504 << Context.getCanonicalTagType(Record);
10505 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10506 return true;
10507 }
10508
10509 // C++0x [temp.explicit]p2:
10510 // If the explicit instantiation is for a class or member class, the
10511 // elaborated-type-specifier in the declaration shall include a
10512 // simple-template-id.
10513 //
10514 // C++98 has the same restriction, just worded differently.
10516 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10517 << Record << SS.getRange();
10518
10519 // C++0x [temp.explicit]p2:
10520 // There are two forms of explicit instantiation: an explicit instantiation
10521 // definition and an explicit instantiation declaration. An explicit
10522 // instantiation declaration begins with the extern keyword. [...]
10526
10527 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10528
10529 // Verify that it is okay to explicitly instantiate here.
10530 CXXRecordDecl *PrevDecl
10531 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10532 if (!PrevDecl && Record->getDefinition())
10533 PrevDecl = Record;
10534 if (PrevDecl) {
10536 bool HasNoEffect = false;
10537 assert(MSInfo && "No member specialization information?");
10538 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10539 PrevDecl,
10541 MSInfo->getPointOfInstantiation(),
10542 HasNoEffect))
10543 return true;
10544 if (HasNoEffect)
10545 return TagD;
10546 }
10547
10548 CXXRecordDecl *RecordDef
10549 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10550 if (!RecordDef) {
10551 // C++ [temp.explicit]p3:
10552 // A definition of a member class of a class template shall be in scope
10553 // at the point of an explicit instantiation of the member class.
10554 CXXRecordDecl *Def
10555 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10556 if (!Def) {
10557 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10558 << 0 << Record->getDeclName() << Record->getDeclContext();
10559 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10560 << Pattern;
10561 return true;
10562 } else {
10563 if (InstantiateClass(NameLoc, Record, Def,
10565 TSK))
10566 return true;
10567
10568 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10569 if (!RecordDef)
10570 return true;
10571 }
10572 }
10573
10574 // Instantiate all of the members of the class.
10575 InstantiateClassMembers(NameLoc, RecordDef,
10577
10579 MarkVTableUsed(NameLoc, RecordDef, true);
10580
10581 // FIXME: We don't have any representation for explicit instantiations of
10582 // member classes. Such a representation is not needed for compilation, but it
10583 // should be available for clients that want to see all of the declarations in
10584 // the source code.
10585 return TagD;
10586}
10587
10589 SourceLocation ExternLoc,
10590 SourceLocation TemplateLoc,
10591 Declarator &D) {
10592 // Explicit instantiations always require a name.
10593 // TODO: check if/when DNInfo should replace Name.
10595 DeclarationName Name = NameInfo.getName();
10596 if (!Name) {
10597 if (!D.isInvalidType())
10599 diag::err_explicit_instantiation_requires_name)
10601
10602 return true;
10603 }
10604
10605 // Get the innermost enclosing declaration scope.
10606 S = S->getDeclParent();
10607
10608 // Determine the type of the declaration.
10610 QualType R = T->getType();
10611 if (R.isNull())
10612 return true;
10613
10614 // C++ [dcl.stc]p1:
10615 // A storage-class-specifier shall not be specified in [...] an explicit
10616 // instantiation (14.7.2) directive.
10618 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10619 << Name;
10620 return true;
10621 } else if (D.getDeclSpec().getStorageClassSpec()
10623 // Complain about then remove the storage class specifier.
10624 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10626
10628 }
10629
10630 // C++0x [temp.explicit]p1:
10631 // [...] An explicit instantiation of a function template shall not use the
10632 // inline or constexpr specifiers.
10633 // Presumably, this also applies to member functions of class templates as
10634 // well.
10638 diag::err_explicit_instantiation_inline :
10639 diag::warn_explicit_instantiation_inline_0x)
10642 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10643 // not already specified.
10645 diag::err_explicit_instantiation_constexpr);
10646
10647 // A deduction guide is not on the list of entities that can be explicitly
10648 // instantiated.
10650 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10651 << /*explicit instantiation*/ 0;
10652 return true;
10653 }
10654
10655 // C++0x [temp.explicit]p2:
10656 // There are two forms of explicit instantiation: an explicit instantiation
10657 // definition and an explicit instantiation declaration. An explicit
10658 // instantiation declaration begins with the extern keyword. [...]
10662
10663 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10665 /*ObjectType=*/QualType());
10666
10667 if (!R->isFunctionType()) {
10668 // C++ [temp.explicit]p1:
10669 // A [...] static data member of a class template can be explicitly
10670 // instantiated from the member definition associated with its class
10671 // template.
10672 // C++1y [temp.explicit]p1:
10673 // A [...] variable [...] template specialization can be explicitly
10674 // instantiated from its template.
10675 if (Previous.isAmbiguous())
10676 return true;
10677
10678 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10679 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10680
10681 if (!PrevTemplate) {
10682 if (!Prev || !Prev->isStaticDataMember()) {
10683 // We expect to see a static data member here.
10684 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10685 << Name;
10686 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10687 P != PEnd; ++P)
10688 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10689 return true;
10690 }
10691
10693 // FIXME: Check for explicit specialization?
10695 diag::err_explicit_instantiation_data_member_not_instantiated)
10696 << Prev;
10697 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10698 // FIXME: Can we provide a note showing where this was declared?
10699 return true;
10700 }
10701 } else {
10702 // Explicitly instantiate a variable template.
10703
10704 // C++1y [dcl.spec.auto]p6:
10705 // ... A program that uses auto or decltype(auto) in a context not
10706 // explicitly allowed in this section is ill-formed.
10707 //
10708 // This includes auto-typed variable template instantiations.
10709 if (R->isUndeducedType()) {
10710 Diag(T->getTypeLoc().getBeginLoc(),
10711 diag::err_auto_not_allowed_var_inst);
10712 return true;
10713 }
10714
10716 // C++1y [temp.explicit]p3:
10717 // If the explicit instantiation is for a variable, the unqualified-id
10718 // in the declaration shall be a template-id.
10720 diag::err_explicit_instantiation_without_template_id)
10721 << PrevTemplate;
10722 Diag(PrevTemplate->getLocation(),
10723 diag::note_explicit_instantiation_here);
10724 return true;
10725 }
10726
10727 // Translate the parser's template argument list into our AST format.
10728 TemplateArgumentListInfo TemplateArgs =
10730
10731 DeclResult Res =
10732 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10733 TemplateArgs, /*SetWrittenArgs=*/true);
10734 if (Res.isInvalid())
10735 return true;
10736
10737 if (!Res.isUsable()) {
10738 // We somehow specified dependent template arguments in an explicit
10739 // instantiation. This should probably only happen during error
10740 // recovery.
10741 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10742 return true;
10743 }
10744
10745 // Ignore access control bits, we don't need them for redeclaration
10746 // checking.
10747 Prev = cast<VarDecl>(Res.get());
10748 }
10749
10750 // C++0x [temp.explicit]p2:
10751 // If the explicit instantiation is for a member function, a member class
10752 // or a static data member of a class template specialization, the name of
10753 // the class template specialization in the qualified-id for the member
10754 // name shall be a simple-template-id.
10755 //
10756 // C++98 has the same restriction, just worded differently.
10757 //
10758 // This does not apply to variable template specializations, where the
10759 // template-id is in the unqualified-id instead.
10760 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10762 diag::ext_explicit_instantiation_without_qualified_id)
10763 << Prev << D.getCXXScopeSpec().getRange();
10764
10765 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10766
10767 // Verify that it is okay to explicitly instantiate here.
10770 bool HasNoEffect = false;
10772 PrevTSK, POI, HasNoEffect))
10773 return true;
10774
10775 if (!HasNoEffect) {
10776 // Instantiate static data member or variable template.
10778 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10779 VTSD->setExternKeywordLoc(ExternLoc);
10780 VTSD->setTemplateKeywordLoc(TemplateLoc);
10781 }
10782
10783 // Merge attributes.
10785 if (PrevTemplate)
10786 ProcessAPINotes(Prev);
10787
10790 }
10791
10792 // Check the new variable specialization against the parsed input.
10793 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10794 Diag(T->getTypeLoc().getBeginLoc(),
10795 diag::err_invalid_var_template_spec_type)
10796 << 0 << PrevTemplate << R << Prev->getType();
10797 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10798 << 2 << PrevTemplate->getDeclName();
10799 return true;
10800 }
10801
10802 // FIXME: Create an ExplicitInstantiation node?
10803 return (Decl*) nullptr;
10804 }
10805
10806 // If the declarator is a template-id, translate the parser's template
10807 // argument list into our AST format.
10808 bool HasExplicitTemplateArgs = false;
10809 TemplateArgumentListInfo TemplateArgs;
10811 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10812 HasExplicitTemplateArgs = true;
10813 }
10814
10815 // C++ [temp.explicit]p1:
10816 // A [...] function [...] can be explicitly instantiated from its template.
10817 // A member function [...] of a class template can be explicitly
10818 // instantiated from the member definition associated with its class
10819 // template.
10820 UnresolvedSet<8> TemplateMatches;
10821 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10823 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10824 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10825 P != PEnd; ++P) {
10826 NamedDecl *Prev = *P;
10827 if (!HasExplicitTemplateArgs) {
10828 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10829 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10830 /*AdjustExceptionSpec*/true);
10831 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10832 if (Method->getPrimaryTemplate()) {
10833 TemplateMatches.addDecl(Method, P.getAccess());
10834 } else {
10835 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10836 C.FoundDecl = P.getPair();
10837 C.Function = Method;
10838 C.Viable = true;
10840 if (Method->getTrailingRequiresClause() &&
10842 /*ForOverloadResolution=*/true) ||
10843 !S.IsSatisfied)) {
10844 C.Viable = false;
10846 }
10847 }
10848 }
10849 }
10850 }
10851
10852 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10853 if (!FunTmpl)
10854 continue;
10855
10856 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10857 FunctionDecl *Specialization = nullptr;
10859 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10860 Specialization, Info);
10862 // Keep track of almost-matches.
10863 FailedTemplateCandidates.addCandidate().set(
10864 P.getPair(), FunTmpl->getTemplatedDecl(),
10865 MakeDeductionFailureInfo(Context, TDK, Info));
10866 (void)TDK;
10867 continue;
10868 }
10869
10870 // Target attributes are part of the cuda function signature, so
10871 // the cuda target of the instantiated function must match that of its
10872 // template. Given that C++ template deduction does not take
10873 // target attributes into account, we reject candidates here that
10874 // have a different target.
10875 if (LangOpts.CUDA &&
10876 CUDA().IdentifyTarget(Specialization,
10877 /* IgnoreImplicitHDAttr = */ true) !=
10878 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10879 FailedTemplateCandidates.addCandidate().set(
10880 P.getPair(), FunTmpl->getTemplatedDecl(),
10883 continue;
10884 }
10885
10886 TemplateMatches.addDecl(Specialization, P.getAccess());
10887 }
10888
10889 FunctionDecl *Specialization = nullptr;
10890 if (!NonTemplateMatches.empty()) {
10891 unsigned Msg = 0;
10892 OverloadCandidateDisplayKind DisplayKind;
10894 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10895 Best)) {
10896 case OR_Success:
10897 case OR_Deleted:
10898 Specialization = cast<FunctionDecl>(Best->Function);
10899 break;
10900 case OR_Ambiguous:
10901 Msg = diag::err_explicit_instantiation_ambiguous;
10902 DisplayKind = OCD_AmbiguousCandidates;
10903 break;
10905 Msg = diag::err_explicit_instantiation_no_candidate;
10906 DisplayKind = OCD_AllCandidates;
10907 break;
10908 }
10909 if (Msg) {
10910 PartialDiagnostic Diag = PDiag(Msg) << Name;
10911 NonTemplateMatches.NoteCandidates(
10912 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10913 {});
10914 return true;
10915 }
10916 }
10917
10918 if (!Specialization) {
10919 // Find the most specialized function template specialization.
10921 TemplateMatches.begin(), TemplateMatches.end(),
10922 FailedTemplateCandidates, D.getIdentifierLoc(),
10923 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10924 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10925 PDiag(diag::note_explicit_instantiation_candidate));
10926
10927 if (Result == TemplateMatches.end())
10928 return true;
10929
10930 // Ignore access control bits, we don't need them for redeclaration checking.
10932 }
10933
10934 // C++11 [except.spec]p4
10935 // In an explicit instantiation an exception-specification may be specified,
10936 // but is not required.
10937 // If an exception-specification is specified in an explicit instantiation
10938 // directive, it shall be compatible with the exception-specifications of
10939 // other declarations of that function.
10940 if (auto *FPT = R->getAs<FunctionProtoType>())
10941 if (FPT->hasExceptionSpec()) {
10942 unsigned DiagID =
10943 diag::err_mismatched_exception_spec_explicit_instantiation;
10944 if (getLangOpts().MicrosoftExt)
10945 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10947 PDiag(DiagID) << Specialization->getType(),
10948 PDiag(diag::note_explicit_instantiation_here),
10949 Specialization->getType()->getAs<FunctionProtoType>(),
10950 Specialization->getLocation(), FPT, D.getBeginLoc());
10951 // In Microsoft mode, mismatching exception specifications just cause a
10952 // warning.
10953 if (!getLangOpts().MicrosoftExt && Result)
10954 return true;
10955 }
10956
10957 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10959 diag::err_explicit_instantiation_member_function_not_instantiated)
10961 << (Specialization->getTemplateSpecializationKind() ==
10963 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10964 return true;
10965 }
10966
10967 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10968 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10969 PrevDecl = Specialization;
10970
10971 if (PrevDecl) {
10972 bool HasNoEffect = false;
10974 PrevDecl,
10976 PrevDecl->getPointOfInstantiation(),
10977 HasNoEffect))
10978 return true;
10979
10980 // FIXME: We may still want to build some representation of this
10981 // explicit specialization.
10982 if (HasNoEffect)
10983 return (Decl*) nullptr;
10984 }
10985
10986 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10987 // functions
10988 // valarray<size_t>::valarray(size_t) and
10989 // valarray<size_t>::~valarray()
10990 // that it declared to have internal linkage with the internal_linkage
10991 // attribute. Ignore the explicit instantiation declaration in this case.
10992 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10994 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10995 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10996 RD->isInStdNamespace())
10997 return (Decl*) nullptr;
10998 }
10999
11002
11003 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11004 // instantiation declarations.
11006 Specialization->hasAttr<DLLImportAttr>() &&
11007 Context.getTargetInfo().getCXXABI().isMicrosoft())
11009
11010 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11011
11012 if (Specialization->isDefined()) {
11013 // Let the ASTConsumer know that this function has been explicitly
11014 // instantiated now, and its linkage might have changed.
11015 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11016 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11018
11019 // C++0x [temp.explicit]p2:
11020 // If the explicit instantiation is for a member function, a member class
11021 // or a static data member of a class template specialization, the name of
11022 // the class template specialization in the qualified-id for the member
11023 // name shall be a simple-template-id.
11024 //
11025 // C++98 has the same restriction, just worded differently.
11026 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11027 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11028 D.getCXXScopeSpec().isSet() &&
11031 diag::ext_explicit_instantiation_without_qualified_id)
11033
11035 *this,
11036 FunTmpl ? (NamedDecl *)FunTmpl
11037 : Specialization->getInstantiatedFromMemberFunction(),
11038 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11039
11040 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11041 return (Decl*) nullptr;
11042}
11043
11045 const CXXScopeSpec &SS,
11046 const IdentifierInfo *Name,
11047 SourceLocation TagLoc,
11048 SourceLocation NameLoc) {
11049 // This has to hold, because SS is expected to be defined.
11050 assert(Name && "Expected a name in a dependent tag");
11051
11053 if (!NNS)
11054 return true;
11055
11057
11058 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11059 Diag(NameLoc, diag::err_dependent_tag_decl)
11060 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11061 return true;
11062 }
11063
11064 // Create the resulting type.
11066 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11067
11068 // Create type-source location information for this type.
11069 TypeLocBuilder TLB;
11071 TL.setElaboratedKeywordLoc(TagLoc);
11073 TL.setNameLoc(NameLoc);
11075}
11076
11078 const CXXScopeSpec &SS,
11079 const IdentifierInfo &II,
11080 SourceLocation IdLoc,
11081 ImplicitTypenameContext IsImplicitTypename) {
11082 if (SS.isInvalid())
11083 return true;
11084
11085 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11086 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11087 << FixItHint::CreateRemoval(TypenameLoc);
11088
11090 TypeSourceInfo *TSI = nullptr;
11091 QualType T =
11094 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11095 /*DeducedTSTContext=*/true);
11096 if (T.isNull())
11097 return true;
11098 return CreateParsedType(T, TSI);
11099}
11100
11103 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11104 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11105 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11106 ASTTemplateArgsPtr TemplateArgsIn,
11107 SourceLocation RAngleLoc) {
11108 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11109 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11110 ? diag::compat_cxx11_typename_outside_of_template
11111 : diag::compat_pre_cxx11_typename_outside_of_template)
11112 << FixItHint::CreateRemoval(TypenameLoc);
11113
11114 // Strangely, non-type results are not ignored by this lookup, so the
11115 // program is ill-formed if it finds an injected-class-name.
11116 if (TypenameLoc.isValid()) {
11117 auto *LookupRD =
11118 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11119 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11120 Diag(TemplateIILoc,
11121 diag::ext_out_of_line_qualified_id_type_names_constructor)
11122 << TemplateII << 0 /*injected-class-name used as template name*/
11123 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11124 }
11125 }
11126
11127 // Translate the parser's template argument list in our AST format.
11128 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11129 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11130
11131 auto Keyword = TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11133
11134 TemplateName Template = TemplateIn.get();
11135 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11136 // Construct a dependent template specialization type.
11137 assert(DTN && "dependent template has non-dependent name?");
11138 assert(DTN->getQualifier() == SS.getScopeRep());
11139
11140 if (!DTN->getName().getIdentifier()) {
11141 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
11143 return true;
11144 }
11145
11146 QualType T = Context.getDependentTemplateSpecializationType(
11147 Keyword, *DTN, TemplateArgs.arguments());
11148
11149 // Create source-location information for this type.
11150 TypeLocBuilder Builder;
11153 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11155 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11156 SpecTL.setTemplateNameLoc(TemplateIILoc);
11157 SpecTL.setLAngleLoc(LAngleLoc);
11158 SpecTL.setRAngleLoc(RAngleLoc);
11159 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11160 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11161 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11162 }
11163
11164 QualType T = CheckTemplateIdType(TypenameLoc.isValid()
11167 Template, TemplateIILoc, TemplateArgs);
11168 if (T.isNull())
11169 return true;
11170
11171 // Provide source-location information for the template specialization type.
11172 TypeLocBuilder Builder;
11174 = Builder.push<TemplateSpecializationTypeLoc>(T);
11175 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11176 TemplateIILoc, TemplateArgs);
11177 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11178 return CreateParsedType(T, TSI);
11179}
11180
11181/// Determine whether this failed name lookup should be treated as being
11182/// disabled by a usage of std::enable_if.
11184 SourceRange &CondRange, Expr *&Cond) {
11185 // We must be looking for a ::type...
11186 if (!II.isStr("type"))
11187 return false;
11188
11189 // ... within an explicitly-written template specialization...
11191 return false;
11192
11193 // FIXME: Look through sugar.
11194 auto EnableIfTSTLoc =
11196 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11197 return false;
11198 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11199
11200 // ... which names a complete class template declaration...
11201 const TemplateDecl *EnableIfDecl =
11202 EnableIfTST->getTemplateName().getAsTemplateDecl();
11203 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11204 return false;
11205
11206 // ... called "enable_if".
11207 const IdentifierInfo *EnableIfII =
11208 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11209 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11210 return false;
11211
11212 // Assume the first template argument is the condition.
11213 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11214
11215 // Dig out the condition.
11216 Cond = nullptr;
11217 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11219 return true;
11220
11221 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11222
11223 // Ignore Boolean literals; they add no value.
11224 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11225 Cond = nullptr;
11226
11227 return true;
11228}
11229
11232 SourceLocation KeywordLoc,
11233 NestedNameSpecifierLoc QualifierLoc,
11234 const IdentifierInfo &II,
11235 SourceLocation IILoc,
11236 TypeSourceInfo **TSI,
11237 bool DeducedTSTContext) {
11238 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11239 DeducedTSTContext);
11240 if (T.isNull())
11241 return QualType();
11242
11243 TypeLocBuilder TLB;
11245 auto TL = TLB.push<DependentNameTypeLoc>(T);
11246 TL.setElaboratedKeywordLoc(KeywordLoc);
11247 TL.setQualifierLoc(QualifierLoc);
11248 TL.setNameLoc(IILoc);
11251 TL.setElaboratedKeywordLoc(KeywordLoc);
11252 TL.setQualifierLoc(QualifierLoc);
11253 TL.setNameLoc(IILoc);
11254 } else if (isa<TemplateTypeParmType>(T)) {
11255 // FIXME: There might be a 'typename' keyword here, but we just drop it
11256 // as it can't be represented.
11257 assert(!QualifierLoc);
11258 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11259 } else if (isa<TagType>(T)) {
11260 auto TL = TLB.push<TagTypeLoc>(T);
11261 TL.setElaboratedKeywordLoc(KeywordLoc);
11262 TL.setQualifierLoc(QualifierLoc);
11263 TL.setNameLoc(IILoc);
11264 } else if (isa<TypedefType>(T)) {
11265 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11266 } else {
11267 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11268 }
11269 *TSI = TLB.getTypeSourceInfo(Context, T);
11270 return T;
11271}
11272
11273/// Build the type that describes a C++ typename specifier,
11274/// e.g., "typename T::type".
11277 SourceLocation KeywordLoc,
11278 NestedNameSpecifierLoc QualifierLoc,
11279 const IdentifierInfo &II,
11280 SourceLocation IILoc, bool DeducedTSTContext) {
11281 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11282
11283 CXXScopeSpec SS;
11284 SS.Adopt(QualifierLoc);
11285
11286 DeclContext *Ctx = nullptr;
11287 if (QualifierLoc) {
11288 Ctx = computeDeclContext(SS);
11289 if (!Ctx) {
11290 // If the nested-name-specifier is dependent and couldn't be
11291 // resolved to a type, build a typename type.
11292 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11293 return Context.getDependentNameType(Keyword,
11294 QualifierLoc.getNestedNameSpecifier(),
11295 &II);
11296 }
11297
11298 // If the nested-name-specifier refers to the current instantiation,
11299 // the "typename" keyword itself is superfluous. In C++03, the
11300 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11301 // allows such extraneous "typename" keywords, and we retroactively
11302 // apply this DR to C++03 code with only a warning. In any case we continue.
11303
11304 if (RequireCompleteDeclContext(SS, Ctx))
11305 return QualType();
11306 }
11307
11308 DeclarationName Name(&II);
11309 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11310 if (Ctx)
11311 LookupQualifiedName(Result, Ctx, SS);
11312 else
11313 LookupName(Result, CurScope);
11314 unsigned DiagID = 0;
11315 Decl *Referenced = nullptr;
11316 switch (Result.getResultKind()) {
11318 // If we're looking up 'type' within a template named 'enable_if', produce
11319 // a more specific diagnostic.
11320 SourceRange CondRange;
11321 Expr *Cond = nullptr;
11322 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11323 // If we have a condition, narrow it down to the specific failed
11324 // condition.
11325 if (Cond) {
11326 Expr *FailedCond;
11327 std::string FailedDescription;
11328 std::tie(FailedCond, FailedDescription) =
11330
11331 Diag(FailedCond->getExprLoc(),
11332 diag::err_typename_nested_not_found_requirement)
11333 << FailedDescription
11334 << FailedCond->getSourceRange();
11335 return QualType();
11336 }
11337
11338 Diag(CondRange.getBegin(),
11339 diag::err_typename_nested_not_found_enable_if)
11340 << Ctx << CondRange;
11341 return QualType();
11342 }
11343
11344 DiagID = Ctx ? diag::err_typename_nested_not_found
11345 : diag::err_unknown_typename;
11346 break;
11347 }
11348
11350 // We found a using declaration that is a value. Most likely, the using
11351 // declaration itself is meant to have the 'typename' keyword.
11352 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11353 IILoc);
11354 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11355 << Name << Ctx << FullRange;
11356 if (UnresolvedUsingValueDecl *Using
11357 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11358 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11359 Diag(Loc, diag::note_using_value_decl_missing_typename)
11360 << FixItHint::CreateInsertion(Loc, "typename ");
11361 }
11362 }
11363 // Fall through to create a dependent typename type, from which we can
11364 // recover better.
11365 [[fallthrough]];
11366
11368 // Okay, it's a member of an unknown instantiation.
11369 return Context.getDependentNameType(Keyword,
11370 QualifierLoc.getNestedNameSpecifier(),
11371 &II);
11372
11374 // FXIME: Missing support for UsingShadowDecl on this path?
11375 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11376 // C++ [class.qual]p2:
11377 // In a lookup in which function names are not ignored and the
11378 // nested-name-specifier nominates a class C, if the name specified
11379 // after the nested-name-specifier, when looked up in C, is the
11380 // injected-class-name of C [...] then the name is instead considered
11381 // to name the constructor of class C.
11382 //
11383 // Unlike in an elaborated-type-specifier, function names are not ignored
11384 // in typename-specifier lookup. However, they are ignored in all the
11385 // contexts where we form a typename type with no keyword (that is, in
11386 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11387 //
11388 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11389 // ignore functions, but that appears to be an oversight.
11394 Type, IILoc);
11395 // FIXME: This appears to be the only case where a template type parameter
11396 // can have an elaborated keyword. We should preserve it somehow.
11399 assert(!QualifierLoc);
11401 }
11402 return Context.getTypeDeclType(
11403 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11404 }
11405
11406 // C++ [dcl.type.simple]p2:
11407 // A type-specifier of the form
11408 // typename[opt] nested-name-specifier[opt] template-name
11409 // is a placeholder for a deduced class type [...].
11410 if (getLangOpts().CPlusPlus17) {
11411 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11412 if (!DeducedTSTContext) {
11413 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11414 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11415 Diag(IILoc, diag::err_dependent_deduced_tst)
11417 << QualType(Qualifier.getAsType(), 0);
11418 else
11419 Diag(IILoc, diag::err_deduced_tst)
11422 return QualType();
11423 }
11424 TemplateName Name = Context.getQualifiedTemplateName(
11425 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11426 TemplateName(TD));
11427 return Context.getDeducedTemplateSpecializationType(
11428 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11429 }
11430 }
11431
11432 DiagID = Ctx ? diag::err_typename_nested_not_type
11433 : diag::err_typename_not_type;
11434 Referenced = Result.getFoundDecl();
11435 break;
11436
11438 DiagID = Ctx ? diag::err_typename_nested_not_type
11439 : diag::err_typename_not_type;
11440 Referenced = *Result.begin();
11441 break;
11442
11444 return QualType();
11445 }
11446
11447 // If we get here, it's because name lookup did not find a
11448 // type. Emit an appropriate diagnostic and return an error.
11449 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11450 IILoc);
11451 if (Ctx)
11452 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11453 else
11454 Diag(IILoc, DiagID) << FullRange << Name;
11455 if (Referenced)
11456 Diag(Referenced->getLocation(),
11457 Ctx ? diag::note_typename_member_refers_here
11458 : diag::note_typename_refers_here)
11459 << Name;
11460 return QualType();
11461}
11462
11463namespace {
11464 // See Sema::RebuildTypeInCurrentInstantiation
11465 class CurrentInstantiationRebuilder
11466 : public TreeTransform<CurrentInstantiationRebuilder> {
11467 SourceLocation Loc;
11468 DeclarationName Entity;
11469
11470 public:
11472
11473 CurrentInstantiationRebuilder(Sema &SemaRef,
11474 SourceLocation Loc,
11475 DeclarationName Entity)
11476 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11477 Loc(Loc), Entity(Entity) { }
11478
11479 /// Determine whether the given type \p T has already been
11480 /// transformed.
11481 ///
11482 /// For the purposes of type reconstruction, a type has already been
11483 /// transformed if it is NULL or if it is not dependent.
11484 bool AlreadyTransformed(QualType T) {
11485 return T.isNull() || !T->isInstantiationDependentType();
11486 }
11487
11488 /// Returns the location of the entity whose type is being
11489 /// rebuilt.
11490 SourceLocation getBaseLocation() { return Loc; }
11491
11492 /// Returns the name of the entity whose type is being rebuilt.
11493 DeclarationName getBaseEntity() { return Entity; }
11494
11495 /// Sets the "base" location and entity when that
11496 /// information is known based on another transformation.
11497 void setBase(SourceLocation Loc, DeclarationName Entity) {
11498 this->Loc = Loc;
11499 this->Entity = Entity;
11500 }
11501
11502 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11503 // Lambdas never need to be transformed.
11504 return E;
11505 }
11506 };
11507} // end anonymous namespace
11508
11510 SourceLocation Loc,
11511 DeclarationName Name) {
11512 if (!T || !T->getType()->isInstantiationDependentType())
11513 return T;
11514
11515 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11516 return Rebuilder.TransformType(T);
11517}
11518
11520 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11521 DeclarationName());
11522 return Rebuilder.TransformExpr(E);
11523}
11524
11526 if (SS.isInvalid())
11527 return true;
11528
11530 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11531 DeclarationName());
11533 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11534 if (!Rebuilt)
11535 return true;
11536
11537 SS.Adopt(Rebuilt);
11538 return false;
11539}
11540
11542 TemplateParameterList *Params) {
11543 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11544 Decl *Param = Params->getParam(I);
11545
11546 // There is nothing to rebuild in a type parameter.
11547 if (isa<TemplateTypeParmDecl>(Param))
11548 continue;
11549
11550 // Rebuild the template parameter list of a template template parameter.
11552 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11554 TTP->getTemplateParameters()))
11555 return true;
11556
11557 continue;
11558 }
11559
11560 // Rebuild the type of a non-type template parameter.
11562 TypeSourceInfo *NewTSI
11564 NTTP->getLocation(),
11565 NTTP->getDeclName());
11566 if (!NewTSI)
11567 return true;
11568
11569 if (NewTSI->getType()->isUndeducedType()) {
11570 // C++17 [temp.dep.expr]p3:
11571 // An id-expression is type-dependent if it contains
11572 // - an identifier associated by name lookup with a non-type
11573 // template-parameter declared with a type that contains a
11574 // placeholder type (7.1.7.4),
11575 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11576 }
11577
11578 if (NewTSI != NTTP->getTypeSourceInfo()) {
11579 NTTP->setTypeSourceInfo(NewTSI);
11580 NTTP->setType(NewTSI->getType());
11581 }
11582 }
11583
11584 return false;
11585}
11586
11587std::string
11589 const TemplateArgumentList &Args) {
11590 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11591}
11592
11593std::string
11595 const TemplateArgument *Args,
11596 unsigned NumArgs) {
11597 SmallString<128> Str;
11598 llvm::raw_svector_ostream Out(Str);
11599
11600 if (!Params || Params->size() == 0 || NumArgs == 0)
11601 return std::string();
11602
11603 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11604 if (I >= NumArgs)
11605 break;
11606
11607 if (I == 0)
11608 Out << "[with ";
11609 else
11610 Out << ", ";
11611
11612 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11613 Out << Id->getName();
11614 } else {
11615 Out << '$' << I;
11616 }
11617
11618 Out << " = ";
11619 Args[I].print(getPrintingPolicy(), Out,
11621 getPrintingPolicy(), Params, I));
11622 }
11623
11624 Out << ']';
11625 return std::string(Out.str());
11626}
11627
11629 CachedTokens &Toks) {
11630 if (!FD)
11631 return;
11632
11633 auto LPT = std::make_unique<LateParsedTemplate>();
11634
11635 // Take tokens to avoid allocations
11636 LPT->Toks.swap(Toks);
11637 LPT->D = FnD;
11638 LPT->FPO = getCurFPFeatures();
11639 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11640
11641 FD->setLateTemplateParsed(true);
11642}
11643
11645 if (!FD)
11646 return;
11647 FD->setLateTemplateParsed(false);
11648}
11649
11651 DeclContext *DC = CurContext;
11652
11653 while (DC) {
11654 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11655 const FunctionDecl *FD = RD->isLocalClass();
11656 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11657 } else if (DC->isTranslationUnit() || DC->isNamespace())
11658 return false;
11659
11660 DC = DC->getParent();
11661 }
11662 return false;
11663}
11664
11665namespace {
11666/// Walk the path from which a declaration was instantiated, and check
11667/// that every explicit specialization along that path is visible. This enforces
11668/// C++ [temp.expl.spec]/6:
11669///
11670/// If a template, a member template or a member of a class template is
11671/// explicitly specialized then that specialization shall be declared before
11672/// the first use of that specialization that would cause an implicit
11673/// instantiation to take place, in every translation unit in which such a
11674/// use occurs; no diagnostic is required.
11675///
11676/// and also C++ [temp.class.spec]/1:
11677///
11678/// A partial specialization shall be declared before the first use of a
11679/// class template specialization that would make use of the partial
11680/// specialization as the result of an implicit or explicit instantiation
11681/// in every translation unit in which such a use occurs; no diagnostic is
11682/// required.
11683class ExplicitSpecializationVisibilityChecker {
11684 Sema &S;
11685 SourceLocation Loc;
11688
11689public:
11690 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11692 : S(S), Loc(Loc), Kind(Kind) {}
11693
11694 void check(NamedDecl *ND) {
11695 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11696 return checkImpl(FD);
11697 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11698 return checkImpl(RD);
11699 if (auto *VD = dyn_cast<VarDecl>(ND))
11700 return checkImpl(VD);
11701 if (auto *ED = dyn_cast<EnumDecl>(ND))
11702 return checkImpl(ED);
11703 }
11704
11705private:
11706 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11707 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11708 : Sema::MissingImportKind::ExplicitSpecialization;
11709 const bool Recover = true;
11710
11711 // If we got a custom set of modules (because only a subset of the
11712 // declarations are interesting), use them, otherwise let
11713 // diagnoseMissingImport intelligently pick some.
11714 if (Modules.empty())
11715 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11716 else
11717 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11718 }
11719
11720 bool CheckMemberSpecialization(const NamedDecl *D) {
11721 return Kind == Sema::AcceptableKind::Visible
11724 }
11725
11726 bool CheckExplicitSpecialization(const NamedDecl *D) {
11727 return Kind == Sema::AcceptableKind::Visible
11730 }
11731
11732 bool CheckDeclaration(const NamedDecl *D) {
11733 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11735 }
11736
11737 // Check a specific declaration. There are three problematic cases:
11738 //
11739 // 1) The declaration is an explicit specialization of a template
11740 // specialization.
11741 // 2) The declaration is an explicit specialization of a member of an
11742 // templated class.
11743 // 3) The declaration is an instantiation of a template, and that template
11744 // is an explicit specialization of a member of a templated class.
11745 //
11746 // We don't need to go any deeper than that, as the instantiation of the
11747 // surrounding class / etc is not triggered by whatever triggered this
11748 // instantiation, and thus should be checked elsewhere.
11749 template<typename SpecDecl>
11750 void checkImpl(SpecDecl *Spec) {
11751 bool IsHiddenExplicitSpecialization = false;
11752 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11753 // Some invalid friend declarations are written as specializations but are
11754 // instantiated implicitly.
11755 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11756 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11757 if (SpecKind == TSK_ExplicitSpecialization) {
11758 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11759 ? !CheckMemberSpecialization(Spec)
11760 : !CheckExplicitSpecialization(Spec);
11761 } else {
11762 checkInstantiated(Spec);
11763 }
11764
11765 if (IsHiddenExplicitSpecialization)
11766 diagnose(Spec->getMostRecentDecl(), false);
11767 }
11768
11769 void checkInstantiated(FunctionDecl *FD) {
11770 if (auto *TD = FD->getPrimaryTemplate())
11771 checkTemplate(TD);
11772 }
11773
11774 void checkInstantiated(CXXRecordDecl *RD) {
11775 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11776 if (!SD)
11777 return;
11778
11779 auto From = SD->getSpecializedTemplateOrPartial();
11780 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11781 checkTemplate(TD);
11782 else if (auto *TD =
11783 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11784 if (!CheckDeclaration(TD))
11785 diagnose(TD, true);
11786 checkTemplate(TD);
11787 }
11788 }
11789
11790 void checkInstantiated(VarDecl *RD) {
11791 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11792 if (!SD)
11793 return;
11794
11795 auto From = SD->getSpecializedTemplateOrPartial();
11796 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11797 checkTemplate(TD);
11798 else if (auto *TD =
11799 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11800 if (!CheckDeclaration(TD))
11801 diagnose(TD, true);
11802 checkTemplate(TD);
11803 }
11804 }
11805
11806 void checkInstantiated(EnumDecl *FD) {}
11807
11808 template<typename TemplDecl>
11809 void checkTemplate(TemplDecl *TD) {
11810 if (TD->isMemberSpecialization()) {
11811 if (!CheckMemberSpecialization(TD))
11812 diagnose(TD->getMostRecentDecl(), false);
11813 }
11814 }
11815};
11816} // end anonymous namespace
11817
11819 if (!getLangOpts().Modules)
11820 return;
11821
11822 ExplicitSpecializationVisibilityChecker(*this, Loc,
11824 .check(Spec);
11825}
11826
11828 NamedDecl *Spec) {
11829 if (!getLangOpts().CPlusPlusModules)
11830 return checkSpecializationVisibility(Loc, Spec);
11831
11832 ExplicitSpecializationVisibilityChecker(*this, Loc,
11834 .check(Spec);
11835}
11836
11839 return N->getLocation();
11840 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11842 return FD->getLocation();
11845 return N->getLocation();
11846 }
11847 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11848 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11849 continue;
11850 return CSC.PointOfInstantiation;
11851 }
11852 return N->getLocation();
11853}
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:983
APSInt & getInt()
Definition APValue.h:489
APSInt & getComplexIntImag()
Definition APValue.h:527
ValueKind getKind() const
Definition APValue.h:461
APFixedPoint & getFixedPoint()
Definition APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1066
APValue & getVectorElt(unsigned I)
Definition APValue.h:563
unsigned getVectorLength() const
Definition APValue.h:571
bool isLValue() const
Definition APValue.h:472
bool isMemberPointer() const
Definition APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
@ 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:1019
APSInt & getComplexIntReal()
Definition APValue.h:519
APFloat & getComplexFloatImag()
Definition APValue.h:543
APFloat & getComplexFloatReal()
Definition APValue.h:535
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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:894
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
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:3908
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:44
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2373
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2391
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2441
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2434
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2409
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2415
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2421
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8195
Pointer to a block type.
Definition TypeBase.h:3558
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:3182
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:2099
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:735
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3864
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:768
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2020
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:2050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2046
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2061
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
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:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
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:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3293
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
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:438
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3776
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4389
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isFileContext() const
Definition DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
bool isNamespace() const
Definition DeclBase.h:2198
bool isTranslationUnit() const
Definition DeclBase.h:2185
bool isRecord() const
Definition DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1272
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1373
ValueDecl * getDecl()
Definition Expr.h:1340
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
bool isVirtualSpecified() const
Definition DeclSpec.h:618
void ClearStorageClassSpecs()
Definition DeclSpec.h:485
bool isNoreturnSpecified() const
Definition DeclSpec.h:631
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:480
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:545
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:544
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:632
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:624
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:472
ParsedAttributes & getAttributes()
Definition DeclSpec.h:843
bool isInlineSpecified() const
Definition DeclSpec.h:607
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:481
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:806
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:610
bool hasExplicitSpecifier() const
Definition DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition DeclSpec.h:807
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
@ FOK_None
Not a friend object.
Definition DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:286
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:251
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:812
void dropAttrs()
static DeclContext * castToDeclContext(const Decl *)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2793
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:234
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition Decl.h:813
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2310
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2700
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2040
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2036
bool hasEllipsis() const
Definition DeclSpec.h:2699
bool isInvalidType() const
Definition DeclSpec.h:2688
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2028
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4077
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2570
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3504
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4027
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4117
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4448
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2631
void setTemplateKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2651
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2618
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition TypeLoc.h:2683
void setTemplateNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2659
IdentifierOrOverloadedOperator getName() const
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4243
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:4004
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4267
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
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:3078
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:444
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:3073
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:829
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:3053
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:4001
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4283
Represents a member of a struct/union/class.
Definition Decl.h:3157
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:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
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:102
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
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:1999
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4146
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4455
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4113
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3688
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2539
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
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:4319
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2361
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4358
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4106
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4860
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5282
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5567
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:4818
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:3789
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:3925
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
Describes an C or C++ initializer list.
Definition Expr.h:5235
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:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
Represents a linkage specification.
Definition DeclCXX.h:3009
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:365
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
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
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
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
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
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4392
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3669
QualType getPointeeType() const
Definition TypeBase.h:3687
Provides information a specialization of a member of a class template, which may be a member function...
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:260
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition Decl.h:500
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:591
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.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:7905
Represents a pointer to an Objective C object.
Definition TypeBase.h:7961
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:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:1416
bool isVarDeclReference() const
Definition ExprCXX.h:3296
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3312
bool isConceptReference() const
Definition ExprCXX.h:3285
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3331
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:4357
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:256
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2184
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:8161
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3346
QualType getPointeeType() const
Definition TypeBase.h:3356
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8432
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3591
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8343
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:8528
QualType getCanonicalType() const
Definition TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8437
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3584
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3651
Represents a struct/union/class.
Definition Decl.h:4309
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4493
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5292
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3589
QualType getPointeeType() const
Definition TypeBase.h:3607
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:362
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:481
Scope * getDeclParent()
Definition Scope.h:335
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
Scope * getTemplateParamParent()
Definition Scope.h:332
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
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:13497
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8393
A RAII object to temporarily push a declaration context.
Definition Sema.h:3468
Whether and why a template name is required in this lookup.
Definition Sema.h:11339
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11347
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12360
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12393
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7668
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:850
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:13431
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12937
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2539
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9277
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9281
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9289
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9284
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:9591
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:1438
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)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
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:4126
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:2042
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:11310
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:11893
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:11896
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:11900
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
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:1276
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...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:915
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:918
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:756
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:1184
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)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition Sema.h:11300
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12066
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12084
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12074
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12094
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:11360
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11367
@ None
This is not assumed to be a template name.
Definition Sema.h:11362
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11364
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:11293
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:168
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:913
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14268
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14256
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14265
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14259
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14283
const LangOptions & getLangOpts() const
Definition Sema.h:911
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.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition Sema.h:14709
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:1275
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:1274
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
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:1411
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
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:15279
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...
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 ...
ASTConsumer & Consumer
Definition Sema.h:1277
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:4622
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:6688
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6667
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 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:11337
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:509
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:11524
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11534
@ TPC_FriendFunctionTemplate
Definition Sema.h:11532
@ TPC_ClassTemplateMember
Definition Sema.h:11530
@ TPC_FunctionTemplate
Definition Sema.h:11529
@ TPC_FriendClassTemplate
Definition Sema.h:11531
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11533
friend class InitializationSequence
Definition Sema.h:1553
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
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)
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose=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.
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
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:6238
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6375
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1268
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3461
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11302
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:143
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:9600
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12780
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:322
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8599
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:358
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:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4658
A structure for storing an already-substituted template template parameter pack.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
StringRef getKindName() const
Definition Decl.h:3904
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:4921
TagKind getTagKind() const
Definition Decl.h:3908
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.
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 ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
TemplateName getUnderlying() const
bool isDependent() const
Determines whether this is a dependent template name.
std::pair< TemplateDecl *, DefaultArguments > getTemplateDeclAndDefaultArgs() const
Retrieves the underlying template declaration that this template name refers to, along with the deduc...
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:707
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3685
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:223
Represents a declaration of a type.
Definition Decl.h:3510
const Type * getTypeForDecl() const
Definition Decl.h:3535
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3544
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:942
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:6193
A container of type source information.
Definition TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8325
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2503
bool isBooleanType() const
Definition TypeBase.h:9066
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2229
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2277
bool isRValueReferenceType() const
Definition TypeBase.h:8612
bool isVoidPointerType() const
Definition Type.cpp:712
bool isArrayType() const
Definition TypeBase.h:8679
bool isPointerType() const
Definition TypeBase.h:8580
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9226
bool isReferenceType() const
Definition TypeBase.h:8604
bool isEnumeralType() const
Definition TypeBase.h:8711
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2107
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:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9054
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8757
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2917
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2808
bool isLValueReferenceType() const
Definition TypeBase.h:8608
bool isBitIntType() const
Definition TypeBase.h:8845
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2800
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2060
bool isMemberPointerType() const
Definition TypeBase.h:8661
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2818
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9072
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:4948
bool isPointerOrReferenceType() const
Definition TypeBase.h:8584
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2440
bool isFunctionType() const
Definition TypeBase.h:8576
bool isVectorType() const
Definition TypeBase.h:8719
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2939
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9159
bool isNullPtrType() const
Definition TypeBase.h:8973
bool isRecordType() const
Definition TypeBase.h:8707
QualType getUnderlyingType() const
Definition Decl.h:3614
Wrapper for source info for typedefs.
Definition TypeLoc.h:782
QualType desugar() const
Definition Type.cpp:4076
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:2246
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1030
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1210
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1207
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1026
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:432
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:787
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:5998
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3934
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3457
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:711
void setType(QualType newType)
Definition Decl.h:723
QualType getType() const
Definition Decl.h:722
Represents a variable declaration or definition.
Definition Decl.h:925
TLSKind getTLSKind() const
Definition Decl.cpp:2168
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
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:2907
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:2800
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:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3982
Represents a GCC generic vector type.
Definition TypeBase.h:4191
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.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:55
ImplicitTypenameContext
Definition DeclSpec.h:1857
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
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:913
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:602
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:982
@ IK_Identifier
An identifier.
Definition DeclSpec.h:976
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:978
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:123
@ AS_public
Definition Specifiers.h:124
@ AS_none
Definition Specifiers.h:127
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
StorageClass
Storage classes.
Definition Specifiers.h:248
@ SC_Extern
Definition Specifiers.h:251
@ TSCS_unspecified
Definition Specifiers.h:236
Expr * Cond
};
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:448
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5906
@ Enum
The "enum" keyword.
Definition TypeBase.h:5920
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:560
@ Type
The name was classified as a type.
Definition Sema.h:562
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
@ TNK_Dependent_template_name
The name refers to a dependent template name:
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
@ TNK_Concept_template
The name refers to a concept.
@ TNK_Non_template
The name does not refer to a template.
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
const FunctionProtoType * T
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:366
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:414
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:418
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
SmallVector< Token, 4 > CachedTokens
A set of tokens that has been cached for later parsing.
Definition DeclSpec.h:1215
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
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:5881
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5902
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5895
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5899
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2247
CharacterLiteralKind
Definition Expr.h:1605
#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:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5367
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3264
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3281
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3246
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
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:11931
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:11927
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:11920
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:11917
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:11917
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12954
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13061
A stack object to be created when performing template instantiation.
Definition Sema.h:13145
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13305
NamedDecl * Previous
Definition Sema.h:353
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:1009