Thanks to visit codestin.com
Credit goes to clang.llvm.org

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