clang 24.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
24#include "clang/AST/Type.h"
33#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/Overload.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/Template.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SmallBitVector.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/SaveAndRestore.h"
49
50#include <optional>
51using namespace clang;
52using namespace sema;
53
54// Exported for use by Parser.
57 unsigned N) {
58 if (!N) return SourceRange();
59 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
60}
61
62unsigned Sema::getTemplateDepth(Scope *S) const {
63 unsigned Depth = 0;
64
65 // Each template parameter scope represents one level of template parameter
66 // depth.
67 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
68 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
69 ++Depth;
70 }
71
72 // Note that there are template parameters with the given depth.
73 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
74
75 // Look for parameters of an enclosing generic lambda. We don't create a
76 // template parameter scope for these.
78 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
79 if (!LSI->TemplateParams.empty()) {
80 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
81 break;
82 }
83 if (LSI->GLTemplateParameterList) {
84 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
85 break;
86 }
87 }
88 }
89
90 // Look for parameters of an enclosing terse function template. We don't
91 // create a template parameter scope for these either.
92 for (const InventedTemplateParameterInfo &Info :
94 if (!Info.TemplateParams.empty()) {
95 ParamsAtDepth(Info.AutoTemplateParameterDepth);
96 break;
97 }
98 }
99
100 return Depth;
101}
102
103/// \brief Determine whether the declaration found is acceptable as the name
104/// of a template and, if so, return that template declaration. Otherwise,
105/// returns null.
106///
107/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
108/// is true. In all other cases it will return a TemplateDecl (or null).
110 bool AllowFunctionTemplates,
111 bool AllowDependent) {
112 D = D->getUnderlyingDecl();
113
114 if (isa<TemplateDecl>(D)) {
115 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
116 return nullptr;
117
118 return D;
119 }
120
121 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
122 // C++ [temp.local]p1:
123 // Like normal (non-template) classes, class templates have an
124 // injected-class-name (Clause 9). The injected-class-name
125 // can be used with or without a template-argument-list. When
126 // it is used without a template-argument-list, it is
127 // equivalent to the injected-class-name followed by the
128 // template-parameters of the class template enclosed in
129 // <>. When it is used with a template-argument-list, it
130 // refers to the specified class template specialization,
131 // which could be the current specialization or another
132 // specialization.
133 if (Record->isInjectedClassName()) {
134 Record = cast<CXXRecordDecl>(Record->getDeclContext());
135 if (Record->getDescribedClassTemplate())
136 return Record->getDescribedClassTemplate();
137
138 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
139 return Spec->getSpecializedTemplate();
140 }
141
142 return nullptr;
143 }
144
145 // 'using Dependent::foo;' can resolve to a template name.
146 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
147 // injected-class-name).
148 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
149 return D;
150
151 return nullptr;
152}
153
155 bool AllowFunctionTemplates,
156 bool AllowDependent) {
157 LookupResult::Filter filter = R.makeFilter();
158 while (filter.hasNext()) {
159 NamedDecl *Orig = filter.next();
160 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
161 filter.erase();
162 }
163 filter.done();
164}
165
167 bool AllowFunctionTemplates,
168 bool AllowDependent,
169 bool AllowNonTemplateFunctions) {
170 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
171 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
172 return true;
173 if (AllowNonTemplateFunctions &&
174 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
175 return true;
176 }
177
178 return false;
179}
180
182Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
183 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
184 bool EnteringContext, TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool AllowTypoCorrection) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
194 TName = DeclarationName(Name.Identifier);
195 break;
196
198 TName = Context.DeclarationNames.getCXXOperatorName(
200 break;
201
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 &AssumedTemplate, AllowTypoCorrection))
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.
279 R.suppressDiagnostics();
280 } else {
281 if (!D) {
282 D = getAsTemplateNameDecl(*R.begin());
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.
306 R.suppressDiagnostics();
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.
344 R.suppressDiagnostics();
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
350 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
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>()->getDecl()->isEntityBeingDefined()) &&
411 "Caller should have completed object type");
412
413 // Template names cannot appear inside an Objective-C class or object type
414 // or a vector type.
415 //
416 // FIXME: This is wrong. For example:
417 //
418 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
419 // Vec<int> vi;
420 // vi.Vec<int>::~Vec<int>();
421 //
422 // ... should be accepted but we will not treat 'Vec' as a template name
423 // here. The right thing to do would be to check if the name is a valid
424 // vector component name, and look up a template name if not. And similarly
425 // for lookups into Objective-C class and object types, where the same
426 // problem can arise.
427 if (ObjectType->isObjCObjectOrInterfaceType() ||
428 ObjectType->isVectorType()) {
429 Found.clear();
430 return false;
431 }
432 } else if (SS.isNotEmpty()) {
433 // This nested-name-specifier occurs after another nested-name-specifier,
434 // so long into the context associated with the prior nested-name-specifier.
435 LookupCtx = computeDeclContext(SS, EnteringContext);
436 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
437
438 // The declaration context must be complete.
439 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
440 return true;
441 }
442
443 bool ObjectTypeSearchedInScope = false;
444 bool AllowFunctionTemplatesInLookup = true;
445 if (LookupCtx) {
446 // Perform "qualified" name lookup into the declaration context we
447 // computed, which is either the type of the base of a member access
448 // expression or the declaration context associated with a prior
449 // nested-name-specifier.
450 LookupQualifiedName(Found, LookupCtx);
451
452 // FIXME: The C++ standard does not clearly specify what happens in the
453 // case where the object type is dependent, and implementations vary. In
454 // Clang, we treat a name after a . or -> as a template-name if lookup
455 // finds a non-dependent member or member of the current instantiation that
456 // is a type template, or finds no such members and lookup in the context
457 // of the postfix-expression finds a type template. In the latter case, the
458 // name is nonetheless dependent, and we may resolve it to a member of an
459 // unknown specialization when we come to instantiate the template.
460 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
461 }
462
463 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
464 // C++ [basic.lookup.classref]p1:
465 // In a class member access expression (5.2.5), if the . or -> token is
466 // immediately followed by an identifier followed by a <, the
467 // identifier must be looked up to determine whether the < is the
468 // beginning of a template argument list (14.2) or a less-than operator.
469 // The identifier is first looked up in the class of the object
470 // expression. If the identifier is not found, it is then looked up in
471 // the context of the entire postfix-expression and shall name a class
472 // template.
473 if (S)
474 LookupName(Found, S);
475
476 if (!ObjectType.isNull()) {
477 // FIXME: We should filter out all non-type templates here, particularly
478 // variable templates and concepts. But the exclusion of alias templates
479 // and template template parameters is a wording defect.
480 AllowFunctionTemplatesInLookup = false;
481 ObjectTypeSearchedInScope = true;
482 }
483
484 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
485 }
486
487 if (Found.isAmbiguous())
488 return false;
489
490 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
491 !RequiredTemplate.hasTemplateKeyword()) {
492 // C++2a [temp.names]p2:
493 // A name is also considered to refer to a template if it is an
494 // unqualified-id followed by a < and name lookup finds either one or more
495 // functions or finds nothing.
496 //
497 // To keep our behavior consistent, we apply the "finds nothing" part in
498 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
499 // successfully form a call to an undeclared template-id.
500 bool AllFunctions =
501 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
503 });
504 if (AllFunctions || (Found.empty() && !IsDependent)) {
505 // If lookup found any functions, or if this is a name that can only be
506 // used for a function, then strongly assume this is a function
507 // template-id.
508 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
511 Found.clear();
512 return false;
513 }
514 }
515
516 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
517 // If we did not find any names, and this is not a disambiguation, attempt
518 // to correct any typos.
519 DeclarationName Name = Found.getLookupName();
520 Found.clear();
521
522 class TemplateNameLookupValidatorCCC final
524 public:
526
527 bool ValidateCandidate(const TypoCorrection &Candidate) final {
528 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
529 !ND || !isa<TemplateDecl>(ND))
530 return false;
532 }
533
534 std::unique_ptr<CorrectionCandidateCallback> clone() final {
535 return std::make_unique<TemplateNameLookupValidatorCCC>(*this);
536 }
537 };
538
539 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
540 FilterCCC.WantTypeSpecifiers = false;
541 FilterCCC.WantExpressionKeywords = false;
542 FilterCCC.WantRemainingKeywords = false;
543 FilterCCC.WantCXXNamedCasts = true;
544 if (TypoCorrection Corrected = CorrectTypo(
545 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
546 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
547 if (auto *ND = Corrected.getFoundDecl())
548 Found.addDecl(ND);
550 if (Found.isAmbiguous()) {
551 Found.clear();
552 } else if (!Found.empty()) {
553 // Do not erase the typo-corrected result to avoid duplicated
554 // diagnostics.
555 AllowFunctionTemplatesInLookup = true;
556 Found.setLookupName(Corrected.getCorrection());
557 if (LookupCtx) {
558 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
559 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
560 Name.getAsString() == CorrectedStr;
561 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
562 << Name << LookupCtx << DroppedSpecifier
563 << SS.getRange());
564 } else {
565 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
566 }
567
568 if (Corrected.WillReplaceSpecifier()) {
569 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
570 // In order to be valid, a non-empty CXXScopeSpec needs a source
571 // range.
572 SS.MakeTrivial(Context, NNS,
573 NNS ? Found.getNameLoc() : SourceRange());
574 }
575 }
576 }
577 }
578
579 NamedDecl *ExampleLookupResult =
580 Found.empty() ? nullptr : Found.getRepresentativeDecl();
581 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
582 if (Found.empty()) {
583 if (IsDependent) {
584 Found.setNotFoundInCurrentInstantiation();
585 return false;
586 }
587
588 // If a 'template' keyword was used, a lookup that finds only non-template
589 // names is an error.
590 if (ExampleLookupResult && RequiredTemplate) {
591 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
592 << Found.getLookupName() << SS.getRange()
593 << RequiredTemplate.hasTemplateKeyword()
594 << RequiredTemplate.getTemplateKeywordLoc();
595 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
596 diag::note_template_kw_refers_to_non_template)
597 << Found.getLookupName();
598 return true;
599 }
600
601 return false;
602 }
603
604 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
606 // C++03 [basic.lookup.classref]p1:
607 // [...] If the lookup in the class of the object expression finds a
608 // template, the name is also looked up in the context of the entire
609 // postfix-expression and [...]
610 //
611 // Note: C++11 does not perform this second lookup.
612 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
614 FoundOuter.setTemplateNameLookup(true);
615 LookupName(FoundOuter, S);
616 // FIXME: We silently accept an ambiguous lookup here, in violation of
617 // [basic.lookup]/1.
618 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
619
620 NamedDecl *OuterTemplate;
621 if (FoundOuter.empty()) {
622 // - if the name is not found, the name found in the class of the
623 // object expression is used, otherwise
624 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
625 !(OuterTemplate =
626 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
627 // - if the name is found in the context of the entire
628 // postfix-expression and does not name a class template, the name
629 // found in the class of the object expression is used, otherwise
630 FoundOuter.clear();
631 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
632 // - if the name found is a class template, it must refer to the same
633 // entity as the one found in the class of the object expression,
634 // otherwise the program is ill-formed.
635 if (!Found.isSingleResult() ||
636 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
637 OuterTemplate->getCanonicalDecl()) {
638 Diag(Found.getNameLoc(),
639 diag::ext_nested_name_member_ref_lookup_ambiguous)
640 << Found.getLookupName()
641 << ObjectType;
642 Diag(Found.getRepresentativeDecl()->getLocation(),
643 diag::note_ambig_member_ref_object_type)
644 << ObjectType;
645 Diag(FoundOuter.getFoundDecl()->getLocation(),
646 diag::note_ambig_member_ref_scope);
647
648 // Recover by taking the template that we found in the object
649 // expression's type.
650 }
651 }
652 }
653
654 return false;
655}
656
660 if (TemplateName.isInvalid())
661 return;
662
663 DeclarationNameInfo NameInfo;
664 CXXScopeSpec SS;
665 LookupNameKind LookupKind;
666
667 DeclContext *LookupCtx = nullptr;
668 NamedDecl *Found = nullptr;
669 bool MissingTemplateKeyword = false;
670
671 // Figure out what name we looked up.
672 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
673 NameInfo = DRE->getNameInfo();
674 SS.Adopt(DRE->getQualifierLoc());
675 LookupKind = LookupOrdinaryName;
676 Found = DRE->getFoundDecl();
677 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
678 NameInfo = ME->getMemberNameInfo();
679 SS.Adopt(ME->getQualifierLoc());
680 LookupKind = LookupMemberName;
681 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
682 Found = ME->getMemberDecl();
683 } else if (auto *DSDRE =
684 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
685 NameInfo = DSDRE->getNameInfo();
686 SS.Adopt(DSDRE->getQualifierLoc());
687 MissingTemplateKeyword = true;
688 } else if (auto *DSME =
689 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
690 NameInfo = DSME->getMemberNameInfo();
691 SS.Adopt(DSME->getQualifierLoc());
692 MissingTemplateKeyword = true;
693 } else {
694 llvm_unreachable("unexpected kind of potential template name");
695 }
696
697 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
698 // was missing.
699 if (MissingTemplateKeyword) {
700 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
701 << NameInfo.getName() << SourceRange(Less, Greater);
702 return;
703 }
704
705 // Try to correct the name by looking for templates and C++ named casts.
706 struct TemplateCandidateFilter : CorrectionCandidateCallback {
707 Sema &S;
708 TemplateCandidateFilter(Sema &S) : S(S) {
709 WantTypeSpecifiers = false;
710 WantExpressionKeywords = false;
711 WantRemainingKeywords = false;
712 WantCXXNamedCasts = true;
713 };
714 bool ValidateCandidate(const TypoCorrection &Candidate) override {
715 if (auto *ND = Candidate.getCorrectionDecl())
716 return S.getAsTemplateNameDecl(ND);
717 return Candidate.isKeyword();
718 }
719
720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
721 return std::make_unique<TemplateCandidateFilter>(*this);
722 }
723 };
724
725 DeclarationName Name = NameInfo.getName();
726 TemplateCandidateFilter CCC(*this);
727 if (TypoCorrection Corrected =
728 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
729 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
730 auto *ND = Corrected.getFoundDecl();
731 if (ND)
732 ND = getAsTemplateNameDecl(ND);
733 if (ND || Corrected.isKeyword()) {
734 if (LookupCtx) {
735 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
736 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
737 Name.getAsString() == CorrectedStr;
738 diagnoseTypo(Corrected,
739 PDiag(diag::err_non_template_in_member_template_id_suggest)
740 << Name << LookupCtx << DroppedSpecifier
741 << SS.getRange(), false);
742 } else {
743 diagnoseTypo(Corrected,
744 PDiag(diag::err_non_template_in_template_id_suggest)
745 << Name, false);
746 }
747 if (Found)
748 Diag(Found->getLocation(),
749 diag::note_non_template_in_template_id_found);
750 return;
751 }
752 }
753
754 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
755 << Name << SourceRange(Less, Greater);
756 if (Found)
757 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
758}
759
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 bool isAddressOfOperand,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 if (SS.isEmpty()) {
767 // FIXME: This codepath is only used by dependent unqualified names
768 // (e.g. a dependent conversion-function-id, or operator= once we support
769 // it). It doesn't quite do the right thing, and it will silently fail if
770 // getCurrentThisType() returns null.
771 QualType ThisType = getCurrentThisType();
772 if (ThisType.isNull())
773 return ExprError();
774
776 Context, /*Base=*/nullptr, ThisType,
777 /*IsArrow=*/!Context.getLangOpts().HLSL,
778 /*OperatorLoc=*/SourceLocation(),
779 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
780 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
781 }
782 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
783}
784
787 SourceLocation TemplateKWLoc,
788 const DeclarationNameInfo &NameInfo,
789 const TemplateArgumentListInfo *TemplateArgs) {
790 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
791 if (!SS.isValid())
792 return CreateRecoveryExpr(
793 SS.getBeginLoc(),
794 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
795
797 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
798 TemplateArgs);
799}
800
802Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
803 QualType ParamType, SourceLocation Loc,
805 UnsignedOrNone PackIndex, bool Final) {
806 // The template argument itself might be an expression, in which case we just
807 // return that expression. This happens when substituting into an alias
808 // template.
809 Expr *Replacement;
811 Replacement = Arg.getAsExpr();
812 } else {
813 ExprResult result =
814 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
815 if (result.isInvalid())
816 return ExprError();
817 Replacement = result.get();
818 }
819 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
820 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
821 AssociatedDecl, ParamType, Index, PackIndex, Final);
822}
823
825 NamedDecl *Instantiation,
826 bool InstantiatedFromMember,
827 const NamedDecl *Pattern,
828 const NamedDecl *PatternDef,
830 bool Complain, bool *Unreachable) {
831 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
832 isa<VarDecl>(Instantiation));
833
834 bool IsEntityBeingDefined = false;
835 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
836 IsEntityBeingDefined = TD->isBeingDefined();
837
838 if (PatternDef && !IsEntityBeingDefined) {
839 NamedDecl *SuggestedDef = nullptr;
840 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
841 &SuggestedDef,
842 /*OnlyNeedComplete*/ false)) {
843 if (Unreachable)
844 *Unreachable = true;
845 // If we're allowed to diagnose this and recover, do so.
846 bool Recover = Complain && !isSFINAEContext();
847 if (Complain)
848 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
850 return !Recover;
851 }
852 return false;
853 }
854
855 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
856 return true;
857
858 CanQualType InstantiationTy;
859 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
860 InstantiationTy = Context.getCanonicalTagType(TD);
861 if (PatternDef) {
862 Diag(PointOfInstantiation,
863 diag::err_template_instantiate_within_definition)
864 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
865 << InstantiationTy;
866 // Not much point in noting the template declaration here, since
867 // we're lexically inside it.
868 Instantiation->setInvalidDecl();
869 } else if (InstantiatedFromMember) {
870 if (isa<FunctionDecl>(Instantiation)) {
871 Diag(PointOfInstantiation,
872 diag::err_explicit_instantiation_undefined_member)
873 << /*member function*/ 1 << Instantiation->getDeclName()
874 << Instantiation->getDeclContext();
875 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
876 } else {
877 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
878 Diag(PointOfInstantiation,
879 diag::err_implicit_instantiate_member_undefined)
880 << InstantiationTy;
881 Diag(Pattern->getLocation(), diag::note_member_declared_at);
882 }
883 } else {
884 if (isa<FunctionDecl>(Instantiation)) {
885 Diag(PointOfInstantiation,
886 diag::err_explicit_instantiation_undefined_func_template)
887 << Pattern;
888 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
889 } else if (isa<TagDecl>(Instantiation)) {
890 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
891 << (TSK != TSK_ImplicitInstantiation)
892 << InstantiationTy;
893 NoteTemplateLocation(*Pattern);
894 } else {
895 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
896 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
897 Diag(PointOfInstantiation,
898 diag::err_explicit_instantiation_undefined_var_template)
899 << Instantiation;
900 Instantiation->setInvalidDecl();
901 } else
902 Diag(PointOfInstantiation,
903 diag::err_explicit_instantiation_undefined_member)
904 << /*static data member*/ 2 << Instantiation->getDeclName()
905 << Instantiation->getDeclContext();
906 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
907 }
908 }
909
910 // In general, Instantiation isn't marked invalid to get more than one
911 // error for multiple undefined instantiations. But the code that does
912 // explicit declaration -> explicit definition conversion can't handle
913 // invalid declarations, so mark as invalid in that case.
915 Instantiation->setInvalidDecl();
916 return true;
917}
918
920 bool SupportedForCompatibility) {
921 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
922
923 // C++23 [temp.local]p6:
924 // The name of a template-parameter shall not be bound to any following.
925 // declaration whose locus is contained by the scope to which the
926 // template-parameter belongs.
927 //
928 // When MSVC compatibility is enabled, the diagnostic is always a warning
929 // by default. Otherwise, it an error unless SupportedForCompatibility is
930 // true, in which case it is a default-to-error warning.
931 unsigned DiagId =
932 getLangOpts().MSVCCompat
933 ? diag::ext_template_param_shadow
934 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
935 : diag::err_template_param_shadow);
936 const auto *ND = cast<NamedDecl>(PrevDecl);
937 Diag(Loc, DiagId) << ND->getDeclName();
939}
940
942 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
943 D = Temp->getTemplatedDecl();
944 return Temp;
945 }
946 return nullptr;
947}
948
950 SourceLocation EllipsisLoc) const {
951 assert(Kind == Template &&
952 "Only template template arguments can be pack expansions here");
953 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
954 "Template template argument pack expansion without packs");
956 Result.EllipsisLoc = EllipsisLoc;
957 return Result;
958}
959
961 const ParsedTemplateArgument &Arg) {
962
963 switch (Arg.getKind()) {
965 TypeSourceInfo *TSI;
966 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);
967 if (!TSI)
968 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
970 }
971
973 Expr *E = Arg.getAsExpr();
974 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
975 }
976
979 TemplateArgument TArg;
980 if (Arg.getEllipsisLoc().isValid())
981 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
982 else
983 TArg = Template;
984 return TemplateArgumentLoc(
985 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
987 Arg.getNameLoc(), Arg.getEllipsisLoc());
988 }
989 }
990
991 llvm_unreachable("Unhandled parsed template argument");
992}
993
995 TemplateArgumentListInfo &TemplateArgs) {
996 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
997 TemplateArgs.addArgument(translateTemplateArgument(*this,
998 TemplateArgsIn[I]));
999}
1000
1002 SourceLocation Loc,
1003 const IdentifierInfo *Name) {
1004 NamedDecl *PrevDecl =
1005 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
1007 if (PrevDecl && PrevDecl->isTemplateParameter())
1008 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1009}
1010
1012 TypeSourceInfo *TInfo;
1013 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
1014 if (T.isNull())
1015 return ParsedTemplateArgument();
1016 assert(TInfo && "template argument with no location");
1017
1018 // If we might have formed a deduced template specialization type, convert
1019 // it to a template template argument.
1020 if (getLangOpts().CPlusPlus17) {
1021 TypeLoc TL = TInfo->getTypeLoc();
1022 SourceLocation EllipsisLoc;
1023 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1024 EllipsisLoc = PET.getEllipsisLoc();
1025 TL = PET.getPatternLoc();
1026 }
1027
1028 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1029 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1030 CXXScopeSpec SS;
1031 SS.Adopt(DTST.getQualifierLoc());
1032 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1033 TemplateTy::make(Name),
1034 DTST.getTemplateNameLoc());
1035 if (EllipsisLoc.isValid())
1036 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1037 return Result;
1038 }
1039 }
1040
1041 // This is a normal type template argument. Note, if the type template
1042 // argument is an injected-class-name for a template, it has a dual nature
1043 // and can be used as either a type or a template. We handle that in
1044 // convertTypeTemplateArgumentToTemplate.
1046 ParsedType.get().getAsOpaquePtr(),
1047 TInfo->getTypeLoc().getBeginLoc());
1048}
1049
1051 SourceLocation EllipsisLoc,
1052 SourceLocation KeyLoc,
1053 IdentifierInfo *ParamName,
1054 SourceLocation ParamNameLoc,
1055 unsigned Depth, unsigned Position,
1056 SourceLocation EqualLoc,
1057 ParsedType DefaultArg,
1058 bool HasTypeConstraint) {
1059 assert(S->isTemplateParamScope() &&
1060 "Template type parameter not in template parameter scope!");
1061
1062 bool IsParameterPack = EllipsisLoc.isValid();
1064 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1065 KeyLoc, ParamNameLoc, Depth, Position,
1066 ParamName, Typename, IsParameterPack,
1067 HasTypeConstraint);
1068 Param->setAccess(AS_public);
1069
1070 if (Param->isParameterPack())
1071 if (auto *CSI = getEnclosingLambdaOrBlock())
1072 CSI->LocalPacks.push_back(Param);
1073
1074 if (ParamName) {
1075 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1076
1077 // Add the template parameter into the current scope.
1078 S->AddDecl(Param);
1079 IdResolver.AddDecl(Param);
1080 }
1081
1082 // C++0x [temp.param]p9:
1083 // A default template-argument may be specified for any kind of
1084 // template-parameter that is not a template parameter pack.
1085 if (DefaultArg && IsParameterPack) {
1086 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1087 DefaultArg = nullptr;
1088 }
1089
1090 // Handle the default argument, if provided.
1091 if (DefaultArg) {
1092 TypeSourceInfo *DefaultTInfo;
1093 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1094
1095 assert(DefaultTInfo && "expected source information for type");
1096
1097 // Check for unexpanded parameter packs.
1098 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1100 return Param;
1101
1102 // Check the template argument itself.
1103 if (CheckTemplateArgument(DefaultTInfo)) {
1104 Param->setInvalidDecl();
1105 return Param;
1106 }
1107
1108 Param->setDefaultArgument(
1109 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1110 }
1111
1112 return Param;
1113}
1114
1115/// Convert the parser's template argument list representation into our form.
1118 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1119 TemplateId.RAngleLoc);
1120 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1121 TemplateId.NumArgs);
1122 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1123 return TemplateArgs;
1124}
1125
1127
1128 TemplateName TN = TypeConstr->Template.get();
1129 NamedDecl *CD = nullptr;
1130 bool IsTypeConcept = false;
1131 bool RequiresArguments = false;
1132 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1133 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1134 RequiresArguments =
1135 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1136 CD = TTP;
1137 } else {
1138 CD = TN.getAsTemplateDecl();
1139 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1140 RequiresArguments = cast<ConceptDecl>(CD)
1141 ->getTemplateParameters()
1142 ->getMinRequiredArguments() > 1;
1143 }
1144
1145 // C++2a [temp.param]p4:
1146 // [...] The concept designated by a type-constraint shall be a type
1147 // concept ([temp.concept]).
1148 if (!IsTypeConcept) {
1149 Diag(TypeConstr->TemplateNameLoc,
1150 diag::err_type_constraint_non_type_concept);
1151 return true;
1152 }
1153
1154 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1155 return true;
1156
1157 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1158
1159 if (!WereArgsSpecified && RequiresArguments) {
1160 Diag(TypeConstr->TemplateNameLoc,
1161 diag::err_type_constraint_missing_arguments)
1162 << CD;
1163 return true;
1164 }
1165 return false;
1166}
1167
1169 TemplateIdAnnotation *TypeConstr,
1170 TemplateTypeParmDecl *ConstrainedParameter,
1171 SourceLocation EllipsisLoc) {
1172 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1173 false);
1174}
1175
1177 TemplateIdAnnotation *TypeConstr,
1178 TemplateTypeParmDecl *ConstrainedParameter,
1179 SourceLocation EllipsisLoc,
1180 bool AllowUnexpandedPack) {
1181
1182 if (CheckTypeConstraint(TypeConstr))
1183 return true;
1184
1185 TemplateName TN = TypeConstr->Template.get();
1188
1189 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1190 TypeConstr->TemplateNameLoc);
1191
1192 TemplateArgumentListInfo TemplateArgs;
1193 if (TypeConstr->LAngleLoc.isValid()) {
1194 TemplateArgs =
1195 makeTemplateArgumentListInfo(*this, *TypeConstr);
1196
1197 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1198 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1200 return true;
1201 }
1202 }
1203 }
1204 return AttachTypeConstraint(
1206 ConceptName, TN,
1207 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
1208 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1209 ConstrainedParameter, EllipsisLoc);
1210}
1211
1212template <typename ArgumentLocAppender>
1215 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1216 SourceLocation RAngleLoc, QualType ConstrainedType,
1217 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1218 SourceLocation EllipsisLoc) {
1219
1220 TemplateArgumentListInfo ConstraintArgs;
1221 ConstraintArgs.addArgument(
1223 /*NTTPType=*/QualType(), ParamNameLoc));
1224
1225 ConstraintArgs.setRAngleLoc(RAngleLoc);
1226 ConstraintArgs.setLAngleLoc(LAngleLoc);
1227 Appender(ConstraintArgs);
1228
1229 // C++2a [temp.param]p4:
1230 // [...] This constraint-expression E is called the immediately-declared
1231 // constraint of T. [...]
1232 CXXScopeSpec SS;
1233 SS.Adopt(NS);
1234 ExprResult ImmediatelyDeclaredConstraint;
1235 if (auto *CD =
1236 dyn_cast_if_present<ConceptDecl>(NamedConcept.getAsTemplateDecl())) {
1237 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1238 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1239 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,
1240 /*DoCheckConstraintSatisfaction=*/
1242 }
1243 // We have a template template parameter
1244 else {
1245 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1246 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1247 NameInfo, NamedConcept, &ConstraintArgs);
1248 }
1249 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1250 return ImmediatelyDeclaredConstraint;
1251
1252 // C++2a [temp.param]p4:
1253 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1254 //
1255 // We have the following case:
1256 //
1257 // template<typename T> concept C1 = true;
1258 // template<C1... T> struct s1;
1259 //
1260 // The constraint: (C1<T> && ...)
1261 //
1262 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1263 // any unqualified lookups for 'operator&&' here.
1264 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1265 /*LParenLoc=*/SourceLocation(),
1266 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1267 EllipsisLoc, /*RHS=*/nullptr,
1268 /*RParenLoc=*/SourceLocation(),
1269 /*NumExpansions=*/std::nullopt);
1270}
1271
1273 DeclarationNameInfo NameInfo,
1274 TemplateName NamedConcept, NamedDecl *FoundDecl,
1275 const TemplateArgumentListInfo *TemplateArgs,
1276 TemplateTypeParmDecl *ConstrainedParameter,
1277 SourceLocation EllipsisLoc) {
1278 // C++2a [temp.param]p4:
1279 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1280 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1281 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1283 *TemplateArgs) : nullptr;
1284
1285 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1286
1287 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1288 *this, NS, NameInfo, NamedConcept, FoundDecl,
1289 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1290 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1291 ParamAsArgument, ConstrainedParameter->getLocation(),
1292 [&](TemplateArgumentListInfo &ConstraintArgs) {
1293 if (TemplateArgs)
1294 for (const auto &ArgLoc : TemplateArgs->arguments())
1295 ConstraintArgs.addArgument(ArgLoc);
1296 },
1297 EllipsisLoc);
1298 if (ImmediatelyDeclaredConstraint.isInvalid())
1299 return true;
1300
1301 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1302 /*TemplateKWLoc=*/SourceLocation{},
1303 /*ConceptNameInfo=*/NameInfo,
1304 /*FoundDecl=*/FoundDecl,
1305 /*NamedConcept=*/NamedConcept,
1306 /*ArgsWritten=*/ArgsAsWritten);
1307 ConstrainedParameter->setTypeConstraint(
1308 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1309 return false;
1310}
1311
1313 NonTypeTemplateParmDecl *NewConstrainedParm,
1314 NonTypeTemplateParmDecl *OrigConstrainedParm,
1315 SourceLocation EllipsisLoc) {
1316 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1318 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1319 diag::err_unsupported_placeholder_constraint)
1320 << NewConstrainedParm->getTypeSourceInfo()
1321 ->getTypeLoc()
1322 .getSourceRange();
1323 NewConstrainedParm->setType(TL.getType());
1324 return true;
1325 }
1326 // FIXME: Concepts: This should be the type of the placeholder, but this is
1327 // unclear in the wording right now.
1328 DeclRefExpr *Ref =
1329 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1330 VK_PRValue, OrigConstrainedParm->getLocation());
1331 if (!Ref)
1332 return true;
1333 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1335 TL.getNamedConcept(),
1336 /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1337 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1338 [&](TemplateArgumentListInfo &ConstraintArgs) {
1339 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1340 ConstraintArgs.addArgument(TL.getArgLoc(I));
1341 },
1342 EllipsisLoc);
1343 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1344 !ImmediatelyDeclaredConstraint.isUsable())
1345 return true;
1346
1347 NewConstrainedParm->setPlaceholderTypeConstraint(
1348 ImmediatelyDeclaredConstraint.get());
1349 return false;
1350}
1351
1353 SourceLocation Loc) {
1354 if (TSI->getType()->isUndeducedType()) {
1355 // C++17 [temp.dep.expr]p3:
1356 // An id-expression is type-dependent if it contains
1357 // - an identifier associated by name lookup with a non-type
1358 // template-parameter declared with a type that contains a
1359 // placeholder type (7.1.7.4),
1361 if (!NewTSI)
1362 return QualType();
1363 TSI = NewTSI;
1364 }
1365
1366 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1367}
1368
1370 if (T->isDependentType())
1371 return false;
1372
1373 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1374 return true;
1375
1376 if (T->isStructuralType())
1377 return false;
1378
1379 // Structural types are required to be object types or lvalue references.
1380 if (T->isRValueReferenceType()) {
1381 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1382 return true;
1383 }
1384
1385 // Don't mention structural types in our diagnostic prior to C++20. Also,
1386 // there's not much more we can say about non-scalar non-class types --
1387 // because we can't see functions or arrays here, those can only be language
1388 // extensions.
1389 if (!getLangOpts().CPlusPlus20 ||
1390 (!T->isScalarType() && !T->isRecordType())) {
1391 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1392 return true;
1393 }
1394
1395 // Structural types are required to be literal types.
1396 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1397 return true;
1398
1399 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1400
1401 // Drill down into the reason why the class is non-structural.
1402 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1403 // All members are required to be public and non-mutable, and can't be of
1404 // rvalue reference type. Check these conditions first to prefer a "local"
1405 // reason over a more distant one.
1406 for (const FieldDecl *FD : RD->fields()) {
1407 if (FD->getAccess() != AS_public) {
1408 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1409 return true;
1410 }
1411 if (FD->isMutable()) {
1412 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1413 return true;
1414 }
1415 if (FD->getType()->isRValueReferenceType()) {
1416 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1417 << T;
1418 return true;
1419 }
1420 }
1421
1422 // All bases are required to be public.
1423 for (const auto &BaseSpec : RD->bases()) {
1424 if (BaseSpec.getAccessSpecifier() != AS_public) {
1425 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1426 << T << 1;
1427 return true;
1428 }
1429 }
1430
1431 // All subobjects are required to be of structural types.
1432 SourceLocation SubLoc;
1433 QualType SubType;
1434 int Kind = -1;
1435
1436 for (const FieldDecl *FD : RD->fields()) {
1437 QualType T = Context.getBaseElementType(FD->getType());
1438 if (!T->isStructuralType()) {
1439 SubLoc = FD->getLocation();
1440 SubType = T;
1441 Kind = 0;
1442 break;
1443 }
1444 }
1445
1446 if (Kind == -1) {
1447 for (const auto &BaseSpec : RD->bases()) {
1448 QualType T = BaseSpec.getType();
1449 if (!T->isStructuralType()) {
1450 SubLoc = BaseSpec.getBaseTypeLoc();
1451 SubType = T;
1452 Kind = 1;
1453 break;
1454 }
1455 }
1456 }
1457
1458 assert(Kind != -1 && "couldn't find reason why type is not structural");
1459 Diag(SubLoc, diag::note_not_structural_subobject)
1460 << T << Kind << SubType;
1461 T = SubType;
1462 RD = T->getAsCXXRecordDecl();
1463 }
1464
1465 return true;
1466}
1467
1469 SourceLocation Loc) {
1470 // We don't allow variably-modified types as the type of non-type template
1471 // parameters.
1472 if (T->isVariablyModifiedType()) {
1473 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1474 << T;
1475 return QualType();
1476 }
1477
1478 if (T->isBlockPointerType()) {
1479 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1480 return QualType();
1481 }
1482
1483 // C++ [temp.param]p4:
1484 //
1485 // A non-type template-parameter shall have one of the following
1486 // (optionally cv-qualified) types:
1487 //
1488 // -- integral or enumeration type,
1489 if (T->isIntegralOrEnumerationType() ||
1490 // -- pointer to object or pointer to function,
1491 T->isPointerType() ||
1492 // -- lvalue reference to object or lvalue reference to function,
1493 T->isLValueReferenceType() ||
1494 // -- pointer to member,
1495 T->isMemberPointerType() ||
1496 // -- std::nullptr_t, or
1497 T->isNullPtrType() ||
1498 // -- a type that contains a placeholder type.
1499 T->isUndeducedType()) {
1500 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1501 // are ignored when determining its type.
1502 return T.getUnqualifiedType();
1503 }
1504
1505 // C++ [temp.param]p8:
1506 //
1507 // A non-type template-parameter of type "array of T" or
1508 // "function returning T" is adjusted to be of type "pointer to
1509 // T" or "pointer to function returning T", respectively.
1510 if (T->isArrayType() || T->isFunctionType())
1511 return Context.getDecayedType(T);
1512
1513 // If T is a dependent type, we can't do the check now, so we
1514 // assume that it is well-formed. Note that stripping off the
1515 // qualifiers here is not really correct if T turns out to be
1516 // an array type, but we'll recompute the type everywhere it's
1517 // used during instantiation, so that should be OK. (Using the
1518 // qualified type is equally wrong.)
1519 if (T->isDependentType())
1520 return T.getUnqualifiedType();
1521
1522 // C++20 [temp.param]p6:
1523 // -- a structural type
1524 if (RequireStructuralType(T, Loc))
1525 return QualType();
1526
1527 if (!getLangOpts().CPlusPlus20) {
1528 // FIXME: Consider allowing structural types as an extension in C++17. (In
1529 // earlier language modes, the template argument evaluation rules are too
1530 // inflexible.)
1531 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1532 return QualType();
1533 }
1534
1535 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1536 return T.getUnqualifiedType();
1537}
1538
1540 unsigned Depth,
1541 unsigned Position,
1542 SourceLocation EqualLoc,
1543 Expr *Default) {
1545
1546 // Check that we have valid decl-specifiers specified.
1547 auto CheckValidDeclSpecifiers = [this, &D] {
1548 // C++ [temp.param]
1549 // p1
1550 // template-parameter:
1551 // ...
1552 // parameter-declaration
1553 // p2
1554 // ... A storage class shall not be specified in a template-parameter
1555 // declaration.
1556 // [dcl.typedef]p1:
1557 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1558 // of a parameter-declaration
1559 const DeclSpec &DS = D.getDeclSpec();
1560 auto EmitDiag = [this](SourceLocation Loc) {
1561 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1563 };
1565 EmitDiag(DS.getStorageClassSpecLoc());
1566
1568 EmitDiag(DS.getThreadStorageClassSpecLoc());
1569
1570 // [dcl.inline]p1:
1571 // The inline specifier can be applied only to the declaration or
1572 // definition of a variable or function.
1573
1574 if (DS.isInlineSpecified())
1575 EmitDiag(DS.getInlineSpecLoc());
1576
1577 // [dcl.constexpr]p1:
1578 // The constexpr specifier shall be applied only to the definition of a
1579 // variable or variable template or the declaration of a function or
1580 // function template.
1581
1582 if (DS.hasConstexprSpecifier())
1583 EmitDiag(DS.getConstexprSpecLoc());
1584
1585 // [dcl.fct.spec]p1:
1586 // Function-specifiers can be used only in function declarations.
1587
1588 if (DS.isVirtualSpecified())
1589 EmitDiag(DS.getVirtualSpecLoc());
1590
1591 if (DS.hasExplicitSpecifier())
1592 EmitDiag(DS.getExplicitSpecLoc());
1593
1594 if (DS.isNoreturnSpecified())
1595 EmitDiag(DS.getNoreturnSpecLoc());
1596 };
1597
1598 CheckValidDeclSpecifiers();
1599
1600 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1601 if (isa<AutoType>(T))
1603 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1604 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1605
1606 assert(S->isTemplateParamScope() &&
1607 "Non-type template parameter not in template parameter scope!");
1608 bool Invalid = false;
1609
1611 if (T.isNull()) {
1612 T = Context.IntTy; // Recover with an 'int' type.
1613 Invalid = true;
1614 }
1615
1617
1618 const IdentifierInfo *ParamName = D.getIdentifier();
1619 bool IsParameterPack = D.hasEllipsis();
1621 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1622 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1623 TInfo);
1624 Param->setAccess(AS_public);
1625
1627 if (TL.isConstrained()) {
1628 if (D.getEllipsisLoc().isInvalid() &&
1629 T->containsUnexpandedParameterPack()) {
1630 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1631 for (auto &Loc :
1632 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1635 }
1636 if (!Invalid &&
1637 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1638 Invalid = true;
1639 }
1640
1641 if (Invalid)
1642 Param->setInvalidDecl();
1643
1644 if (Param->isParameterPack())
1645 if (auto *CSI = getEnclosingLambdaOrBlock())
1646 CSI->LocalPacks.push_back(Param);
1647
1648 if (ParamName) {
1650 ParamName);
1651
1652 // Add the template parameter into the current scope.
1653 S->AddDecl(Param);
1654 IdResolver.AddDecl(Param);
1655 }
1656
1657 // C++0x [temp.param]p9:
1658 // A default template-argument may be specified for any kind of
1659 // template-parameter that is not a template parameter pack.
1660 if (Default && IsParameterPack) {
1661 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1662 Default = nullptr;
1663 }
1664
1665 // Check the well-formedness of the default template argument, if provided.
1666 if (Default) {
1667 // Check for unexpanded parameter packs.
1669 return Param;
1670
1671 Param->setDefaultArgument(
1673 TemplateArgument(Default, /*IsCanonical=*/false),
1674 QualType(), SourceLocation()));
1675 }
1676
1677 return Param;
1678}
1679
1680/// ActOnTemplateTemplateParameter - Called when a C++ template template
1681/// parameter (e.g. T in template <template <typename> class T> class array)
1682/// has been parsed. S is the current scope.
1684 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1685 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1686 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1687 unsigned Position, SourceLocation EqualLoc,
1689 assert(S->isTemplateParamScope() &&
1690 "Template template parameter not in template parameter scope!");
1691
1692 bool IsParameterPack = EllipsisLoc.isValid();
1693
1694 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1695 if (Params->size() == 0) {
1696 Diag(Loc, diag::err_template_template_parm_no_parms)
1697 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1698
1699 // Recover as if there was a type template parameter pack.
1700 SmallVector<NamedDecl *, 4> ParamDecls;
1701 ParamDecls.push_back(TemplateTypeParmDecl::Create(
1702 Context, Context.getTranslationUnitDecl(), Loc, SourceLocation(),
1703 Depth + 1, 0, /*Id=*/nullptr,
1704 /*Typename=*/false, /*ParameterPack=*/true));
1706 Context, Params->getTemplateLoc(), Params->getLAngleLoc(), ParamDecls,
1707 Params->getRAngleLoc(), Params->getRequiresClause());
1708 }
1709
1710 bool Invalid = false;
1712 Params,
1713 /*OldParams=*/nullptr,
1714 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1715 Invalid = true;
1716
1717 // Construct the parameter object.
1719 Context, Context.getTranslationUnitDecl(), Loc, Depth, Position,
1720 IsParameterPack, Name, Kind, Typename, Params);
1721 Param->setAccess(AS_public);
1722
1723 if (Param->isParameterPack())
1724 if (auto *LSI = getEnclosingLambdaOrBlock())
1725 LSI->LocalPacks.push_back(Param);
1726
1727 // If the template template parameter has a name, then link the identifier
1728 // into the scope and lookup mechanisms.
1729 if (Name) {
1730 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1731
1732 S->AddDecl(Param);
1733 IdResolver.AddDecl(Param);
1734 }
1735
1736 if (Invalid)
1737 Param->setInvalidDecl();
1738
1739 // C++0x [temp.param]p9:
1740 // A default template-argument may be specified for any kind of
1741 // template-parameter that is not a template parameter pack.
1742 if (IsParameterPack && !Default.isInvalid()) {
1743 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1745 }
1746
1747 if (!Default.isInvalid()) {
1748 // Check only that we have a template template argument. We don't want to
1749 // try to check well-formedness now, because our template template parameter
1750 // might have dependent types in its template parameters, which we wouldn't
1751 // be able to match now.
1752 //
1753 // If none of the template template parameter's template arguments mention
1754 // other template parameters, we could actually perform more checking here.
1755 // However, it isn't worth doing.
1757 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1758 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1759 << DefaultArg.getSourceRange();
1760 return Param;
1761 }
1762
1763 TemplateName Name =
1766 if (Template &&
1768 return Param;
1769 }
1770
1771 // Check for unexpanded parameter packs.
1773 DefaultArg.getArgument().getAsTemplate(),
1775 return Param;
1776
1777 Param->setDefaultArgument(Context, DefaultArg);
1778 }
1779
1780 return Param;
1781}
1782
1783namespace {
1784class ConstraintRefersToContainingTemplateChecker
1786 using inherited = ConstDynamicRecursiveASTVisitor;
1787 bool Result = false;
1788 const FunctionDecl *Friend = nullptr;
1789 unsigned TemplateDepth = 0;
1790
1791 // Check a record-decl that we've seen to see if it is a lexical parent of the
1792 // Friend, likely because it was referred to without its template arguments.
1793 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1794 CheckingRD = CheckingRD->getMostRecentDecl();
1795 if (!CheckingRD->isTemplated())
1796 return true;
1797
1798 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1799 DC && !DC->isFileContext(); DC = DC->getParent())
1800 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1801 if (CheckingRD == RD->getMostRecentDecl()) {
1802 Result = true;
1803 return false;
1804 }
1805
1806 return true;
1807 }
1808
1809 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1810 if (D->getDepth() < TemplateDepth)
1811 Result = true;
1812
1813 // Necessary because the type of the NTTP might be what refers to the parent
1814 // constriant.
1815 return TraverseType(D->getType());
1816 }
1817
1818public:
1819 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1820 unsigned TemplateDepth)
1821 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1822
1823 bool getResult() const { return Result; }
1824
1825 // This should be the only template parm type that we have to deal with.
1826 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1827 // FunctionParmPackExpr are all partially substituted, which cannot happen
1828 // with concepts at this point in translation.
1829 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1830 if (Type->getDecl()->getDepth() < TemplateDepth) {
1831 Result = true;
1832 return false;
1833 }
1834 return true;
1835 }
1836
1837 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1838 return TraverseDecl(E->getDecl());
1839 }
1840
1841 bool TraverseTypedefType(const TypedefType *TT,
1842 bool /*TraverseQualifier*/) override {
1843 return TraverseType(TT->desugar());
1844 }
1845
1846 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1847 // We don't care about TypeLocs. So traverse Types instead.
1848 return TraverseType(TL.getType(), TraverseQualifier);
1849 }
1850
1851 bool VisitTagType(const TagType *T) override {
1852 return TraverseDecl(T->getDecl());
1853 }
1854
1855 bool TraverseDecl(const Decl *D) override {
1856 assert(D);
1857 // FIXME : This is possibly an incomplete list, but it is unclear what other
1858 // Decl kinds could be used to refer to the template parameters. This is a
1859 // best guess so far based on examples currently available, but the
1860 // unreachable should catch future instances/cases.
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1862 return TraverseType(TD->getUnderlyingType());
1863 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1864 return CheckNonTypeTemplateParmDecl(NTTPD);
1865 if (auto *VD = dyn_cast<ValueDecl>(D))
1866 return TraverseType(VD->getType());
1867 if (isa<TemplateDecl>(D))
1868 return true;
1869 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1870 return CheckIfContainingRecord(RD);
1871
1873 // No direct types to visit here I believe.
1874 } else
1875 llvm_unreachable("Don't know how to handle this declaration type yet");
1876 return true;
1877 }
1878};
1879} // namespace
1880
1882 const FunctionDecl *Friend, unsigned TemplateDepth,
1883 const Expr *Constraint) {
1884 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1885 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1886 Checker.TraverseStmt(Constraint);
1887 return Checker.getResult();
1888}
1889
1892 SourceLocation ExportLoc,
1893 SourceLocation TemplateLoc,
1894 SourceLocation LAngleLoc,
1895 ArrayRef<NamedDecl *> Params,
1896 SourceLocation RAngleLoc,
1897 Expr *RequiresClause) {
1898 if (ExportLoc.isValid())
1899 Diag(ExportLoc, diag::warn_template_export_unsupported);
1900
1901 for (NamedDecl *P : Params)
1903
1904 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1905 llvm::ArrayRef(Params), RAngleLoc,
1906 RequiresClause);
1907}
1908
1910 const CXXScopeSpec &SS) {
1911 if (SS.isSet())
1912 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1913}
1914
1915// Returns the template parameter list with all default template argument
1916// information.
1918 // Make sure we get the template parameter list from the most
1919 // recent declaration, since that is the only one that is guaranteed to
1920 // have all the default template argument information.
1921 Decl *D = TD->getMostRecentDecl();
1922 // C++11 N3337 [temp.param]p12:
1923 // A default template argument shall not be specified in a friend class
1924 // template declaration.
1925 //
1926 // Skip past friend *declarations* because they are not supposed to contain
1927 // default template arguments. Moreover, these declarations may introduce
1928 // template parameters living in different template depths than the
1929 // corresponding template parameters in TD, causing unmatched constraint
1930 // substitution.
1931 //
1932 // FIXME: Diagnose such cases within a class template:
1933 // template <class T>
1934 // struct S {
1935 // template <class = void> friend struct C;
1936 // };
1937 // template struct S<int>;
1939 D->getPreviousDecl())
1940 D = D->getPreviousDecl();
1941 return cast<TemplateDecl>(D)->getTemplateParameters();
1942}
1943
1945 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1946 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1947 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1948 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1949 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1950 TemplateParameterList **OuterTemplateParamLists,
1951 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1952 assert(TemplateParams && TemplateParams->size() > 0 &&
1953 "No template parameters");
1954 assert(TUK != TagUseKind::Reference &&
1955 "Can only declare or define class templates");
1956 bool Invalid = false;
1957
1958 // Check that we can declare a template here.
1959 if (CheckTemplateDeclScope(S, TemplateParams))
1960 return true;
1961
1963 assert(Kind != TagTypeKind::Enum &&
1964 "can't build template of enumerated type");
1965
1966 // There is no such thing as an unnamed class template.
1967 if (!Name) {
1968 Diag(KWLoc, diag::err_template_unnamed_class);
1969 return true;
1970 }
1971
1972 // Find any previous declaration with this name. For a friend with no
1973 // scope explicitly specified, we only look for tag declarations (per
1974 // C++11 [basic.lookup.elab]p2).
1975 DeclContext *SemanticContext;
1976 LookupResult Previous(*this, Name, NameLoc,
1977 (SS.isEmpty() && TUK == TagUseKind::Friend)
1981 if (SS.isNotEmpty() && !SS.isInvalid()) {
1982 SemanticContext = computeDeclContext(SS, true);
1983 if (!SemanticContext) {
1984 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
1985 << SS.getScopeRep() << SS.getRange();
1986 return true;
1987 }
1988
1989 if (RequireCompleteDeclContext(SS, SemanticContext))
1990 return true;
1991
1992 // If we're adding a template to a dependent context, we may need to
1993 // rebuilding some of the types used within the template parameter list,
1994 // now that we know what the current instantiation is.
1995 if (SemanticContext->isDependentContext()) {
1996 ContextRAII SavedContext(*this, SemanticContext);
1998 Invalid = true;
1999 }
2000
2001 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2002 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
2003 /*TemplateId=*/nullptr,
2004 IsMemberSpecialization))
2005 return true;
2006
2007 LookupQualifiedName(Previous, SemanticContext);
2008 } else {
2009 SemanticContext = CurContext;
2010
2011 // C++14 [class.mem]p14:
2012 // If T is the name of a class, then each of the following shall have a
2013 // name different from T:
2014 // -- every member template of class T
2015 if (TUK != TagUseKind::Friend &&
2016 DiagnoseClassNameShadow(SemanticContext,
2017 DeclarationNameInfo(Name, NameLoc)))
2018 return true;
2019
2020 LookupName(Previous, S);
2021 }
2022
2023 if (Previous.isAmbiguous())
2024 return true;
2025
2026 // Let the template parameter scope enter the lookup chain of the current
2027 // class template. For example, given
2028 //
2029 // namespace ns {
2030 // template <class> bool Param = false;
2031 // template <class T> struct N;
2032 // }
2033 //
2034 // template <class Param> struct ns::N { void foo(Param); };
2035 //
2036 // When we reference Param inside the function parameter list, our name lookup
2037 // chain for it should be like:
2038 // FunctionScope foo
2039 // -> RecordScope N
2040 // -> TemplateParamScope (where we will find Param)
2041 // -> NamespaceScope ns
2042 //
2043 // See also CppLookupName().
2044 if (S->isTemplateParamScope())
2045 EnterTemplatedContext(S, SemanticContext);
2046
2047 NamedDecl *PrevDecl = nullptr;
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050
2051 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2052 // Maybe we will complain about the shadowed template parameter.
2053 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2054 // Just pretend that we didn't see the previous declaration.
2055 PrevDecl = nullptr;
2056 }
2057
2058 // If there is a previous declaration with the same name, check
2059 // whether this is a valid redeclaration.
2060 ClassTemplateDecl *PrevClassTemplate =
2061 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
2062
2063 // We may have found the injected-class-name of a class template,
2064 // class template partial specialization, or class template specialization.
2065 // In these cases, grab the template that is being defined or specialized.
2066 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
2067 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
2068 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
2069 PrevClassTemplate
2070 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
2071 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
2072 PrevClassTemplate
2074 ->getSpecializedTemplate();
2075 }
2076 }
2077
2078 if (TUK == TagUseKind::Friend) {
2079 // C++ [namespace.memdef]p3:
2080 // [...] When looking for a prior declaration of a class or a function
2081 // declared as a friend, and when the name of the friend class or
2082 // function is neither a qualified name nor a template-id, scopes outside
2083 // the innermost enclosing namespace scope are not considered.
2084 if (!SS.isSet()) {
2085 DeclContext *OutermostContext = CurContext;
2086 while (!OutermostContext->isFileContext())
2087 OutermostContext = OutermostContext->getLookupParent();
2088
2089 if (PrevDecl &&
2090 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2091 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2092 SemanticContext = PrevDecl->getDeclContext();
2093 } else {
2094 // Declarations in outer scopes don't matter. However, the outermost
2095 // context we computed is the semantic context for our new
2096 // declaration.
2097 PrevDecl = PrevClassTemplate = nullptr;
2098 SemanticContext = OutermostContext;
2099
2100 // Check that the chosen semantic context doesn't already contain a
2101 // declaration of this name as a non-tag type.
2103 DeclContext *LookupContext = SemanticContext;
2104 while (LookupContext->isTransparentContext())
2105 LookupContext = LookupContext->getLookupParent();
2106 LookupQualifiedName(Previous, LookupContext);
2107
2108 if (Previous.isAmbiguous())
2109 return true;
2110
2111 if (Previous.begin() != Previous.end())
2112 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2113 }
2114 }
2115 } else if (PrevDecl &&
2116 !isTagRedeclarationInScope(Previous.getRepresentativeDecl(),
2117 SemanticContext, S, SS.isValid()))
2118 PrevDecl = PrevClassTemplate = nullptr;
2119
2120 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2121 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2122 if (SS.isEmpty() &&
2123 !(PrevClassTemplate &&
2124 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2125 SemanticContext->getRedeclContext()))) {
2126 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2127 Diag(Shadow->getTargetDecl()->getLocation(),
2128 diag::note_using_decl_target);
2129 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2130 // Recover by ignoring the old declaration.
2131 PrevDecl = PrevClassTemplate = nullptr;
2132 }
2133 }
2134
2135 if (PrevClassTemplate) {
2136 // Ensure that the template parameter lists are compatible. Skip this check
2137 // for a friend in a dependent context: the template parameter list itself
2138 // could be dependent.
2139 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2141 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2142 : CurContext,
2143 CurContext, KWLoc),
2144 TemplateParams, PrevClassTemplate,
2145 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2147 return true;
2148
2149 // C++ [temp.class]p4:
2150 // In a redeclaration, partial specialization, explicit
2151 // specialization or explicit instantiation of a class template,
2152 // the class-key shall agree in kind with the original class
2153 // template declaration (7.1.5.3).
2154 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2156 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2157 Diag(KWLoc, diag::err_use_with_wrong_tag)
2158 << Name
2159 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2160 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2161 Kind = PrevRecordDecl->getTagKind();
2162 }
2163
2164 // Check for redefinition of this class template.
2165 if (TUK == TagUseKind::Definition) {
2166 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2167 // If we have a prior definition that is not visible, treat this as
2168 // simply making that previous definition visible.
2169 NamedDecl *Hidden = nullptr;
2170 bool HiddenDefVisible = false;
2171 if (SkipBody &&
2172 isRedefinitionAllowedFor(Def, NameLoc, &Hidden, HiddenDefVisible)) {
2173 SkipBody->ShouldSkip = true;
2174 SkipBody->Previous = Def;
2175 if (!HiddenDefVisible && Hidden) {
2176 auto *Tmpl =
2177 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2178 assert(Tmpl && "original definition of a class template is not a "
2179 "class template?");
2182 }
2183 } else {
2184 Diag(NameLoc, diag::err_redefinition) << Name;
2185 Diag(Def->getLocation(), diag::note_previous_definition);
2186 // FIXME: Would it make sense to try to "forget" the previous
2187 // definition, as part of error recovery?
2188 return true;
2189 }
2190 }
2191 }
2192 } else if (PrevDecl) {
2193 // C++ [temp]p5:
2194 // A class template shall not have the same name as any other
2195 // template, class, function, object, enumeration, enumerator,
2196 // namespace, or type in the same scope (3.3), except as specified
2197 // in (14.5.4).
2198 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2199 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2200 return true;
2201 }
2202
2203 // Check the template parameter list of this declaration, possibly
2204 // merging in the template parameter list from the previous class
2205 // template declaration. Skip this check for a friend in a dependent
2206 // context, because the template parameter list might be dependent.
2207 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2209 TemplateParams,
2210 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2211 : nullptr,
2212 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2213 SemanticContext->isDependentContext())
2216 : TPC_Other,
2217 SkipBody))
2218 Invalid = true;
2219
2220 if (SS.isSet()) {
2221 // If the name of the template was qualified, we must be defining the
2222 // template out-of-line.
2223 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2224 return Diag(NameLoc, TUK == TagUseKind::Friend
2225 ? diag::err_friend_decl_does_not_match
2226 : diag::err_member_decl_does_not_match)
2227 << Name << SemanticContext << /*IsDefinition*/ true
2228 << SS.getRange();
2229 }
2230
2231 // If this is a templated friend in a dependent context we should not put it
2232 // on the redecl chain. In some cases, the templated friend can be the most
2233 // recent declaration tricking the template instantiator to make substitutions
2234 // there.
2235 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2236 bool ShouldAddRedecl =
2237 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2238
2240 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2241 PrevClassTemplate && ShouldAddRedecl
2242 ? PrevClassTemplate->getTemplatedDecl()
2243 : nullptr);
2244 SetNestedNameSpecifier(*this, NewClass, SS);
2245 if (NumOuterTemplateParamLists > 0)
2247 Context,
2248 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2249
2250 // Add alignment attributes if necessary; these attributes are checked when
2251 // the ASTContext lays out the structure.
2252 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2253 if (LangOpts.HLSL)
2254 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2257 }
2258
2259 ClassTemplateDecl *NewTemplate
2260 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2261 DeclarationName(Name), TemplateParams,
2262 NewClass);
2263
2264 if (ShouldAddRedecl)
2265 NewTemplate->setPreviousDecl(PrevClassTemplate);
2266
2267 NewClass->setDescribedClassTemplate(NewTemplate);
2268
2269 if (ModulePrivateLoc.isValid())
2270 NewTemplate->setModulePrivate();
2271
2272 if (IsMemberSpecialization) {
2273 assert(PrevClassTemplate &&
2274 "Member specialization without a primary template?");
2275 NewTemplate->setMemberSpecialization();
2276 }
2277
2278 // Set the access specifier.
2279 if (!Invalid && TUK != TagUseKind::Friend &&
2280 NewTemplate->getDeclContext()->isRecord())
2281 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2282
2283 // Set the lexical context of these templates
2285 NewTemplate->setLexicalDeclContext(CurContext);
2286
2287 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2288 NewClass->startDefinition();
2289
2290 ProcessDeclAttributeList(S, NewClass, Attr);
2291
2292 if (PrevClassTemplate) {
2293 mergeDeclAttributes(NewTemplate, PrevClassTemplate);
2294 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2295 }
2296
2300
2301 if (TUK != TagUseKind::Friend) {
2302 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2303 Scope *Outer = S;
2304 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2305 Outer = Outer->getParent();
2306 PushOnScopeChains(NewTemplate, Outer);
2307 } else {
2308 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2309 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2310 NewClass->setAccess(PrevClassTemplate->getAccess());
2311 }
2312
2313 NewTemplate->setObjectOfFriendDecl();
2314
2315 // Friend templates are visible in fairly strange ways.
2316 if (!CurContext->isDependentContext()) {
2317 DeclContext *DC = SemanticContext->getRedeclContext();
2318 DC->makeDeclVisibleInContext(NewTemplate);
2319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2320 PushOnScopeChains(NewTemplate, EnclosingScope,
2321 /* AddToContext = */ false);
2322 }
2323
2325 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2326 Friend->setAccess(AS_public);
2327 CurContext->addDecl(Friend);
2328 }
2329
2330 if (PrevClassTemplate)
2331 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2332
2333 if (Invalid) {
2334 NewTemplate->setInvalidDecl();
2335 NewClass->setInvalidDecl();
2336 }
2337
2338 ActOnDocumentableDecl(NewTemplate);
2339
2340 if (SkipBody && SkipBody->ShouldSkip)
2341 return SkipBody->Previous;
2342
2343 return NewTemplate;
2344}
2345
2346/// Diagnose the presence of a default template argument on a
2347/// template parameter, which is ill-formed in certain contexts.
2348///
2349/// \returns true if the default template argument should be dropped.
2352 SourceLocation ParamLoc,
2353 SourceRange DefArgRange) {
2354 switch (TPC) {
2355 case Sema::TPC_Other:
2357 return false;
2358
2361 // C++ [temp.param]p9:
2362 // A default template-argument shall not be specified in a
2363 // function template declaration or a function template
2364 // definition [...]
2365 // If a friend function template declaration specifies a default
2366 // template-argument, that declaration shall be a definition and shall be
2367 // the only declaration of the function template in the translation unit.
2368 // (C++98/03 doesn't have this wording; see DR226).
2369 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2370 << DefArgRange;
2371 return false;
2372
2374 // C++0x [temp.param]p9:
2375 // A default template-argument shall not be specified in the
2376 // template-parameter-lists of the definition of a member of a
2377 // class template that appears outside of the member's class.
2378 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2379 << DefArgRange;
2380 return true;
2381
2384 // C++ [temp.param]p9:
2385 // A default template-argument shall not be specified in a
2386 // friend template declaration.
2387 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2388 << DefArgRange;
2389 return true;
2390
2391 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2392 // for friend function templates if there is only a single
2393 // declaration (and it is a definition). Strange!
2394 }
2395
2396 llvm_unreachable("Invalid TemplateParamListContext!");
2397}
2398
2399/// Check for unexpanded parameter packs within the template parameters
2400/// of a template template parameter, recursively.
2403 // A template template parameter which is a parameter pack is also a pack
2404 // expansion.
2405 if (TTP->isParameterPack())
2406 return false;
2407
2409 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2410 NamedDecl *P = Params->getParam(I);
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2412 if (!TTP->isParameterPack())
2413 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2414 if (TC->hasExplicitTemplateArgs())
2415 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2418 return true;
2419 continue;
2420 }
2421
2422 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2423 if (!NTTP->isParameterPack() &&
2424 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2425 NTTP->getTypeSourceInfo(),
2427 return true;
2428
2429 continue;
2430 }
2431
2432 if (TemplateTemplateParmDecl *InnerTTP
2433 = dyn_cast<TemplateTemplateParmDecl>(P))
2434 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2435 return true;
2436 }
2437
2438 return false;
2439}
2440
2442 TemplateParameterList *OldParams,
2444 SkipBodyInfo *SkipBody) {
2445 bool Invalid = false;
2446
2447 // C++ [temp.param]p10:
2448 // The set of default template-arguments available for use with a
2449 // template declaration or definition is obtained by merging the
2450 // default arguments from the definition (if in scope) and all
2451 // declarations in scope in the same way default function
2452 // arguments are (8.3.6).
2453 bool SawDefaultArgument = false;
2454 SourceLocation PreviousDefaultArgLoc;
2455
2456 // Dummy initialization to avoid warnings.
2457 TemplateParameterList::iterator OldParam = NewParams->end();
2458 if (OldParams)
2459 OldParam = OldParams->begin();
2460
2461 bool RemoveDefaultArguments = false;
2462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2463 NewParamEnd = NewParams->end();
2464 NewParam != NewParamEnd; ++NewParam) {
2465 // Whether we've seen a duplicate default argument in the same translation
2466 // unit.
2467 bool RedundantDefaultArg = false;
2468 // Whether we've found inconsis inconsitent default arguments in different
2469 // translation unit.
2470 bool InconsistentDefaultArg = false;
2471 // The name of the module which contains the inconsistent default argument.
2472 std::string PrevModuleName;
2473
2474 SourceLocation OldDefaultLoc;
2475 SourceLocation NewDefaultLoc;
2476
2477 // Variable used to diagnose missing default arguments
2478 bool MissingDefaultArg = false;
2479
2480 // Variable used to diagnose non-final parameter packs
2481 bool SawParameterPack = false;
2482
2483 if (TemplateTypeParmDecl *NewTypeParm
2484 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2485 // Check the presence of a default argument here.
2486 if (NewTypeParm->hasDefaultArgument() &&
2488 *this, TPC, NewTypeParm->getLocation(),
2489 NewTypeParm->getDefaultArgument().getSourceRange()))
2490 NewTypeParm->removeDefaultArgument();
2491
2492 // Merge default arguments for template type parameters.
2493 TemplateTypeParmDecl *OldTypeParm
2494 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2495 if (NewTypeParm->isParameterPack()) {
2496 assert(!NewTypeParm->hasDefaultArgument() &&
2497 "Parameter packs can't have a default argument!");
2498 SawParameterPack = true;
2499 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2500 NewTypeParm->hasDefaultArgument() &&
2501 (!SkipBody || !SkipBody->ShouldSkip)) {
2502 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2503 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2504 SawDefaultArgument = true;
2505
2506 if (!OldTypeParm->getOwningModule())
2507 RedundantDefaultArg = true;
2508 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2509 NewTypeParm)) {
2510 InconsistentDefaultArg = true;
2511 PrevModuleName =
2513 }
2514 PreviousDefaultArgLoc = NewDefaultLoc;
2515 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2516 // Merge the default argument from the old declaration to the
2517 // new declaration.
2518 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2519 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2520 } else if (NewTypeParm->hasDefaultArgument()) {
2521 SawDefaultArgument = true;
2522 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2523 } else if (SawDefaultArgument)
2524 MissingDefaultArg = true;
2525 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2526 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2527 // Check for unexpanded parameter packs, except in a template template
2528 // parameter pack, as in those any unexpanded packs should be expanded
2529 // along with the parameter itself.
2531 !NewNonTypeParm->isParameterPack() &&
2532 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2533 NewNonTypeParm->getTypeSourceInfo(),
2535 Invalid = true;
2536 continue;
2537 }
2538
2539 // Check the presence of a default argument here.
2540 if (NewNonTypeParm->hasDefaultArgument() &&
2542 *this, TPC, NewNonTypeParm->getLocation(),
2543 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2544 NewNonTypeParm->removeDefaultArgument();
2545 }
2546
2547 // Merge default arguments for non-type template parameters
2548 NonTypeTemplateParmDecl *OldNonTypeParm
2549 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2550 if (NewNonTypeParm->isParameterPack()) {
2551 assert(!NewNonTypeParm->hasDefaultArgument() &&
2552 "Parameter packs can't have a default argument!");
2553 if (!NewNonTypeParm->isPackExpansion())
2554 SawParameterPack = true;
2555 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2556 NewNonTypeParm->hasDefaultArgument() &&
2557 (!SkipBody || !SkipBody->ShouldSkip)) {
2558 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2559 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2560 SawDefaultArgument = true;
2561 if (!OldNonTypeParm->getOwningModule())
2562 RedundantDefaultArg = true;
2563 else if (!getASTContext().isSameDefaultTemplateArgument(
2564 OldNonTypeParm, NewNonTypeParm)) {
2565 InconsistentDefaultArg = true;
2566 PrevModuleName =
2567 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2568 }
2569 PreviousDefaultArgLoc = NewDefaultLoc;
2570 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2571 // Merge the default argument from the old declaration to the
2572 // new declaration.
2573 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2574 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2575 } else if (NewNonTypeParm->hasDefaultArgument()) {
2576 SawDefaultArgument = true;
2577 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2578 } else if (SawDefaultArgument)
2579 MissingDefaultArg = true;
2580 } else {
2581 TemplateTemplateParmDecl *NewTemplateParm
2582 = cast<TemplateTemplateParmDecl>(*NewParam);
2583
2584 // Check for unexpanded parameter packs, recursively.
2585 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2586 Invalid = true;
2587 continue;
2588 }
2589
2590 // Check the presence of a default argument here.
2591 if (NewTemplateParm->hasDefaultArgument() &&
2593 NewTemplateParm->getLocation(),
2594 NewTemplateParm->getDefaultArgument().getSourceRange()))
2595 NewTemplateParm->removeDefaultArgument();
2596
2597 // Merge default arguments for template template parameters
2598 TemplateTemplateParmDecl *OldTemplateParm
2599 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2600 if (NewTemplateParm->isParameterPack()) {
2601 assert(!NewTemplateParm->hasDefaultArgument() &&
2602 "Parameter packs can't have a default argument!");
2603 if (!NewTemplateParm->isPackExpansion())
2604 SawParameterPack = true;
2605 } else if (OldTemplateParm &&
2606 hasVisibleDefaultArgument(OldTemplateParm) &&
2607 NewTemplateParm->hasDefaultArgument() &&
2608 (!SkipBody || !SkipBody->ShouldSkip)) {
2609 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2610 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2611 SawDefaultArgument = true;
2612 if (!OldTemplateParm->getOwningModule())
2613 RedundantDefaultArg = true;
2614 else if (!getASTContext().isSameDefaultTemplateArgument(
2615 OldTemplateParm, NewTemplateParm)) {
2616 InconsistentDefaultArg = true;
2617 PrevModuleName =
2618 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2619 }
2620 PreviousDefaultArgLoc = NewDefaultLoc;
2621 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2622 // Merge the default argument from the old declaration to the
2623 // new declaration.
2624 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2625 PreviousDefaultArgLoc
2626 = OldTemplateParm->getDefaultArgument().getLocation();
2627 } else if (NewTemplateParm->hasDefaultArgument()) {
2628 SawDefaultArgument = true;
2629 PreviousDefaultArgLoc
2630 = NewTemplateParm->getDefaultArgument().getLocation();
2631 } else if (SawDefaultArgument)
2632 MissingDefaultArg = true;
2633 }
2634
2635 // C++11 [temp.param]p11:
2636 // If a template parameter of a primary class template or alias template
2637 // is a template parameter pack, it shall be the last template parameter.
2638 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2639 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2640 Diag((*NewParam)->getLocation(),
2641 diag::err_template_param_pack_must_be_last_template_parameter);
2642 Invalid = true;
2643 }
2644
2645 // [basic.def.odr]/13:
2646 // There can be more than one definition of a
2647 // ...
2648 // default template argument
2649 // ...
2650 // in a program provided that each definition appears in a different
2651 // translation unit and the definitions satisfy the [same-meaning
2652 // criteria of the ODR].
2653 //
2654 // Simply, the design of modules allows the definition of template default
2655 // argument to be repeated across translation unit. Note that the ODR is
2656 // checked elsewhere. But it is still not allowed to repeat template default
2657 // argument in the same translation unit.
2658 if (RedundantDefaultArg) {
2659 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2660 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2661 Invalid = true;
2662 } else if (InconsistentDefaultArg) {
2663 // We could only diagnose about the case that the OldParam is imported.
2664 // The case NewParam is imported should be handled in ASTReader.
2665 Diag(NewDefaultLoc,
2666 diag::err_template_param_default_arg_inconsistent_redefinition);
2667 Diag(OldDefaultLoc,
2668 diag::note_template_param_prev_default_arg_in_other_module)
2669 << PrevModuleName;
2670 Invalid = true;
2671 } else if (MissingDefaultArg &&
2672 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2673 TPC == TPC_FriendClassTemplate)) {
2674 // C++ 23[temp.param]p14:
2675 // If a template-parameter of a class template, variable template, or
2676 // alias template has a default template argument, each subsequent
2677 // template-parameter shall either have a default template argument
2678 // supplied or be a template parameter pack.
2679 Diag((*NewParam)->getLocation(),
2680 diag::err_template_param_default_arg_missing);
2681 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2682 Invalid = true;
2683 RemoveDefaultArguments = true;
2684 }
2685
2686 // If we have an old template parameter list that we're merging
2687 // in, move on to the next parameter.
2688 if (OldParams)
2689 ++OldParam;
2690 }
2691
2692 // We were missing some default arguments at the end of the list, so remove
2693 // all of the default arguments.
2694 if (RemoveDefaultArguments) {
2695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2696 NewParamEnd = NewParams->end();
2697 NewParam != NewParamEnd; ++NewParam) {
2698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2699 TTP->removeDefaultArgument();
2700 else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2702 NTTP->removeDefaultArgument();
2703 else
2704 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2705 }
2706 }
2707
2708 return Invalid;
2709}
2710
2711namespace {
2712
2713/// A class which looks for a use of a certain level of template
2714/// parameter.
2715struct DependencyChecker : DynamicRecursiveASTVisitor {
2716 unsigned Depth;
2717
2718 // Whether we're looking for a use of a template parameter that makes the
2719 // overall construct type-dependent / a dependent type. This is strictly
2720 // best-effort for now; we may fail to match at all for a dependent type
2721 // in some cases if this is set.
2722 bool IgnoreNonTypeDependent;
2723
2724 bool Match;
2725 SourceLocation MatchLoc;
2726
2727 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2728 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2729 Match(false) {}
2730
2731 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2732 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2733 NamedDecl *ND = Params->getParam(0);
2734 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2735 Depth = PD->getDepth();
2736 } else if (NonTypeTemplateParmDecl *PD =
2737 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2738 Depth = PD->getDepth();
2739 } else {
2740 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2741 }
2742 }
2743
2744 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2745 if (ParmDepth >= Depth) {
2746 Match = true;
2747 MatchLoc = Loc;
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 bool TraverseStmt(Stmt *S) override {
2754 // Prune out non-type-dependent expressions if requested. This can
2755 // sometimes result in us failing to find a template parameter reference
2756 // (if a value-dependent expression creates a dependent type), but this
2757 // mode is best-effort only.
2758 if (auto *E = dyn_cast_or_null<Expr>(S))
2759 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2760 return true;
2762 }
2763
2764 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2765 if (IgnoreNonTypeDependent && !TL.isNull() &&
2766 !TL.getType()->isDependentType())
2767 return true;
2768 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2769 }
2770
2771 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2772 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2773 }
2774
2775 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2776 // For a best-effort search, keep looking until we find a location.
2777 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2778 }
2779
2780 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2781 if (TemplateTemplateParmDecl *PD =
2782 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2783 if (Matches(PD->getDepth()))
2784 return false;
2786 TraverseQualifier);
2787 }
2788
2789 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2790 if (NonTypeTemplateParmDecl *PD =
2791 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2792 if (Matches(PD->getDepth(), E->getExprLoc()))
2793 return false;
2794 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2795 }
2796
2797 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2798 if (Matches(E->getParameter()->getDepth(), E->getExprLoc()))
2799 return false;
2800 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(E);
2801 }
2802
2803 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2804 return TraverseType(T->getReplacementType());
2805 }
2806
2807 bool VisitSubstTemplateTypeParmPackType(
2808 SubstTemplateTypeParmPackType *T) override {
2809 return TraverseTemplateArgument(T->getArgumentPack());
2810 }
2811
2812 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2813 bool TraverseQualifier) override {
2814 // An InjectedClassNameType will never have a dependent template name,
2815 // so no need to traverse it.
2816 return TraverseTemplateArguments(
2817 T->getTemplateArgs(T->getDecl()->getASTContext()));
2818 }
2819};
2820} // end anonymous namespace
2821
2822/// Determines whether a given type depends on the given parameter
2823/// list.
2824static bool
2826 if (!Params->size())
2827 return false;
2828
2829 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2830 Checker.TraverseType(T);
2831 return Checker.Match;
2832}
2833
2834// Find the source range corresponding to the named type in the given
2835// nested-name-specifier, if any.
2837 QualType T,
2838 const CXXScopeSpec &SS) {
2840 for (;;) {
2843 break;
2844 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2845 return NNSLoc.castAsTypeLoc().getSourceRange();
2846 // FIXME: This will always be empty.
2847 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2848 }
2849
2850 return SourceRange();
2851}
2852
2854 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2855 TemplateIdAnnotation *TemplateId,
2856 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2857 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2858 IsMemberSpecialization = false;
2859 Invalid = false;
2860
2861 // The sequence of nested types to which we will match up the template
2862 // parameter lists. We first build this list by starting with the type named
2863 // by the nested-name-specifier and walking out until we run out of types.
2864 SmallVector<QualType, 4> NestedTypes;
2865 QualType T;
2866 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2867 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2868 if (CXXRecordDecl *Record =
2869 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2870 T = Context.getCanonicalTagType(Record);
2871 else
2872 T = QualType(Qualifier.getAsType(), 0);
2873 }
2874
2875 // If we found an explicit specialization that prevents us from needing
2876 // 'template<>' headers, this will be set to the location of that
2877 // explicit specialization.
2878 SourceLocation ExplicitSpecLoc;
2879
2880 while (!T.isNull()) {
2881 NestedTypes.push_back(T);
2882
2883 // Retrieve the parent of a record type.
2884 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2885 // If this type is an explicit specialization, we're done.
2887 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2889 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2890 ExplicitSpecLoc = Spec->getLocation();
2891 break;
2892 }
2893 } else if (Record->getTemplateSpecializationKind()
2895 ExplicitSpecLoc = Record->getLocation();
2896 break;
2897 }
2898
2899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2900 T = Context.getTypeDeclType(Parent);
2901 else
2902 T = QualType();
2903 continue;
2904 }
2905
2906 if (const TemplateSpecializationType *TST
2907 = T->getAs<TemplateSpecializationType>()) {
2908 TemplateName Name = TST->getTemplateName();
2909 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2910 // Look one step prior in a dependent template specialization type.
2911 if (NestedNameSpecifier NNS = DTS->getQualifier();
2913 T = QualType(NNS.getAsType(), 0);
2914 else
2915 T = QualType();
2916 continue;
2917 }
2918 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2919 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2920 T = Context.getTypeDeclType(Parent);
2921 else
2922 T = QualType();
2923 continue;
2924 }
2925 }
2926
2927 // Look one step prior in a dependent name type.
2928 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2929 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2931 T = QualType(NNS.getAsType(), 0);
2932 else
2933 T = QualType();
2934 continue;
2935 }
2936
2937 // Retrieve the parent of an enumeration type.
2938 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2939 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2940 // check here.
2941 EnumDecl *Enum = EnumT->getDecl();
2942
2943 // Get to the parent type.
2944 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2945 T = Context.getCanonicalTypeDeclType(Parent);
2946 else
2947 T = QualType();
2948 continue;
2949 }
2950
2951 T = QualType();
2952 }
2953 // Reverse the nested types list, since we want to traverse from the outermost
2954 // to the innermost while checking template-parameter-lists.
2955 std::reverse(NestedTypes.begin(), NestedTypes.end());
2956
2957 // C++0x [temp.expl.spec]p17:
2958 // A member or a member template may be nested within many
2959 // enclosing class templates. In an explicit specialization for
2960 // such a member, the member declaration shall be preceded by a
2961 // template<> for each enclosing class template that is
2962 // explicitly specialized.
2963 bool SawNonEmptyTemplateParameterList = false;
2964
2965 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2966 if (SawNonEmptyTemplateParameterList) {
2967 if (!SuppressDiagnostic)
2968 Diag(DeclLoc, diag::err_specialize_member_of_template)
2969 << !Recovery << Range;
2970 Invalid = true;
2971 IsMemberSpecialization = false;
2972 return true;
2973 }
2974
2975 return false;
2976 };
2977
2978 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2979 // Check that we can have an explicit specialization here.
2980 if (CheckExplicitSpecialization(Range, true))
2981 return true;
2982
2983 // We don't have a template header, but we should.
2984 SourceLocation ExpectedTemplateLoc;
2985 if (!ParamLists.empty())
2986 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2987 else
2988 ExpectedTemplateLoc = DeclStartLoc;
2989
2990 if (!SuppressDiagnostic)
2991 Diag(DeclLoc, diag::err_template_spec_needs_header)
2992 << Range
2993 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2994 return false;
2995 };
2996
2997 unsigned ParamIdx = 0;
2998 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2999 ++TypeIdx) {
3000 T = NestedTypes[TypeIdx];
3001
3002 // Whether we expect a 'template<>' header.
3003 bool NeedEmptyTemplateHeader = false;
3004
3005 // Whether we expect a template header with parameters.
3006 bool NeedNonemptyTemplateHeader = false;
3007
3008 // For a dependent type, the set of template parameters that we
3009 // expect to see.
3010 TemplateParameterList *ExpectedTemplateParams = nullptr;
3011
3012 // C++0x [temp.expl.spec]p15:
3013 // A member or a member template may be nested within many enclosing
3014 // class templates. In an explicit specialization for such a member, the
3015 // member declaration shall be preceded by a template<> for each
3016 // enclosing class template that is explicitly specialized.
3017 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3019 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3020 ExpectedTemplateParams = Partial->getTemplateParameters();
3021 NeedNonemptyTemplateHeader = true;
3022 } else if (Record->isDependentType()) {
3023 if (Record->getDescribedClassTemplate()) {
3024 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3025 ->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 }
3028 } else if (ClassTemplateSpecializationDecl *Spec
3029 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3030 // C++0x [temp.expl.spec]p4:
3031 // Members of an explicitly specialized class template are defined
3032 // in the same manner as members of normal classes, and not using
3033 // the template<> syntax.
3034 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3035 NeedEmptyTemplateHeader = true;
3036 else
3037 continue;
3038 } else if (Record->getTemplateSpecializationKind()) {
3039 if (Record->getTemplateSpecializationKind()
3041 TypeIdx == NumTypes - 1)
3042 IsMemberSpecialization = true;
3043
3044 continue;
3045 }
3046 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3047 TemplateName Name = TST->getTemplateName();
3048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3049 ExpectedTemplateParams = Template->getTemplateParameters();
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDependentTemplateName()) {
3052 NeedNonemptyTemplateHeader = true;
3053 } else if (Name.getAsDeducedTemplateName()) {
3054 // FIXME: We actually could/should check the template arguments here
3055 // against the corresponding template parameter list.
3056 NeedNonemptyTemplateHeader = false;
3057 }
3058 }
3059
3060 // C++ [temp.expl.spec]p16:
3061 // In an explicit specialization declaration for a member of a class
3062 // template or a member template that appears in namespace scope, the
3063 // member template and some of its enclosing class templates may remain
3064 // unspecialized, except that the declaration shall not explicitly
3065 // specialize a class member template if its enclosing class templates
3066 // are not explicitly specialized as well.
3067 if (ParamIdx < ParamLists.size()) {
3068 if (ParamLists[ParamIdx]->size() == 0) {
3069 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072 } else
3073 SawNonEmptyTemplateParameterList = true;
3074 }
3075
3076 if (NeedEmptyTemplateHeader) {
3077 // If we're on the last of the types, and we need a 'template<>' header
3078 // here, then it's a member specialization.
3079 if (TypeIdx == NumTypes - 1)
3080 IsMemberSpecialization = true;
3081
3082 if (ParamIdx < ParamLists.size()) {
3083 if (ParamLists[ParamIdx]->size() > 0) {
3084 // The header has template parameters when it shouldn't. Complain.
3085 if (!SuppressDiagnostic)
3086 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3087 diag::err_template_param_list_matches_nontemplate)
3088 << T
3089 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3090 ParamLists[ParamIdx]->getRAngleLoc())
3092 Invalid = true;
3093 return nullptr;
3094 }
3095
3096 // Consume this template header.
3097 ++ParamIdx;
3098 continue;
3099 }
3100
3101 if (!IsFriend)
3102 if (DiagnoseMissingExplicitSpecialization(
3104 return nullptr;
3105
3106 continue;
3107 }
3108
3109 if (NeedNonemptyTemplateHeader) {
3110 // In friend declarations we can have template-ids which don't
3111 // depend on the corresponding template parameter lists. But
3112 // assume that empty parameter lists are supposed to match this
3113 // template-id.
3114 if (IsFriend && T->isDependentType()) {
3115 if (ParamIdx < ParamLists.size() &&
3117 ExpectedTemplateParams = nullptr;
3118 else
3119 continue;
3120 }
3121
3122 if (ParamIdx < ParamLists.size()) {
3123 // Check the template parameter list, if we can.
3124 if (ExpectedTemplateParams &&
3126 ExpectedTemplateParams,
3127 !SuppressDiagnostic, TPL_TemplateMatch))
3128 Invalid = true;
3129
3130 if (!Invalid &&
3131 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3133 Invalid = true;
3134
3135 ++ParamIdx;
3136 continue;
3137 }
3138
3139 if (!SuppressDiagnostic)
3140 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3141 << T
3143 Invalid = true;
3144 continue;
3145 }
3146 }
3147
3148 // If there were at least as many template-ids as there were template
3149 // parameter lists, then there are no template parameter lists remaining for
3150 // the declaration itself.
3151 if (ParamIdx >= ParamLists.size()) {
3152 if (TemplateId && !IsFriend) {
3153 // We don't have a template header for the declaration itself, but we
3154 // should.
3155 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3156 TemplateId->RAngleLoc));
3157
3158 // Fabricate an empty template parameter list for the invented header.
3160 SourceLocation(), {},
3161 SourceLocation(), nullptr);
3162 }
3163
3164 return nullptr;
3165 }
3166
3167 // If there were too many template parameter lists, complain about that now.
3168 if (ParamIdx < ParamLists.size() - 1) {
3169 bool HasAnyExplicitSpecHeader = false;
3170 bool AllExplicitSpecHeaders = true;
3171 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3172 if (ParamLists[I]->size() == 0)
3173 HasAnyExplicitSpecHeader = true;
3174 else
3175 AllExplicitSpecHeaders = false;
3176 }
3177
3178 if (!SuppressDiagnostic)
3179 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3180 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3181 : diag::err_template_spec_extra_headers)
3182 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3183 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3184
3185 // If there was a specialization somewhere, such that 'template<>' is
3186 // not required, and there were any 'template<>' headers, note where the
3187 // specialization occurred.
3188 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3189 !SuppressDiagnostic)
3190 Diag(ExplicitSpecLoc,
3191 diag::note_explicit_template_spec_does_not_need_header)
3192 << NestedTypes.back();
3193
3194 // We have a template parameter list with no corresponding scope, which
3195 // means that the resulting template declaration can't be instantiated
3196 // properly (we'll end up with dependent nodes when we shouldn't).
3197 if (!AllExplicitSpecHeaders)
3198 Invalid = true;
3199 }
3200
3201 // C++ [temp.expl.spec]p16:
3202 // In an explicit specialization declaration for a member of a class
3203 // template or a member template that ap- pears in namespace scope, the
3204 // member template and some of its enclosing class templates may remain
3205 // unspecialized, except that the declaration shall not explicitly
3206 // specialize a class member template if its en- closing class templates
3207 // are not explicitly specialized as well.
3208 if (ParamLists.back()->size() == 0 &&
3209 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3210 false))
3211 return nullptr;
3212
3213 // Return the last template parameter list, which corresponds to the
3214 // entity being declared.
3215 return ParamLists.back();
3216}
3217
3219 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3220 Diag(Template->getLocation(), diag::note_template_declared_here)
3222 ? 0
3224 ? 1
3226 ? 2
3228 << Template->getDeclName();
3229 return;
3230 }
3231
3233 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3234 IEnd = OST->end();
3235 I != IEnd; ++I)
3236 Diag((*I)->getLocation(), diag::note_template_declared_here)
3237 << 0 << (*I)->getDeclName();
3238
3239 return;
3240 }
3241}
3242
3244 TemplateName BaseTemplate,
3245 SourceLocation TemplateLoc,
3247 auto lookUpCommonType = [&](TemplateArgument T1,
3248 TemplateArgument T2) -> QualType {
3249 // Don't bother looking for other specializations if both types are
3250 // builtins - users aren't allowed to specialize for them
3251 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3252 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3253 {T1, T2});
3254
3258 Args.addArgument(TemplateArgumentLoc(
3259 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3260
3261 EnterExpressionEvaluationContext UnevaluatedContext(
3263 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3265
3266 QualType BaseTemplateInst = S.CheckTemplateIdType(
3267 Keyword, BaseTemplate, TemplateLoc, Args,
3268 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3269
3270 if (SFINAE.hasErrorOccurred())
3271 return QualType();
3272
3273 return BaseTemplateInst;
3274 };
3275
3276 // Note A: For the common_type trait applied to a template parameter pack T of
3277 // types, the member type shall be either defined or not present as follows:
3278 switch (Ts.size()) {
3279
3280 // If sizeof...(T) is zero, there shall be no member type.
3281 case 0:
3282 return QualType();
3283
3284 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3285 // pack T. The member typedef-name type shall denote the same type, if any, as
3286 // common_type_t<T0, T0>; otherwise there shall be no member type.
3287 case 1:
3288 return lookUpCommonType(Ts[0], Ts[0]);
3289
3290 // If sizeof...(T) is two, let the first and second types constituting T be
3291 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3292 // as decay_t<T1> and decay_t<T2>, respectively.
3293 case 2: {
3294 QualType T1 = Ts[0].getAsType();
3295 QualType T2 = Ts[1].getAsType();
3296 QualType D1 = S.BuiltinDecay(T1, {});
3297 QualType D2 = S.BuiltinDecay(T2, {});
3298
3299 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3300 // the same type, if any, as common_type_t<D1, D2>.
3301 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3302 return lookUpCommonType(D1, D2);
3303
3304 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3305 // denotes a valid type, let C denote that type.
3306 {
3307 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3308 EnterExpressionEvaluationContext UnevaluatedContext(
3310 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3312
3313 // false
3315 VK_PRValue);
3316 ExprResult Cond = &CondExpr;
3317
3318 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3319 if (ConstRefQual) {
3320 D1.addConst();
3321 D2.addConst();
3322 }
3323
3324 // declval<D1>()
3325 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3326 ExprResult LHS = &LHSExpr;
3327
3328 // declval<D2>()
3329 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3330 ExprResult RHS = &RHSExpr;
3331
3334
3335 // decltype(false ? declval<D1>() : declval<D2>())
3337 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3338
3339 if (Result.isNull() || SFINAE.hasErrorOccurred())
3340 return QualType();
3341
3342 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3343 return S.BuiltinDecay(Result, TemplateLoc);
3344 };
3345
3346 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3347 return Res;
3348
3349 // Let:
3350 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3351 // COND-RES(X, Y) be
3352 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3353
3354 // C++20 only
3355 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3356 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3357 if (!S.Context.getLangOpts().CPlusPlus20)
3358 return QualType();
3359 return CheckConditionalOperands(true);
3360 }
3361 }
3362
3363 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3364 // denote the first, second, and (pack of) remaining types constituting T. Let
3365 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3366 // a type C, the member typedef-name type shall denote the same type, if any,
3367 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3368 default: {
3369 QualType Result = Ts.front().getAsType();
3370 for (auto T : llvm::drop_begin(Ts)) {
3371 Result = lookUpCommonType(Result, T.getAsType());
3372 if (Result.isNull())
3373 return QualType();
3374 }
3375 return Result;
3376 }
3377 }
3378}
3379
3380static bool isInVkNamespace(const RecordType *RT) {
3381 DeclContext *DC = RT->getDecl()->getDeclContext();
3382 if (!DC)
3383 return false;
3384
3385 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3386 if (!ND)
3387 return false;
3388
3389 return ND->getQualifiedNameAsString() == "hlsl::vk";
3390}
3391
3392static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3393 QualType OperandArg,
3394 SourceLocation Loc) {
3395 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3396 bool Literal = false;
3397 SourceLocation LiteralLoc;
3398 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3403 QualType ConstantType = LiteralArgs[0].getAsType();
3404 RT = ConstantType->getAsCanonical<RecordType>();
3405 Literal = true;
3406 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3407 }
3408
3409 if (RT && isInVkNamespace(RT) &&
3410 RT->getDecl()->getName() == "integral_constant") {
3411 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3412 assert(SpecDecl);
3413
3414 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3415
3416 QualType ConstantType = ConstantArgs[0].getAsType();
3417 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3418
3419 if (Literal)
3420 return SpirvOperand::createLiteral(Value);
3421 return SpirvOperand::createConstant(ConstantType, Value);
3422 } else if (Literal) {
3423 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3424 return SpirvOperand();
3425 }
3426 }
3427 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3428 diag::err_call_incomplete_argument))
3429 return SpirvOperand();
3430 return SpirvOperand::createType(OperandArg);
3431}
3432
3434 ArrayRef<TemplateArgument> InputArgs) {
3435 // FIXME: cache mangling globally?
3436 std::unique_ptr<MangleContext> MC(Context.createMangleContext());
3438 InputArgs.size());
3439 llvm::transform(InputArgs, SortedArgs.begin(),
3440 [&](const TemplateArgument &Arg) {
3441 assert(Arg.getKind() == TemplateArgument::Type);
3442 std::string MangledName;
3443 llvm::raw_string_ostream OS(MangledName);
3444 MC->mangleCanonicalTypeName(Arg.getAsType(), OS);
3445 return std::pair<std::string, TemplateArgument>(
3446 std::move(MangledName), Arg);
3447 });
3448 llvm::stable_sort(SortedArgs, llvm::less_first());
3449
3450 auto OutArgs = llvm::to_vector(llvm::make_second_range(SortedArgs));
3451 return Context.getSubstBuiltinTemplatePack(
3452 TemplateArgument::CreatePackCopy(Context, OutArgs));
3453}
3454
3457 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3458 TemplateArgumentListInfo &TemplateArgs) {
3459 ASTContext &Context = SemaRef.getASTContext();
3460
3461 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3462 "Builtin template arguments do not match its parameters");
3463
3464 switch (BTD->getBuiltinTemplateKind()) {
3465 case BTK__make_integer_seq: {
3466 // Specializations of __make_integer_seq<S, T, N> are treated like
3467 // S<T, 0, ..., N-1>.
3468
3469 QualType OrigType = Converted[1].getAsType();
3470 // C++14 [inteseq.intseq]p1:
3471 // T shall be an integer type.
3472 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3473 SemaRef.Diag(TemplateArgs[1].getLocation(),
3474 diag::err_integer_sequence_integral_element_type);
3475 return QualType();
3476 }
3477
3478 TemplateArgument NumArgsArg = Converted[2];
3479 if (NumArgsArg.isDependent())
3480 return QualType();
3481
3482 TemplateArgumentListInfo SyntheticTemplateArgs;
3483 // The type argument, wrapped in substitution sugar, gets reused as the
3484 // first template argument in the synthetic template argument list.
3485 SyntheticTemplateArgs.addArgument(
3488 OrigType, TemplateArgs[1].getLocation())));
3489
3490 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3491 // Expand N into 0 ... N-1.
3492 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3493 I < NumArgs; ++I) {
3494 TemplateArgument TA(Context, I, OrigType);
3495 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3496 TA, OrigType, TemplateArgs[2].getLocation()));
3497 }
3498 } else {
3499 // C++14 [inteseq.make]p1:
3500 // If N is negative the program is ill-formed.
3501 SemaRef.Diag(TemplateArgs[2].getLocation(),
3502 diag::err_integer_sequence_negative_length);
3503 return QualType();
3504 }
3505
3506 // The first template argument will be reused as the template decl that
3507 // our synthetic template arguments will be applied to.
3508 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3509 TemplateLoc, SyntheticTemplateArgs,
3510 /*Scope=*/nullptr,
3511 /*ForNestedNameSpecifier=*/false);
3512 }
3513
3514 case BTK__type_pack_element: {
3515 // Specializations of
3516 // __type_pack_element<Index, T_1, ..., T_N>
3517 // are treated like T_Index.
3518 assert(Converted.size() == 2 &&
3519 "__type_pack_element should be given an index and a parameter pack");
3520
3521 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3522 if (IndexArg.isDependent() || Ts.isDependent())
3523 return QualType();
3524
3525 llvm::APSInt Index = IndexArg.getAsIntegral();
3526 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3527 "type std::size_t, and hence be non-negative");
3528 // If the Index is out of bounds, the program is ill-formed.
3529 if (Index >= Ts.pack_size()) {
3530 SemaRef.Diag(TemplateArgs[0].getLocation(),
3531 diag::err_type_pack_element_out_of_bounds);
3532 return QualType();
3533 }
3534
3535 // We simply return the type at index `Index`.
3536 int64_t N = Index.getExtValue();
3537 return Ts.getPackAsArray()[N].getAsType();
3538 }
3539
3540 case BTK__builtin_common_type: {
3541 assert(Converted.size() == 4);
3542 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3543 return QualType();
3544
3545 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3546 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3547 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3548 TemplateLoc, Ts);
3549 !CT.isNull()) {
3553 CT, TemplateArgs[1].getLocation())));
3554 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3555 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3556 TAs, /*Scope=*/nullptr,
3557 /*ForNestedNameSpecifier=*/false);
3558 }
3559 QualType HasNoTypeMember = Converted[2].getAsType();
3560 return HasNoTypeMember;
3561 }
3562
3563 case BTK__hlsl_spirv_type: {
3564 assert(Converted.size() == 4);
3565
3566 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3567 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3568 }
3569
3570 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3571 return QualType();
3572
3573 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3574 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3575 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3576
3577 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3578
3580
3581 for (auto &OperandTA : OperandArgs) {
3582 QualType OperandArg = OperandTA.getAsType();
3583 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3584 TemplateArgs[3].getLocation());
3585 if (!Operand.isValid())
3586 return QualType();
3587 Operands.push_back(Operand);
3588 }
3589
3590 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3591 }
3592 case BTK__builtin_dedup_pack: {
3593 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3594 "a parameter pack");
3595 TemplateArgument Ts = Converted[0];
3596 // Delay the computation until we can compute the final result. We choose
3597 // not to remove the duplicates upfront before substitution to keep the code
3598 // simple.
3599 if (Ts.isDependent())
3600 return QualType();
3601 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3603 llvm::SmallDenseSet<QualType> Seen;
3604 // Synthesize a new template argument list, removing duplicates.
3605 for (auto T : Ts.getPackAsArray()) {
3606 assert(T.getKind() == clang::TemplateArgument::Type);
3607 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3608 continue;
3609 OutArgs.push_back(T);
3610 }
3611 return Context.getSubstBuiltinTemplatePack(
3612 TemplateArgument::CreatePackCopy(Context, OutArgs));
3613 }
3614 case BTK__builtin_sort_pack: {
3615 assert(Converted.size() == 1 &&
3616 "__builtin_sort_pack should be given a parameter pack");
3617 TemplateArgument Ts = Converted[0];
3618 if (Ts.isDependent())
3619 return QualType();
3620 assert(Ts.getKind() == TemplateArgument::Pack);
3621 return sortBuiltinTemplatePack(Context, Ts.getPackAsArray());
3622 }
3623 }
3624 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3625}
3626
3627/// Determine whether this alias template is "enable_if_t".
3628/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3630 return AliasTemplate->getName() == "enable_if_t" ||
3631 AliasTemplate->getName() == "__enable_if_t";
3632}
3633
3634/// Collect all of the separable terms in the given condition, which
3635/// might be a conjunction.
3636///
3637/// FIXME: The right answer is to convert the logical expression into
3638/// disjunctive normal form, so we can find the first failed term
3639/// within each possible clause.
3640static void collectConjunctionTerms(Expr *Clause,
3641 SmallVectorImpl<Expr *> &Terms) {
3642 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3643 if (BinOp->getOpcode() == BO_LAnd) {
3644 collectConjunctionTerms(BinOp->getLHS(), Terms);
3645 collectConjunctionTerms(BinOp->getRHS(), Terms);
3646 return;
3647 }
3648 }
3649
3650 Terms.push_back(Clause);
3651}
3652
3653// The ranges-v3 library uses an odd pattern of a top-level "||" with
3654// a left-hand side that is value-dependent but never true. Identify
3655// the idiom and ignore that term.
3657 // Top-level '||'.
3658 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3659 if (!BinOp) return Cond;
3660
3661 if (BinOp->getOpcode() != BO_LOr) return Cond;
3662
3663 // With an inner '==' that has a literal on the right-hand side.
3664 Expr *LHS = BinOp->getLHS();
3665 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3666 if (!InnerBinOp) return Cond;
3667
3668 if (InnerBinOp->getOpcode() != BO_EQ ||
3669 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3670 return Cond;
3671
3672 // If the inner binary operation came from a macro expansion named
3673 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3674 // of the '||', which is the real, user-provided condition.
3675 SourceLocation Loc = InnerBinOp->getExprLoc();
3676 if (!Loc.isMacroID()) return Cond;
3677
3678 StringRef MacroName = PP.getImmediateMacroName(Loc);
3679 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3680 return BinOp->getRHS();
3681
3682 return Cond;
3683}
3684
3685namespace {
3686
3687// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3688// within failing boolean expression, such as substituting template parameters
3689// for actual types.
3690class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3691public:
3692 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3693 : Policy(P) {}
3694
3695 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3696 const auto *DR = dyn_cast<DeclRefExpr>(E);
3697 if (DR && DR->getQualifier()) {
3698 // If this is a qualified name, expand the template arguments in nested
3699 // qualifiers.
3700 DR->getQualifier().print(OS, Policy, true);
3701 // Then print the decl itself.
3702 const ValueDecl *VD = DR->getDecl();
3703 OS << *VD;
3704 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3705 // This is a template variable, print the expanded template arguments.
3706 printTemplateArgumentList(
3707 OS, IV->getTemplateArgs().asArray(), Policy,
3708 IV->getSpecializedTemplate()->getTemplateParameters());
3709 }
3710 return true;
3711 }
3712 return false;
3713 }
3714
3715private:
3716 const PrintingPolicy Policy;
3717};
3718
3719} // end anonymous namespace
3720
3721std::pair<Expr *, std::string>
3723 Cond = lookThroughRangesV3Condition(PP, Cond);
3724
3725 // Separate out all of the terms in a conjunction.
3727 collectConjunctionTerms(Cond, Terms);
3728
3729 // Determine which term failed.
3730 Expr *FailedCond = nullptr;
3731 for (Expr *Term : Terms) {
3732 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3733
3734 // Literals are uninteresting.
3735 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3736 isa<IntegerLiteral>(TermAsWritten))
3737 continue;
3738
3739 // The initialization of the parameter from the argument is
3740 // a constant-evaluated context.
3743
3744 bool Succeeded;
3745 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3746 !Succeeded) {
3747 FailedCond = TermAsWritten;
3748 break;
3749 }
3750 }
3751 if (!FailedCond)
3752 FailedCond = Cond->IgnoreParenImpCasts();
3753
3754 std::string Description;
3755 {
3756 llvm::raw_string_ostream Out(Description);
3758 Policy.PrintAsCanonical = true;
3759 FailedBooleanConditionPrinterHelper Helper(Policy);
3760 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3761 }
3762 return { FailedCond, Description };
3763}
3764
3765static TemplateName
3767 const AssumedTemplateStorage *ATN,
3768 SourceLocation NameLoc) {
3769 // We assumed this undeclared identifier to be an (ADL-only) function
3770 // template name, but it was used in a context where a type was required.
3771 // Try to typo-correct it now.
3772 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3773 struct CandidateCallback : CorrectionCandidateCallback {
3774 bool ValidateCandidate(const TypoCorrection &TC) override {
3775 return TC.getCorrectionDecl() &&
3777 }
3778 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3779 return std::make_unique<CandidateCallback>(*this);
3780 }
3781 } FilterCCC;
3782
3783 TypoCorrection Corrected =
3784 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,
3785 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);
3786 if (Corrected && Corrected.getFoundDecl()) {
3787 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)
3788 << ATN->getDeclName());
3790 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3792 }
3793
3794 return TemplateName();
3795}
3796
3798 TemplateName Name,
3799 SourceLocation TemplateLoc,
3800 TemplateArgumentListInfo &TemplateArgs,
3801 Scope *Scope, bool ForNestedNameSpecifier) {
3802 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3803
3804 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3805 if (!Template) {
3806 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3807 Template = S->getParameterPack();
3808 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3809 Template = PI->getParameterPack();
3810 if (!Template)
3811 Template = PI->getPattern().getAsTemplateDecl();
3812 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3813 if (DTN->getName().getIdentifier())
3814 // When building a template-id where the template-name is dependent,
3815 // assume the template is a type template. Either our assumption is
3816 // correct, or the code is ill-formed and will be diagnosed when the
3817 // dependent name is substituted.
3818 return Context.getTemplateSpecializationType(Keyword, Name,
3819 TemplateArgs.arguments(),
3820 /*CanonicalArgs=*/{});
3821 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3823 *this, Scope, ATN, TemplateLoc);
3824 CorrectedName.isNull()) {
3825 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();
3826 return QualType();
3827 } else {
3828 Name = CorrectedName;
3829 Template = Name.getAsTemplateDecl();
3830 }
3831 }
3832 }
3833 if (!Template ||
3835 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3836 if (ForNestedNameSpecifier)
3837 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)
3838 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;
3839 else
3840 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;
3842 return QualType();
3843 }
3844
3845 // Check that the template argument list is well-formed for this
3846 // template.
3848 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3849 DefaultArgs, /*PartialTemplateArgs=*/false,
3850 CTAI,
3851 /*UpdateArgsWithConversions=*/true))
3852 return QualType();
3853
3854 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3855 // and there are no diagnsotics currently implemented for TemplateDecls,
3856 // so avoid doing it for now.
3857 MarkAnyDeclReferenced(TemplateLoc, Template, /*OdrUse=*/false);
3858
3859 QualType CanonType;
3860
3862 // We might have a substituted template template parameter pack. If so,
3863 // build a template specialization type for it.
3865 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3866
3867 // C++0x [dcl.type.elab]p2:
3868 // If the identifier resolves to a typedef-name or the simple-template-id
3869 // resolves to an alias template specialization, the
3870 // elaborated-type-specifier is ill-formed.
3873 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3876 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3877 }
3878
3879 // Find the canonical type for this type alias template specialization.
3880 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3881
3882 // Diagnose uses of the pattern of this template.
3883 (void)DiagnoseUseOfDecl(Pattern, TemplateLoc);
3884 MarkAnyDeclReferenced(TemplateLoc, Pattern, /*OdrUse=*/false);
3885
3886 if (Pattern->isInvalidDecl())
3887 return QualType();
3888
3889 // Only substitute for the innermost template argument list.
3890 MultiLevelTemplateArgumentList TemplateArgLists;
3892 /*Final=*/true);
3893 TemplateArgLists.addOuterRetainedLevels(
3894 AliasTemplate->getTemplateParameters()->getDepth());
3895
3897
3898 // FIXME: The TemplateArgs passed here are not used for the context note,
3899 // nor they should, because this note will be pointing to the specialization
3900 // anyway. These arguments are needed for a hack for instantiating lambdas
3901 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3902 // arguments will be used for collating the template arguments needed to
3903 // instantiate the lambda.
3904 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3905 /*Entity=*/AliasTemplate,
3906 /*TemplateArgs=*/CTAI.SugaredConverted);
3907 if (Inst.isInvalid())
3908 return QualType();
3909
3910 std::optional<ContextRAII> SavedContext;
3911 if (!AliasTemplate->getDeclContext()->isFileContext())
3912 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3913
3914 CanonType =
3915 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3916 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3917 if (CanonType.isNull()) {
3918 // If this was enable_if and we failed to find the nested type
3919 // within enable_if in a SFINAE context, dig out the specific
3920 // enable_if condition that failed and present that instead.
3922 if (SFINAETrap *Trap = getSFINAEContext();
3923 TemplateDeductionInfo *DeductionInfo =
3924 Trap ? Trap->getDeductionInfo() : nullptr) {
3925 if (DeductionInfo->hasSFINAEDiagnostic() &&
3926 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3927 diag::err_typename_nested_not_found_enable_if &&
3928 TemplateArgs[0].getArgument().getKind() ==
3930 Expr *FailedCond;
3931 std::string FailedDescription;
3932 std::tie(FailedCond, FailedDescription) =
3933 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3934
3935 // Remove the old SFINAE diagnostic.
3936 PartialDiagnosticAt OldDiag =
3938 DeductionInfo->takeSFINAEDiagnostic(OldDiag);
3939
3940 // Add a new SFINAE diagnostic specifying which condition
3941 // failed.
3942 DeductionInfo->addSFINAEDiagnostic(
3943 OldDiag.first,
3944 PDiag(diag::err_typename_nested_not_found_requirement)
3945 << FailedDescription << FailedCond->getSourceRange());
3946 }
3947 }
3948 }
3949
3950 return QualType();
3951 }
3952 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3953 CanonType = checkBuiltinTemplateIdType(
3954 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3955 } else if (Name.isDependent() ||
3956 TemplateSpecializationType::anyDependentTemplateArguments(
3957 TemplateArgs, CTAI.CanonicalConverted)) {
3958 // This class template specialization is a dependent
3959 // type. Therefore, its canonical type is another class template
3960 // specialization type that contains all of the converted
3961 // arguments in canonical form. This ensures that, e.g., A<T> and
3962 // A<T, T> have identical types when A is declared as:
3963 //
3964 // template<typename T, typename U = T> struct A;
3965 CanonType = Context.getCanonicalTemplateSpecializationType(
3967 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3968 CTAI.CanonicalConverted);
3969 assert(CanonType->isCanonicalUnqualified());
3970
3971 // This might work out to be a current instantiation, in which
3972 // case the canonical type needs to be the InjectedClassNameType.
3973 //
3974 // TODO: in theory this could be a simple hashtable lookup; most
3975 // changes to CurContext don't change the set of current
3976 // instantiations.
3978 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3979 // If we get out to a namespace, we're done.
3980 if (Ctx->isFileContext()) break;
3981
3982 // If this isn't a record, keep looking.
3983 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3984 if (!Record) continue;
3985
3986 // Look for one of the two cases with InjectedClassNameTypes
3987 // and check whether it's the same template.
3989 !Record->getDescribedClassTemplate())
3990 continue;
3991
3992 // Fetch the injected class name type and check whether its
3993 // injected type is equal to the type we just built.
3994 CanQualType ICNT = Context.getCanonicalTagType(Record);
3995 CanQualType Injected =
3996 Record->getCanonicalTemplateSpecializationType(Context);
3997
3998 if (CanonType != Injected)
3999 continue;
4000
4001 (void)DiagnoseUseOfDecl(Record, TemplateLoc);
4002 MarkAnyDeclReferenced(TemplateLoc, Record, /*OdrUse=*/false);
4003
4004 // If so, the canonical type of this TST is the injected
4005 // class name type of the record we just found.
4006 CanonType = ICNT;
4007 break;
4008 }
4009 }
4010 } else if (ClassTemplateDecl *ClassTemplate =
4011 dyn_cast<ClassTemplateDecl>(Template)) {
4012 // Find the class template specialization declaration that
4013 // corresponds to these arguments.
4014 llvm::FoldingSetInsertToken InsertToken;
4016 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4017 if (!Decl) {
4018 // This is the first time we have referenced this class template
4019 // specialization. Create the canonical declaration and add it to
4020 // the set of specializations.
4022 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4023 ClassTemplate->getDeclContext(),
4024 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4025 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
4026 CTAI.StrictPackMatch, nullptr);
4027 ClassTemplate->AddSpecialization(Decl, InsertToken);
4028 if (ClassTemplate->isOutOfLine())
4029 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4030 }
4031
4032 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4033 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4034 NonSFINAEContext _(*this);
4035 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4036 if (!Inst.isInvalid()) {
4038 CTAI.CanonicalConverted,
4039 /*Final=*/false);
4040 InstantiateAttrsForDecl(TemplateArgLists,
4041 ClassTemplate->getTemplatedDecl(), Decl);
4042 }
4043 }
4044
4045 // Diagnose uses of this specialization.
4046 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4047 MarkAnyDeclReferenced(TemplateLoc, Decl, /*OdrUse=*/false);
4048
4049 CanonType = Context.getCanonicalTagType(Decl);
4050 assert(isa<RecordType>(CanonType) &&
4051 "type of non-dependent specialization is not a RecordType");
4052 } else {
4053 llvm_unreachable("Unhandled template kind");
4054 }
4055
4056 // Build the fully-sugared type for this class template
4057 // specialization, which refers back to the class template
4058 // specialization we created or found.
4059 return Context.getTemplateSpecializationType(
4060 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
4061 CanonType);
4062}
4063
4065 TemplateNameKind &TNK,
4066 SourceLocation NameLoc,
4067 IdentifierInfo *&II) {
4068 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4069
4070 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4071 assert(ATN && "not an assumed template name");
4072 II = ATN->getDeclName().getAsIdentifierInfo();
4073
4074 if (TemplateName Name =
4075 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);
4076 !Name.isNull()) {
4077 // Resolved to a type template name.
4078 ParsedName = TemplateTy::make(Name);
4079 TNK = TNK_Type_template;
4080 }
4081}
4082
4084 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4085 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4086 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4087 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4088 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4089 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4090 ImplicitTypenameContext AllowImplicitTypename) {
4091 if (SS.isInvalid())
4092 return true;
4093
4094 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4095 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4096
4097 // C++ [temp.res]p3:
4098 // A qualified-id that refers to a type and in which the
4099 // nested-name-specifier depends on a template-parameter (14.6.2)
4100 // shall be prefixed by the keyword typename to indicate that the
4101 // qualified-id denotes a type, forming an
4102 // elaborated-type-specifier (7.1.5.3).
4103 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4104 // C++2a relaxes some of those restrictions in [temp.res]p5.
4105 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,
4106 SS.getScopeRep(), TemplateII);
4108 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4109 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
4110 << NNS;
4111 if (!getLangOpts().CPlusPlus20)
4112 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4113 } else
4114 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
4115
4116 // FIXME: This is not quite correct recovery as we don't transform SS
4117 // into the corresponding dependent form (and we don't diagnose missing
4118 // 'template' keywords within SS as a result).
4119 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4120 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4121 TemplateArgsIn, RAngleLoc);
4122 }
4123
4124 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4125 // it's not actually allowed to be used as a type in most cases. Because
4126 // we annotate it before we know whether it's valid, we have to check for
4127 // this case here.
4128 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4129 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4130 Diag(TemplateIILoc,
4131 TemplateKWLoc.isInvalid()
4132 ? diag::err_out_of_line_qualified_id_type_names_constructor
4133 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4134 << TemplateII << 0 /*injected-class-name used as template name*/
4135 << 1 /*if any keyword was present, it was 'template'*/;
4136 }
4137 }
4138
4139 // Translate the parser's template argument list in our AST format.
4140 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4141 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4142
4144 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,
4145 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4146 if (SpecTy.isNull())
4147 return true;
4148
4149 // Build type-source information.
4150 TypeLocBuilder TLB;
4151 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4152 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4153 TemplateIILoc, TemplateArgs);
4154 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4155}
4156
4158 TypeSpecifierType TagSpec,
4159 SourceLocation TagLoc,
4160 CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 TemplateTy TemplateD,
4163 SourceLocation TemplateLoc,
4164 SourceLocation LAngleLoc,
4165 ASTTemplateArgsPtr TemplateArgsIn,
4166 SourceLocation RAngleLoc) {
4167 if (SS.isInvalid())
4168 return TypeResult(true);
4169
4170 // Translate the parser's template argument list in our AST format.
4171 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4172 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4173
4174 // Determine the tag kind
4178
4180 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,
4181 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4182 if (Result.isNull())
4183 return TypeResult(true);
4184
4185 // Check the tag kind
4186 if (const RecordType *RT = Result->getAs<RecordType>()) {
4187 RecordDecl *D = RT->getDecl();
4188
4189 IdentifierInfo *Id = D->getIdentifier();
4190 assert(Id && "templated class must have an identifier");
4191
4193 TagLoc, Id)) {
4194 Diag(TagLoc, diag::err_use_with_wrong_tag)
4195 << Result
4197 Diag(D->getLocation(), diag::note_previous_use);
4198 }
4199 }
4200
4201 // Provide source-location information for the template specialization.
4202 TypeLocBuilder TLB;
4204 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4205 TemplateArgs);
4207}
4208
4209static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4210 NamedDecl *PrevDecl,
4211 SourceLocation Loc,
4213
4215
4217 unsigned Depth,
4218 unsigned Index) {
4219 switch (Arg.getKind()) {
4227 return false;
4228
4230 QualType Type = Arg.getAsType();
4231 const TemplateTypeParmType *TPT =
4232 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4233 return TPT && !Type.hasQualifiers() &&
4234 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4235 }
4236
4238 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4239 if (!DRE || !DRE->getDecl())
4240 return false;
4241 const NonTypeTemplateParmDecl *NTTP =
4242 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4243 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4244 }
4245
4247 const TemplateTemplateParmDecl *TTP =
4248 dyn_cast_or_null<TemplateTemplateParmDecl>(
4250 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4251 }
4252 llvm_unreachable("unexpected kind of template argument");
4253}
4254
4256 TemplateParameterList *SpecParams,
4258 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4259 return false;
4260
4261 unsigned Depth = Params->getDepth();
4262
4263 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4264 TemplateArgument Arg = Args[I];
4265
4266 // If the parameter is a pack expansion, the argument must be a pack
4267 // whose only element is a pack expansion.
4268 if (Params->getParam(I)->isParameterPack()) {
4269 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4270 !Arg.pack_begin()->isPackExpansion())
4271 return false;
4272 Arg = Arg.pack_begin()->getPackExpansionPattern();
4273 }
4274
4275 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4276 return false;
4277
4278 // For NTTPs further specialization is allowed via deduced types, so
4279 // we need to make sure to only reject here if primary template and
4280 // specialization use the same type for the NTTP.
4281 if (auto *SpecNTTP =
4282 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4283 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4284 if (!NTTP || NTTP->getType().getCanonicalType() !=
4285 SpecNTTP->getType().getCanonicalType())
4286 return false;
4287 }
4288 }
4289
4290 return true;
4291}
4292
4293template<typename PartialSpecDecl>
4294static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4295 if (Partial->getDeclContext()->isDependentContext())
4296 return;
4297
4298 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4299 // for non-substitution-failure issues?
4300 TemplateDeductionInfo Info(Partial->getLocation());
4301 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4302 return;
4303
4304 auto *Template = Partial->getSpecializedTemplate();
4305 S.Diag(Partial->getLocation(),
4306 diag::ext_partial_spec_not_more_specialized_than_primary)
4308
4309 if (Info.hasSFINAEDiagnostic()) {
4313 SmallString<128> SFINAEArgString;
4314 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4315 S.Diag(Diag.first,
4316 diag::note_partial_spec_not_more_specialized_than_primary)
4317 << SFINAEArgString;
4318 }
4319
4321 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4322 Template->getAssociatedConstraints(TemplateAC);
4323 Partial->getAssociatedConstraints(PartialAC);
4325 TemplateAC);
4326}
4327
4328static void
4330 const llvm::SmallBitVector &DeducibleParams) {
4331 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4332 if (!DeducibleParams[I]) {
4333 NamedDecl *Param = TemplateParams->getParam(I);
4334 if (Param->getDeclName())
4335 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4336 << Param->getDeclName();
4337 else
4338 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4339 << "(anonymous)";
4340 }
4341 }
4342}
4343
4344
4345template<typename PartialSpecDecl>
4347 PartialSpecDecl *Partial) {
4348 // C++1z [temp.class.spec]p8: (DR1495)
4349 // - The specialization shall be more specialized than the primary
4350 // template (14.5.5.2).
4352
4353 // C++ [temp.class.spec]p8: (DR1315)
4354 // - Each template-parameter shall appear at least once in the
4355 // template-id outside a non-deduced context.
4356 // C++1z [temp.class.spec.match]p3 (P0127R2)
4357 // If the template arguments of a partial specialization cannot be
4358 // deduced because of the structure of its template-parameter-list
4359 // and the template-id, the program is ill-formed.
4360 auto *TemplateParams = Partial->getTemplateParameters();
4361 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4362 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4363 TemplateParams->getDepth(), DeducibleParams);
4364
4365 if (!DeducibleParams.all()) {
4366 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4367 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4369 << (NumNonDeducible > 1)
4370 << SourceRange(Partial->getLocation(),
4371 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4372 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4380
4385
4387 // C++1z [temp.param]p11:
4388 // A template parameter of a deduction guide template that does not have a
4389 // default-argument shall be deducible from the parameter-type-list of the
4390 // deduction guide template.
4391 auto *TemplateParams = TD->getTemplateParameters();
4392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4393 MarkDeducedTemplateParameters(TD, DeducibleParams);
4394 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4395 // A parameter pack is deducible (to an empty pack).
4396 auto *Param = TemplateParams->getParam(I);
4397 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4398 DeducibleParams[I] = true;
4399 }
4400
4401 if (!DeducibleParams.all()) {
4402 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4403 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4404 << (NumNonDeducible > 1);
4405 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4406 }
4407}
4408
4411 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4413 // D must be variable template id.
4415 "Variable template specialization is declared with a template id.");
4416
4417 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4418 TemplateArgumentListInfo TemplateArgs =
4419 makeTemplateArgumentListInfo(*this, *TemplateId);
4420 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4421 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4422 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4423
4424 TemplateName Name = TemplateId->Template.get();
4425
4426 // The template-id must name a variable template.
4428 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4429 if (!VarTemplate) {
4430 NamedDecl *FnTemplate;
4431 if (auto *OTS = Name.getAsOverloadedTemplate())
4432 FnTemplate = *OTS->begin();
4433 else
4434 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4435 if (FnTemplate)
4436 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4437 << FnTemplate->getDeclName();
4438 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4440 }
4441
4442 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4443 auto Message = DSA->getMessage();
4444 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4445 << VarTemplate << !Message.empty() << Message;
4446 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4447 }
4448
4449 // Check for unexpanded parameter packs in any of the template arguments.
4450 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4451 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4455 return true;
4456
4457 // Check that the template argument list is well-formed for this
4458 // template.
4460 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4461 /*DefaultArgs=*/{},
4462 /*PartialTemplateArgs=*/false, CTAI,
4463 /*UpdateArgsWithConversions=*/true))
4464 return true;
4465
4466 // Find the variable template (partial) specialization declaration that
4467 // corresponds to these arguments.
4470 TemplateArgs.size(),
4471 CTAI.CanonicalConverted))
4472 return true;
4473
4474 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4475 // we also do them during instantiation.
4476 if (!Name.isDependent() &&
4477 !TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, CTAI.CanonicalConverted)) {
4479 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4480 << VarTemplate->getDeclName();
4482 }
4483
4484 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4485 TemplateParams, CTAI.CanonicalConverted) &&
4486 (!Context.getLangOpts().CPlusPlus20 ||
4487 !TemplateParams->hasAssociatedConstraints())) {
4488 // C++ [temp.class.spec]p9b3:
4489 //
4490 // -- The argument list of the specialization shall not be identical
4491 // to the implicit argument list of the primary template.
4492 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4493 << /*variable template*/ 1
4494 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4495 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4496 // FIXME: Recover from this by treating the declaration as a
4497 // redeclaration of the primary template.
4498 return true;
4499 }
4500 }
4501
4502 llvm::FoldingSetInsertToken InsertToken;
4503 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4504
4506 PrevDecl = VarTemplate->findPartialSpecialization(
4507 CTAI.CanonicalConverted, TemplateParams, InsertToken);
4508 else
4509 PrevDecl =
4510 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
4511
4513
4514 // Check whether we can declare a variable template specialization in
4515 // the current scope.
4516 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4517 TemplateNameLoc,
4519 return true;
4520
4521 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4522 // Since the only prior variable template specialization with these
4523 // arguments was referenced but not declared, reuse that
4524 // declaration node as our own, updating its source location and
4525 // the list of outer template parameters to reflect our new declaration.
4526 Specialization = PrevDecl;
4527 Specialization->setLocation(TemplateNameLoc);
4528 PrevDecl = nullptr;
4529 } else if (IsPartialSpecialization) {
4530 // Create a new class template partial specialization declaration node.
4532 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4535 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4536 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,
4537 SC, CTAI.CanonicalConverted);
4538 Partial->setTemplateArgsAsWritten(TemplateArgs);
4539
4540 if (!PrevPartial)
4541 VarTemplate->AddPartialSpecialization(Partial, InsertToken);
4542 Specialization = Partial;
4543
4545 } else {
4546 // Create a new class template specialization declaration node for
4547 // this explicit specialization or friend declaration.
4549 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4550 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);
4551 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4552
4553 if (!PrevDecl)
4554 VarTemplate->AddSpecialization(Specialization, InsertToken);
4555 }
4556
4557 // C++ [temp.expl.spec]p6:
4558 // If a template, a member template or the member of a class template is
4559 // explicitly specialized then that specialization shall be declared
4560 // before the first use of that specialization that would cause an implicit
4561 // instantiation to take place, in every translation unit in which such a
4562 // use occurs; no diagnostic is required.
4563 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4564 bool Okay = false;
4565 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4566 // Is there any previous explicit specialization declaration?
4568 Okay = true;
4569 break;
4570 }
4571 }
4572
4573 if (!Okay) {
4574 SourceRange Range(TemplateNameLoc, RAngleLoc);
4575 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4576 << Name << Range;
4577
4578 Diag(PrevDecl->getPointOfInstantiation(),
4579 diag::note_instantiation_required_here)
4580 << (PrevDecl->getTemplateSpecializationKind() !=
4582 return true;
4583 }
4584 }
4585
4586 Specialization->setLexicalDeclContext(CurContext);
4587
4588 // Add the specialization into its lexical context, so that it can
4589 // be seen when iterating through the list of declarations in that
4590 // context. However, specializations are not found by name lookup.
4591 CurContext->addDecl(Specialization);
4592
4593 // Note that this is an explicit specialization.
4594 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4595
4596 Previous.clear();
4597 if (PrevDecl)
4598 Previous.addDecl(PrevDecl);
4599 else if (Specialization->isStaticDataMember() &&
4600 Specialization->isOutOfLine())
4601 Specialization->setAccess(VarTemplate->getAccess());
4602
4603 return Specialization;
4604}
4605
4606namespace {
4607/// A partial specialization whose template arguments have matched
4608/// a given template-id.
4609struct PartialSpecMatchResult {
4612};
4613
4614// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4615// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4616static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4617 if (Var->getName() != "format_kind" ||
4618 !Var->getDeclContext()->isStdNamespace())
4619 return false;
4620
4621 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4622 // release in which users can access std::format_kind.
4623 // We can use 20250520 as the final date, see the following commits.
4624 // GCC releases/gcc-15 branch:
4625 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4626 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4627 // GCC master branch:
4628 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4629 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4630 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4631}
4632} // end anonymous namespace
4633
4636 SourceLocation TemplateNameLoc,
4637 const TemplateArgumentListInfo &TemplateArgs,
4638 bool SetWrittenArgs) {
4639 assert(Template && "A variable template id without template?");
4640
4641 // Check that the template argument list is well-formed for this template.
4644 Template, TemplateNameLoc,
4645 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4646 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4647 /*UpdateArgsWithConversions=*/true))
4648 return true;
4649
4650 // Produce a placeholder value if the specialization is dependent.
4651 if (Template->getDeclContext()->isDependentContext() ||
4652 TemplateSpecializationType::anyDependentTemplateArguments(
4653 TemplateArgs, CTAI.CanonicalConverted)) {
4654 if (ParsingInitForAutoVars.empty())
4655 return DeclResult();
4656
4657 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4658 const TemplateArgument &Arg2) {
4659 return Context.isSameTemplateArgument(Arg1, Arg2);
4660 };
4661
4662 if (VarDecl *Var = Template->getTemplatedDecl();
4663 ParsingInitForAutoVars.count(Var) &&
4664 // See comments on this function definition
4665 !IsLibstdcxxStdFormatKind(PP, Var) &&
4666 llvm::equal(
4667 CTAI.CanonicalConverted,
4668 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4669 IsSameTemplateArg)) {
4670 Diag(TemplateNameLoc,
4671 diag::err_auto_variable_cannot_appear_in_own_initializer)
4672 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4673 return true;
4674 }
4675
4677 Template->getPartialSpecializations(PartialSpecs);
4678 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4679 if (ParsingInitForAutoVars.count(Partial) &&
4680 llvm::equal(CTAI.CanonicalConverted,
4681 Partial->getTemplateArgs().asArray(),
4682 IsSameTemplateArg)) {
4683 Diag(TemplateNameLoc,
4684 diag::err_auto_variable_cannot_appear_in_own_initializer)
4685 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4686 << Partial->getType();
4687 return true;
4688 }
4689
4690 return DeclResult();
4691 }
4692
4693 // Find the variable template specialization declaration that
4694 // corresponds to these arguments.
4695 llvm::FoldingSetInsertToken InsertToken;
4697 Template->findSpecialization(CTAI.CanonicalConverted, InsertToken)) {
4698 checkSpecializationReachability(TemplateNameLoc, Spec);
4699 if (Spec->getType()->isUndeducedType()) {
4700 if (ParsingInitForAutoVars.count(Spec))
4701 Diag(TemplateNameLoc,
4702 diag::err_auto_variable_cannot_appear_in_own_initializer)
4703 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4704 << Spec->getType();
4705 else
4706 // We are substituting the initializer of this variable template
4707 // specialization.
4708 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4709 << Spec << Spec->getType();
4710
4711 return true;
4712 }
4713 // If we already have a variable template specialization, return it.
4714 return Spec;
4715 }
4716
4717 // This is the first time we have referenced this variable template
4718 // specialization. Create the canonical declaration and add it to
4719 // the set of specializations, based on the closest partial specialization
4720 // that it represents. That is,
4721 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4722 const TemplateArgumentList *PartialSpecArgs = nullptr;
4723 bool AmbiguousPartialSpec = false;
4724 typedef PartialSpecMatchResult MatchResult;
4726 SourceLocation PointOfInstantiation = TemplateNameLoc;
4727 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4728 /*ForTakingAddress=*/false);
4729
4730 // 1. Attempt to find the closest partial specialization that this
4731 // specializes, if any.
4732 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4733 // Perhaps better after unification of DeduceTemplateArguments() and
4734 // getMoreSpecializedPartialSpecialization().
4736 Template->getPartialSpecializations(PartialSpecs);
4737
4738 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4739 // C++ [temp.spec.partial.member]p2:
4740 // If the primary member template is explicitly specialized for a given
4741 // (implicit) specialization of the enclosing class template, the partial
4742 // specializations of the member template are ignored for this
4743 // specialization of the enclosing class template. If a partial
4744 // specialization of the member template is explicitly specialized for a
4745 // given (implicit) specialization of the enclosing class template, the
4746 // primary member template and its other partial specializations are still
4747 // considered for this specialization of the enclosing class template.
4748 if (Template->isMemberSpecialization() &&
4749 !Partial->isMemberSpecialization())
4750 continue;
4751
4752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4753
4755 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4757 // Store the failed-deduction information for use in diagnostics, later.
4758 // TODO: Actually use the failed-deduction info?
4759 FailedCandidates.addCandidate().set(
4762 (void)Result;
4763 } else {
4764 Matched.push_back(PartialSpecMatchResult());
4765 Matched.back().Partial = Partial;
4766 Matched.back().Args = Info.takeSugared();
4767 }
4768 }
4769
4770 if (Matched.size() >= 1) {
4771 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4772 if (Matched.size() == 1) {
4773 // -- If exactly one matching specialization is found, the
4774 // instantiation is generated from that specialization.
4775 // We don't need to do anything for this.
4776 } else {
4777 // -- If more than one matching specialization is found, the
4778 // partial order rules (14.5.4.2) are used to determine
4779 // whether one of the specializations is more specialized
4780 // than the others. If none of the specializations is more
4781 // specialized than all of the other matching
4782 // specializations, then the use of the variable template is
4783 // ambiguous and the program is ill-formed.
4784 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4785 PEnd = Matched.end();
4786 P != PEnd; ++P) {
4787 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4788 PointOfInstantiation) ==
4789 P->Partial)
4790 Best = P;
4791 }
4792
4793 // Determine if the best partial specialization is more specialized than
4794 // the others.
4795 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4796 PEnd = Matched.end();
4797 P != PEnd; ++P) {
4799 P->Partial, Best->Partial,
4800 PointOfInstantiation) != Best->Partial) {
4801 AmbiguousPartialSpec = true;
4802 break;
4803 }
4804 }
4805 }
4806
4807 // Instantiate using the best variable template partial specialization.
4808 InstantiationPattern = Best->Partial;
4809 PartialSpecArgs = Best->Args;
4810 } else {
4811 // -- If no match is found, the instantiation is generated
4812 // from the primary template.
4813 // InstantiationPattern = Template->getTemplatedDecl();
4814 }
4815
4816 // 2. Create the canonical declaration.
4817 // Note that we do not instantiate a definition until we see an odr-use
4818 // in DoMarkVarDeclReferenced().
4819 // FIXME: LateAttrs et al.?
4820 if (AmbiguousPartialSpec) {
4821 // Partial ordering did not produce a clear winner. Complain.
4822 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4823 << Template;
4824 // Print the matching partial specializations.
4825 for (MatchResult P : Matched)
4826 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4827 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4828 *P.Args);
4829 return true;
4830 }
4831
4833 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,
4834 TemplateNameLoc /*, LateAttrs, StartingScope*/);
4835 if (!Decl)
4836 return true;
4837 if (SetWrittenArgs)
4838 Decl->setTemplateArgsAsWritten(TemplateArgs);
4839
4841 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4842 Decl->setInstantiationOf(D, PartialSpecArgs);
4843
4844 checkSpecializationReachability(TemplateNameLoc, Decl);
4845
4846 assert(Decl && "No variable template specialization?");
4847 return Decl;
4848}
4849
4851 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4852 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4853 const TemplateArgumentListInfo *TemplateArgs) {
4854
4855 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4856 *TemplateArgs, /*SetWrittenArgs=*/false);
4857 if (Decl.isInvalid())
4858 return ExprError();
4859
4860 if (!Decl.get())
4861 return ExprResult();
4862
4863 VarDecl *Var = cast<VarDecl>(Decl.get());
4866 NameInfo.getLoc());
4867
4868 // Build an ordinary singleton decl ref.
4869 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4870}
4871
4873 const DeclarationNameInfo &NameInfo, TemplateName Template,
4874 const TemplateArgumentListInfo *TemplateArgs) {
4876 Template.getAsTemplateTemplateParmDecl();
4877 assert(Parameter && "A variable template id without template?");
4878
4879 if (Parameter->templateParameterKind() !=
4881 Parameter->templateParameterKind() !=
4883 return ExprResult();
4884
4885 // Check that the template argument list is well-formed for this template.
4888 Parameter, /*Template kw loc=*/{},
4889 // FIXME: TemplateArgs will not be modified because
4890 // UpdateArgsWithConversions is false, however, we should
4891 // CheckTemplateArgumentList to be const-correct.
4892 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4893 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4894 /*UpdateArgsWithConversions=*/false))
4895 return true;
4896
4898 *TemplateArgs);
4899}
4900
4902 SourceLocation Loc) {
4903 Diag(Loc, diag::err_template_missing_args)
4904 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4905 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4906 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4907 }
4908}
4909
4911 bool TemplateKeyword,
4912 TemplateDecl *TD,
4913 SourceLocation Loc) {
4914 TemplateName Name = Context.getQualifiedTemplateName(
4915 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4917}
4918
4920 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4921 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4922 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4923 bool DoCheckConstraintSatisfaction) {
4924 assert(NamedConcept && "A concept template id without a template?");
4925
4926 if (NamedConcept->isInvalidDecl())
4927 return ExprError();
4928
4931 NamedConcept, ConceptNameInfo.getLoc(),
4932 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4933 /*DefaultArgs=*/{},
4934 /*PartialTemplateArgs=*/false, CTAI,
4935 /*UpdateArgsWithConversions=*/false))
4936 return ExprError();
4937
4938 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4939
4940 // There's a bug with CTAI.CanonicalConverted.
4941 // If the template argument contains a DependentDecltypeType that includes a
4942 // TypeAliasType, and the same written type had occurred previously in the
4943 // source, then the DependentDecltypeType would be canonicalized to that
4944 // previous type which would mess up the substitution.
4945 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4947 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4948 CTAI.SugaredConverted);
4949 ConstraintSatisfaction Satisfaction;
4950 bool AreArgsDependent =
4951 TemplateSpecializationType::anyDependentTemplateArguments(
4952 *TemplateArgs, CTAI.SugaredConverted);
4953 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4954 /*Final=*/false);
4956 Context,
4958 TemplateKWLoc, ConceptNameInfo, FoundDecl, TemplateName(NamedConcept),
4960
4961 bool Error = false;
4962 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);
4963 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4964 DoCheckConstraintSatisfaction) {
4965
4967
4970
4972 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
4973 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4974 TemplateArgs->getRAngleLoc()),
4975 Satisfaction, CL);
4976 Satisfaction.ContainsErrors = Error;
4977 }
4978
4979 if (Error)
4980 return ExprError();
4981
4983 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4984}
4985
4987 SourceLocation TemplateKWLoc,
4988 LookupResult &R,
4989 bool RequiresADL,
4990 const TemplateArgumentListInfo *TemplateArgs) {
4991 // FIXME: Can we do any checking at this point? I guess we could check the
4992 // template arguments that we have against the template name, if the template
4993 // name refers to a single template. That's not a terribly common case,
4994 // though.
4995 // foo<int> could identify a single function unambiguously
4996 // This approach does NOT work, since f<int>(1);
4997 // gets resolved prior to resorting to overload resolution
4998 // i.e., template<class T> void f(double);
4999 // vs template<class T, class U> void f(U);
5000
5001 // These should be filtered out by our callers.
5002 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5003
5004 // Non-function templates require a template argument list.
5005 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5006 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5008 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
5009 return ExprError();
5010 }
5011 }
5012 bool KnownDependent = false;
5013 // In C++1y, check variable template ids.
5014 if (R.getAsSingle<VarTemplateDecl>()) {
5016 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
5017 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5018 if (Res.isInvalid() || Res.isUsable())
5019 return Res;
5020 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5021 KnownDependent = true;
5022 }
5023
5024 // We don't want lookup warnings at this point.
5025 R.suppressDiagnostics();
5026
5027 if (R.getAsSingle<ConceptDecl>()) {
5028 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5029 R.getRepresentativeDecl(),
5030 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5031 }
5032
5033 // Check variable template ids (C++17) and concept template parameters
5034 // (C++26).
5036 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5037 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5038 assert(TemplateKWLoc.isInvalid() &&
5039 "template keyword in front of a template parameter?");
5041 R.getLookupNameInfo(),
5042 TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5043 }
5044
5045 // Function templates
5047 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5048 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5049 R.begin(), R.end(), KnownDependent,
5050 /*KnownInstantiationDependent=*/false);
5051 // Model the templates with UnresolvedTemplateTy. The expression should then
5052 // either be transformed in an instantiation or be diagnosed in
5053 // CheckPlaceholderExpr.
5054 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5055 !R.getFoundDecl()->getAsFunction())
5056 ULE->setType(Context.UnresolvedTemplateTy);
5057
5058 return ULE;
5059}
5060
5062 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5063 const DeclarationNameInfo &NameInfo,
5064 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5065 assert(TemplateArgs || TemplateKWLoc.isValid());
5066
5067 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5068 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5069 /*EnteringContext=*/false, TemplateKWLoc))
5070 return ExprError();
5071
5072 if (R.isAmbiguous())
5073 return ExprError();
5074
5075 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5076 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5077
5078 if (R.empty()) {
5080 Diag(NameInfo.getLoc(), diag::err_no_member)
5081 << NameInfo.getName() << DC << SS.getRange();
5082 return ExprError();
5083 }
5084
5085 // If necessary, build an implicit class member access.
5086 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5087 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5088 /*S=*/nullptr);
5089
5090 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
5091}
5092
5094 CXXScopeSpec &SS,
5095 SourceLocation TemplateKWLoc,
5096 const UnqualifiedId &Name,
5097 ParsedType ObjectType,
5098 bool EnteringContext,
5100 bool AllowInjectedClassName) {
5101 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5102 DiagCompat(TemplateKWLoc, diag_compat::template_outside_of_template)
5103 << FixItHint::CreateRemoval(TemplateKWLoc);
5104
5105 if (SS.isInvalid())
5106 return TNK_Non_template;
5107
5108 // Figure out where isTemplateName is going to look.
5109 DeclContext *LookupCtx = nullptr;
5110 if (SS.isNotEmpty())
5111 LookupCtx = computeDeclContext(SS, EnteringContext);
5112 else if (ObjectType)
5113 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5114
5115 // C++0x [temp.names]p5:
5116 // If a name prefixed by the keyword template is not the name of
5117 // a template, the program is ill-formed. [Note: the keyword
5118 // template may not be applied to non-template members of class
5119 // templates. -end note ] [ Note: as is the case with the
5120 // typename prefix, the template prefix is allowed in cases
5121 // where it is not strictly necessary; i.e., when the
5122 // nested-name-specifier or the expression on the left of the ->
5123 // or . is not dependent on a template-parameter, or the use
5124 // does not appear in the scope of a template. -end note]
5125 //
5126 // Note: C++03 was more strict here, because it banned the use of
5127 // the "template" keyword prior to a template-name that was not a
5128 // dependent name. C++ DR468 relaxed this requirement (the
5129 // "template" keyword is now permitted). We follow the C++0x
5130 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5131 bool MemberOfUnknownSpecialization;
5132 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5133 ObjectType, EnteringContext, Result,
5134 MemberOfUnknownSpecialization);
5135 if (TNK != TNK_Non_template) {
5136 // We resolved this to a (non-dependent) template name. Return it.
5137 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5138 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5140 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5141 // C++14 [class.qual]p2:
5142 // In a lookup in which function names are not ignored and the
5143 // nested-name-specifier nominates a class C, if the name specified
5144 // [...] is the injected-class-name of C, [...] the name is instead
5145 // considered to name the constructor
5146 //
5147 // We don't get here if naming the constructor would be valid, so we
5148 // just reject immediately and recover by treating the
5149 // injected-class-name as naming the template.
5150 Diag(Name.getBeginLoc(),
5151 diag::ext_out_of_line_qualified_id_type_names_constructor)
5152 << Name.Identifier
5153 << 0 /*injected-class-name used as template name*/
5154 << TemplateKWLoc.isValid();
5155 }
5156 return TNK;
5157 }
5158
5159 if (!MemberOfUnknownSpecialization) {
5160 // Didn't find a template name, and the lookup wasn't dependent.
5161 // Do the lookup again to determine if this is a "nothing found" case or
5162 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5163 // need to do this.
5165 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5167 // Tell LookupTemplateName that we require a template so that it diagnoses
5168 // cases where it finds a non-template.
5169 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5170 ? RequiredTemplateKind(TemplateKWLoc)
5172 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5173 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5174 !R.isAmbiguous()) {
5175 if (LookupCtx)
5176 Diag(Name.getBeginLoc(), diag::err_no_member)
5177 << DNI.getName() << LookupCtx << SS.getRange();
5178 else
5179 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5180 << DNI.getName() << SS.getRange();
5181 }
5182 return TNK_Non_template;
5183 }
5184
5185 NestedNameSpecifier Qualifier = SS.getScopeRep();
5186
5187 switch (Name.getKind()) {
5189 Result = TemplateTy::make(Context.getDependentTemplateName(
5190 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5192
5194 Result = TemplateTy::make(Context.getDependentTemplateName(
5195 {Qualifier, Name.OperatorFunctionId.Operator,
5196 TemplateKWLoc.isValid()}));
5197 return TNK_Function_template;
5198
5200 // This is a kind of template name, but can never occur in a dependent
5201 // scope (literal operators can only be declared at namespace scope).
5202 break;
5203
5204 default:
5205 break;
5206 }
5207
5208 // This name cannot possibly name a dependent template. Diagnose this now
5209 // rather than building a dependent template name that can never be valid.
5210 Diag(Name.getBeginLoc(),
5211 diag::err_template_kw_refers_to_dependent_non_template)
5213 << TemplateKWLoc.isValid() << TemplateKWLoc;
5214 return TNK_Non_template;
5215}
5216
5219 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5220 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5221 const TemplateArgument &Arg = AL.getArgument();
5223 TypeSourceInfo *TSI = nullptr;
5224
5225 // Check template type parameter.
5226 switch(Arg.getKind()) {
5228 // C++ [temp.arg.type]p1:
5229 // A template-argument for a template-parameter which is a
5230 // type shall be a type-id.
5231 ArgType = Arg.getAsType();
5232 TSI = AL.getTypeSourceInfo();
5233 break;
5236 // We have a template type parameter but the template argument
5237 // is a template without any arguments.
5238 SourceRange SR = AL.getSourceRange();
5241 return true;
5242 }
5244 // We have a template type parameter but the template argument is an
5245 // expression; see if maybe it is missing the "typename" keyword.
5246 CXXScopeSpec SS;
5247 DeclarationNameInfo NameInfo;
5248 TemplateArgument Pattern = Arg;
5249 if (Pattern.isPackExpansion())
5250 Pattern = Pattern.getPackExpansionPattern();
5251 Expr *E = Pattern.getAsExpr();
5252
5253 if (DependentScopeDeclRefExpr *ArgExpr =
5254 dyn_cast<DependentScopeDeclRefExpr>(E)) {
5255 SS.Adopt(ArgExpr->getQualifierLoc());
5256 NameInfo = ArgExpr->getNameInfo();
5257 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5258 dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5259 if (ArgExpr->isImplicitAccess()) {
5260 SS.Adopt(ArgExpr->getQualifierLoc());
5261 NameInfo = ArgExpr->getMemberNameInfo();
5262 }
5263 }
5264
5265 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5266 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5267 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5268
5269 if (Result.getAsSingle<TypeDecl>() ||
5270 Result.wasNotFoundInCurrentInstantiation()) {
5271 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5272 // Suggest that the user add 'typename' before the NNS.
5274 Diag(Loc, getLangOpts().MSVCCompat
5275 ? diag::ext_ms_template_type_arg_missing_typename
5276 : diag::err_template_arg_must_be_type_suggest)
5277 << FixItHint::CreateInsertion(Loc, "typename ");
5279
5280 // Recover by synthesizing a type using the location information that we
5281 // already have.
5282 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,
5283 SS.getScopeRep(), II);
5284 TypeLocBuilder TLB;
5286 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5288 TL.setNameLoc(NameInfo.getLoc());
5289 if (Arg.isPackExpansion()) {
5290 ArgType = Context.getPackExpansionType(ArgType, std::nullopt);
5292 TL.setEllipsisLoc(
5293 cast<PackExpansionExpr>(Arg.getAsExpr())->getEllipsisLoc());
5294 }
5295 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5296
5297 // Overwrite our input TemplateArgumentLoc so that we can recover
5298 // properly.
5301
5302 break;
5303 }
5304 }
5305 // fallthrough
5306 [[fallthrough]];
5307 }
5308 default: {
5309 // We allow instantiating a template with template argument packs when
5310 // building deduction guides or mapping constraint template parameters.
5311 if (Arg.getKind() == TemplateArgument::Pack &&
5312 (CodeSynthesisContexts.back().Kind ==
5315 SugaredConverted.push_back(Arg);
5316 CanonicalConverted.push_back(Arg);
5317 return false;
5318 }
5319 // We have a template type parameter but the template argument
5320 // is not a type.
5321 SourceRange SR = AL.getSourceRange();
5322 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5324
5325 return true;
5326 }
5327 }
5328
5329 if (CheckTemplateArgument(TSI))
5330 return true;
5331
5332 // Objective-C ARC:
5333 // If an explicitly-specified template argument type is a lifetime type
5334 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5335 if (getLangOpts().ObjCAutoRefCount &&
5336 ArgType->isObjCLifetimeType() &&
5337 !ArgType.getObjCLifetime()) {
5338 Qualifiers Qs;
5340 ArgType = Context.getQualifiedType(ArgType, Qs);
5341 }
5342
5343 SugaredConverted.push_back(TemplateArgument(ArgType));
5344 CanonicalConverted.push_back(
5345 TemplateArgument(Context.getCanonicalType(ArgType)));
5346 return false;
5347}
5348
5349/// Substitute template arguments into the default template argument for
5350/// the given template type parameter.
5351///
5352/// \param SemaRef the semantic analysis object for which we are performing
5353/// the substitution.
5354///
5355/// \param Template the template that we are synthesizing template arguments
5356/// for.
5357///
5358/// \param TemplateLoc the location of the template name that started the
5359/// template-id we are checking.
5360///
5361/// \param RAngleLoc the location of the right angle bracket ('>') that
5362/// terminates the template-id.
5363///
5364/// \param Param the template template parameter whose default we are
5365/// substituting into.
5366///
5367/// \param Converted the list of template arguments provided for template
5368/// parameters that precede \p Param in the template parameter list.
5369///
5370/// \param Output the resulting substituted template argument.
5371///
5372/// \returns true if an error occurred.
5374 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5375 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5376 ArrayRef<TemplateArgument> SugaredConverted,
5377 ArrayRef<TemplateArgument> CanonicalConverted,
5378 TemplateArgumentLoc &Output) {
5379 Output = Param->getDefaultArgument();
5380
5381 // If the argument type is dependent, instantiate it now based
5382 // on the previously-computed template arguments.
5383 if (Output.getArgument().isInstantiationDependent()) {
5384 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5385 SugaredConverted,
5386 SourceRange(TemplateLoc, RAngleLoc));
5387 if (Inst.isInvalid())
5388 return true;
5389
5390 // Only substitute for the innermost template argument list.
5391 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5392 /*Final=*/true);
5393 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5394 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5395
5396 bool ForLambdaCallOperator = false;
5397 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5398 ForLambdaCallOperator = Rec->isLambda();
5399 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5400 !ForLambdaCallOperator);
5401
5402 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5403 Param->getDefaultArgumentLoc(),
5404 Param->getDeclName()))
5405 return true;
5406 }
5407
5408 return false;
5409}
5410
5411/// Substitute template arguments into the default template argument for
5412/// the given non-type template parameter.
5413///
5414/// \param SemaRef the semantic analysis object for which we are performing
5415/// the substitution.
5416///
5417/// \param Template the template that we are synthesizing template arguments
5418/// for.
5419///
5420/// \param TemplateLoc the location of the template name that started the
5421/// template-id we are checking.
5422///
5423/// \param RAngleLoc the location of the right angle bracket ('>') that
5424/// terminates the template-id.
5425///
5426/// \param Param the non-type template parameter whose default we are
5427/// substituting into.
5428///
5429/// \param Converted the list of template arguments provided for template
5430/// parameters that precede \p Param in the template parameter list.
5431///
5432/// \returns the substituted template argument, or NULL if an error occurred.
5434 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5435 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5436 ArrayRef<TemplateArgument> SugaredConverted,
5437 ArrayRef<TemplateArgument> CanonicalConverted,
5438 TemplateArgumentLoc &Output) {
5439 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5440 SugaredConverted,
5441 SourceRange(TemplateLoc, RAngleLoc));
5442 if (Inst.isInvalid())
5443 return true;
5444
5445 // Only substitute for the innermost template argument list.
5446 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5447 /*Final=*/true);
5448 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5449 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5450
5451 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5452 EnterExpressionEvaluationContext ConstantEvaluated(
5454 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5455 TemplateArgLists, Output);
5456}
5457
5458/// Substitute template arguments into the default template argument for
5459/// the given template template parameter.
5460///
5461/// \param SemaRef the semantic analysis object for which we are performing
5462/// the substitution.
5463///
5464/// \param Template the template that we are synthesizing template arguments
5465/// for.
5466///
5467/// \param TemplateLoc the location of the template name that started the
5468/// template-id we are checking.
5469///
5470/// \param RAngleLoc the location of the right angle bracket ('>') that
5471/// terminates the template-id.
5472///
5473/// \param Param the template template parameter whose default we are
5474/// substituting into.
5475///
5476/// \param Converted the list of template arguments provided for template
5477/// parameters that precede \p Param in the template parameter list.
5478///
5479/// \param QualifierLoc Will be set to the nested-name-specifier (with
5480/// source-location information) that precedes the template name.
5481///
5482/// \returns the substituted template argument, or NULL if an error occurred.
5484 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5485 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5487 ArrayRef<TemplateArgument> SugaredConverted,
5488 ArrayRef<TemplateArgument> CanonicalConverted,
5489 NestedNameSpecifierLoc &QualifierLoc) {
5491 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5492 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5493 if (Inst.isInvalid())
5494 return TemplateName();
5495
5496 // Only substitute for the innermost template argument list.
5497 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5498 /*Final=*/true);
5499 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5500 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5501
5502 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5503
5504 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5505 QualifierLoc = A.getTemplateQualifierLoc();
5506 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5508 A.getTemplateNameLoc(), TemplateArgLists);
5509}
5510
5512 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5513 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5514 ArrayRef<TemplateArgument> SugaredConverted,
5515 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5516 HasDefaultArg = false;
5517
5518 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5519 if (!hasReachableDefaultArgument(TypeParm))
5520 return TemplateArgumentLoc();
5521
5522 HasDefaultArg = true;
5523 TemplateArgumentLoc Output;
5524 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5525 RAngleLoc, TypeParm, SugaredConverted,
5526 CanonicalConverted, Output))
5527 return TemplateArgumentLoc();
5528 return Output;
5529 }
5530
5531 if (NonTypeTemplateParmDecl *NonTypeParm
5532 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5533 if (!hasReachableDefaultArgument(NonTypeParm))
5534 return TemplateArgumentLoc();
5535
5536 HasDefaultArg = true;
5537 TemplateArgumentLoc Output;
5538 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5539 RAngleLoc, NonTypeParm, SugaredConverted,
5540 CanonicalConverted, Output))
5541 return TemplateArgumentLoc();
5542 return Output;
5543 }
5544
5545 TemplateTemplateParmDecl *TempTempParm
5547 if (!hasReachableDefaultArgument(TempTempParm))
5548 return TemplateArgumentLoc();
5549
5550 HasDefaultArg = true;
5551 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5552 NestedNameSpecifierLoc QualifierLoc;
5554 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5555 SugaredConverted, CanonicalConverted, QualifierLoc);
5556 if (TName.isNull())
5557 return TemplateArgumentLoc();
5558
5559 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5560 QualifierLoc, A.getTemplateNameLoc());
5561}
5562
5563/// Convert a template-argument that we parsed as a type into a template, if
5564/// possible. C++ permits injected-class-names to perform dual service as
5565/// template template arguments and as template type arguments.
5568 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5569 if (!TagLoc)
5570 return TemplateArgumentLoc();
5571
5572 // If this type was written as an injected-class-name, it can be used as a
5573 // template template argument.
5574 // If this type was written as an injected-class-name, it may have been
5575 // converted to a RecordType during instantiation. If the RecordType is
5576 // *not* wrapped in a TemplateSpecializationType and denotes a class
5577 // template specialization, it must have come from an injected-class-name.
5578
5579 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5580 if (Name.isNull())
5581 return TemplateArgumentLoc();
5582
5583 return TemplateArgumentLoc(Context, Name,
5584 /*TemplateKWLoc=*/SourceLocation(),
5585 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5586}
5587
5590 SourceLocation TemplateLoc,
5591 SourceLocation RAngleLoc,
5592 unsigned ArgumentPackIndex,
5595 // Check template type parameters.
5596 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5597 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5598 CTAI.CanonicalConverted);
5599
5600 const TemplateArgument &Arg = ArgLoc.getArgument();
5601 // Check non-type template parameters.
5602 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5603 // Do substitution on the type of the non-type template parameter
5604 // with the template arguments we've seen thus far. But if the
5605 // template has a dependent context then we cannot substitute yet.
5606 QualType NTTPType = NTTP->getType();
5607 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5608 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5609
5610 // C++26 [dcl.type.auto.deduct]p3:
5611 // If the placeholder-type-specifier is of the form type-constraint_opt
5612 // auto, [...] If E is a value synthesized for a constant template
5613 // parameter of type decltype(auto) ([temp.func.order]), the declaration
5614 // is ill-formed.
5615 auto isUndeducedAuto = [](QualType T, bool DecltypeAuto) {
5616 if (T.isNull())
5617 return false;
5618 const AutoType *AT = T->getContainedAutoType();
5619 return AT && AT->isDecltypeAuto() == DecltypeAuto &&
5620 AT->getDeducedType().isNull();
5621 };
5622 if (CTAI.PartialOrdering &&
5623 isUndeducedAuto(NTTPType, /*DecltypeAuto=*/false) &&
5624 isUndeducedAuto(getTypeOfConstantTemplateParameter(Arg),
5625 /*DecltypeAuto=*/true))
5626 return true;
5627
5628 if (NTTPType->isInstantiationDependentType()) {
5629 // Do substitution on the type of the non-type template parameter.
5630 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5631 CTAI.SugaredConverted,
5632 SourceRange(TemplateLoc, RAngleLoc));
5633 if (Inst.isInvalid())
5634 return true;
5635
5637 /*Final=*/true);
5638 MLTAL.addOuterRetainedLevels(NTTP->getDepth());
5639 // If the parameter is a pack expansion, expand this slice of the pack.
5640 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5641 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5642 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5643 NTTP->getDeclName());
5644 } else {
5645 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5646 NTTP->getDeclName());
5647 }
5648
5649 // If that worked, check the non-type template parameter type
5650 // for validity.
5651 if (!NTTPType.isNull())
5652 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5653 NTTP->getLocation());
5654 if (NTTPType.isNull())
5655 return true;
5656 }
5657
5658 auto checkExpr = [&](Expr *E) -> Expr * {
5659 TemplateArgument SugaredResult, CanonicalResult;
5661 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5662 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5663 // If the current template argument causes an error, give up now.
5664 if (Res.isInvalid())
5665 return nullptr;
5666 CTAI.SugaredConverted.push_back(SugaredResult);
5667 CTAI.CanonicalConverted.push_back(CanonicalResult);
5668 return Res.get();
5669 };
5670
5671 switch (Arg.getKind()) {
5673 llvm_unreachable("Should never see a NULL template argument here");
5674
5676 Expr *E = Arg.getAsExpr();
5677 Expr *R = checkExpr(E);
5678 if (!R)
5679 return true;
5680 // If the resulting expression is new, then use it in place of the
5681 // old expression in the template argument.
5682 if (R != E) {
5683 TemplateArgument TA(R, /*IsCanonical=*/false);
5684 ArgLoc = TemplateArgumentLoc(TA, R);
5685 }
5686 break;
5687 }
5688
5689 // As for the converted NTTP kinds, they still might need another
5690 // conversion, as the new corresponding parameter might be different.
5691 // Ideally, we would always perform substitution starting with sugared types
5692 // and never need these, as we would still have expressions. Since these are
5693 // needed so rarely, it's probably a better tradeoff to just convert them
5694 // back to expressions.
5699 // FIXME: StructuralValue is untested here.
5700 ExprResult R =
5702 assert(R.isUsable());
5703 if (!checkExpr(R.get()))
5704 return true;
5705 break;
5706 }
5707
5710 // We were given a template template argument. It may not be ill-formed;
5711 // see below.
5714 // We have a template argument such as \c T::template X, which we
5715 // parsed as a template template argument. However, since we now
5716 // know that we need a non-type template argument, convert this
5717 // template name into an expression.
5718
5719 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5720 ArgLoc.getTemplateNameLoc());
5721
5722 CXXScopeSpec SS;
5723 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5724 // FIXME: the template-template arg was a DependentTemplateName,
5725 // so it was provided with a template keyword. However, its source
5726 // location is not stored in the template argument structure.
5727 SourceLocation TemplateKWLoc;
5729 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5730 nullptr);
5731
5732 // If we parsed the template argument as a pack expansion, create a
5733 // pack expansion expression.
5736 if (E.isInvalid())
5737 return true;
5738 }
5739
5740 TemplateArgument SugaredResult, CanonicalResult;
5742 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5743 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5744 if (E.isInvalid())
5745 return true;
5746
5747 CTAI.SugaredConverted.push_back(SugaredResult);
5748 CTAI.CanonicalConverted.push_back(CanonicalResult);
5749 break;
5750 }
5751
5752 // We have a template argument that actually does refer to a class
5753 // template, alias template, or template template parameter, and
5754 // therefore cannot be a non-type template argument.
5755 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5756 << ArgLoc.getSourceRange();
5758
5759 return true;
5760
5762 // We have a non-type template parameter but the template
5763 // argument is a type.
5764
5765 // C++ [temp.arg]p2:
5766 // In a template-argument, an ambiguity between a type-id and
5767 // an expression is resolved to a type-id, regardless of the
5768 // form of the corresponding template-parameter.
5769 //
5770 // We warn specifically about this case, since it can be rather
5771 // confusing for users.
5772 QualType T = Arg.getAsType();
5773 SourceRange SR = ArgLoc.getSourceRange();
5774 if (T->isFunctionType())
5775 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5776 else
5777 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5779 return true;
5780 }
5781
5783 llvm_unreachable("Caller must expand template argument packs");
5784 }
5785
5786 return false;
5787 }
5788
5789
5790 // Check template template parameters.
5792
5793 TemplateParameterList *Params = TempParm->getTemplateParameters();
5794 if (TempParm->isExpandedParameterPack())
5795 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5796
5797 // Substitute into the template parameter list of the template
5798 // template parameter, since previously-supplied template arguments
5799 // may appear within the template template parameter.
5800 //
5801 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5802 {
5803 // Set up a template instantiation context.
5805 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5806 CTAI.SugaredConverted,
5807 SourceRange(TemplateLoc, RAngleLoc));
5808 if (Inst.isInvalid())
5809 return true;
5810
5811 Params = SubstTemplateParams(
5812 Params, CurContext,
5814 /*Final=*/true),
5815 /*EvaluateConstraints=*/false);
5816 if (!Params)
5817 return true;
5818 }
5819
5820 // C++1z [temp.local]p1: (DR1004)
5821 // When [the injected-class-name] is used [...] as a template-argument for
5822 // a template template-parameter [...] it refers to the class template
5823 // itself.
5824 if (Arg.getKind() == TemplateArgument::Type) {
5826 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5827 if (!ConvertedArg.getArgument().isNull())
5828 ArgLoc = ConvertedArg;
5829 }
5830
5831 switch (Arg.getKind()) {
5833 llvm_unreachable("Should never see a NULL template argument here");
5834
5837 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5838 CTAI.PartialOrdering,
5839 &CTAI.StrictPackMatch))
5840 return true;
5841
5842 CTAI.SugaredConverted.push_back(Arg);
5843 CTAI.CanonicalConverted.push_back(
5844 Context.getCanonicalTemplateArgument(Arg));
5845 break;
5846
5849 auto Kind = 0;
5850 switch (TempParm->templateParameterKind()) {
5852 Kind = 1;
5853 break;
5855 Kind = 2;
5856 break;
5857 default:
5858 break;
5859 }
5860
5861 // We have a template template parameter but the template
5862 // argument does not refer to a template.
5863 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5864 << Kind << getLangOpts().CPlusPlus11;
5865 return true;
5866 }
5867
5872 llvm_unreachable("non-type argument with template template parameter");
5873
5875 llvm_unreachable("Caller must expand template argument packs");
5876 }
5877
5878 return false;
5879}
5880
5881/// Diagnose a missing template argument.
5882template <typename TemplateParmDecl>
5884 TemplateDecl *TD,
5885 const TemplateParmDecl *D) {
5886 // Dig out the most recent declaration of the template parameter; there may be
5887 // declarations of the template that are more recent than TD.
5889 ->getTemplateParameters()
5890 ->getParam(D->getIndex()));
5891
5892 // If there's a default argument that's not reachable, diagnose that we're
5893 // missing a module import.
5895 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5897 D->getDefaultArgumentLoc(), Modules,
5899 /*Recover*/true);
5900 return;
5901 }
5902
5903 // FIXME: If there's a more recent default argument that *is* visible,
5904 // diagnose that it was declared too late.
5905
5907
5908 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5909 << /*not enough args*/0
5911 << TD;
5912 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5913}
5914
5915/// Check that the given template argument list is well-formed
5916/// for specializing the given template.
5918 TemplateDecl *Template, SourceLocation TemplateLoc,
5919 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5920 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5921 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5923 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,
5924 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5926}
5927
5928/// Check that the given template argument list is well-formed
5929/// for specializing the given template.
5932 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5933 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5934 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5936
5938 *ConstraintsNotSatisfied = false;
5939
5940 // Make a copy of the template arguments for processing. Only make the
5941 // changes at the end when successful in matching the arguments to the
5942 // template.
5943 TemplateArgumentListInfo NewArgs = TemplateArgs;
5944
5945 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5946
5947 // C++23 [temp.arg.general]p1:
5948 // [...] The type and form of each template-argument specified in
5949 // a template-id shall match the type and form specified for the
5950 // corresponding parameter declared by the template in its
5951 // template-parameter-list.
5952 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5953 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5954 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5955 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5956 LocalInstantiationScope InstScope(*this, true);
5957 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5958 ParamEnd = Params->end(),
5959 Param = ParamBegin;
5960 Param != ParamEnd;
5961 /* increment in loop */) {
5962 if (size_t ParamIdx = Param - ParamBegin;
5963 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5964 // All written arguments should have been consumed by this point.
5965 assert(ArgIdx == NumArgs && "bad default argument deduction");
5966 if (ParamIdx == DefaultArgs.StartPos) {
5967 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5968 // Default arguments from a DeducedTemplateName are already converted.
5969 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5970 CTAI.SugaredConverted.push_back(DefArg);
5971 CTAI.CanonicalConverted.push_back(
5972 Context.getCanonicalTemplateArgument(DefArg));
5973 ++Param;
5974 }
5975 continue;
5976 }
5977 }
5978
5979 // If we have an expanded parameter pack, make sure we don't have too
5980 // many arguments.
5981 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5982 if (*Expansions == SugaredArgumentPack.size()) {
5983 // We're done with this parameter pack. Pack up its arguments and add
5984 // them to the list.
5985 CTAI.SugaredConverted.push_back(
5986 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5987 SugaredArgumentPack.clear();
5988
5989 CTAI.CanonicalConverted.push_back(
5990 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5991 CanonicalArgumentPack.clear();
5992
5993 // This argument is assigned to the next parameter.
5994 ++Param;
5995 continue;
5996 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5997 // Not enough arguments for this parameter pack.
5998 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5999 << /*not enough args*/0
6001 << Template;
6003 return true;
6004 }
6005 }
6006
6007 // Check for builtins producing template packs in this context, we do not
6008 // support them yet.
6009 if (const NonTypeTemplateParmDecl *NTTP =
6010 dyn_cast<NonTypeTemplateParmDecl>(*Param);
6011 NTTP && NTTP->isPackExpansion()) {
6012 auto TL = NTTP->getTypeSourceInfo()
6013 ->getTypeLoc()
6016 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
6017 for (const auto &UPP : Unexpanded) {
6018 auto *TST = dyn_cast<const TemplateSpecializationType *>(UPP.first);
6019 if (!TST)
6020 continue;
6021 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
6022 // Expanding a built-in pack in this context is not yet supported.
6023 Diag(TL.getEllipsisLoc(),
6024 diag::err_unsupported_builtin_template_pack_expansion)
6025 << TST->getTemplateName();
6026 return true;
6027 }
6028 }
6029
6030 if (ArgIdx < NumArgs) {
6031 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6032 bool NonPackParameter =
6033 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
6034 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6035
6036 if (ArgIsExpansion && CTAI.MatchingTTP) {
6037 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6038 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6039 ++Param) {
6040 TemplateArgument &Arg = Args[Param - First];
6041 Arg = ArgLoc.getArgument();
6042 if (!(*Param)->isTemplateParameterPack() ||
6043 getExpandedPackSize(*Param))
6044 Arg = Arg.getPackExpansionPattern();
6045 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6046 SaveAndRestore _1(CTAI.PartialOrdering, false);
6047 SaveAndRestore _2(CTAI.MatchingTTP, true);
6048 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
6049 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6051 return true;
6052 Arg = NewArgLoc.getArgument();
6053 CTAI.CanonicalConverted.back().setIsDefaulted(
6054 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,
6055 CTAI.CanonicalConverted,
6056 Params->getDepth()));
6057 }
6058 ArgLoc = TemplateArgumentLoc(
6061 } else {
6062 SaveAndRestore _1(CTAI.PartialOrdering, false);
6063 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
6064 RAngleLoc, SugaredArgumentPack.size(), CTAI,
6066 return true;
6067 CTAI.CanonicalConverted.back().setIsDefaulted(
6068 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),
6069 *Param, CTAI.CanonicalConverted,
6070 Params->getDepth()));
6071 if (ArgIsExpansion && NonPackParameter) {
6072 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6073 // alias template, builtin template, or concept, and it's not part of
6074 // a parameter pack. This can't be canonicalized, so reject it now.
6076 Template)) {
6077 unsigned DiagSelect = isa<ConceptDecl>(Template) ? 1
6079 : 0;
6080 Diag(ArgLoc.getLocation(),
6081 diag::err_template_expansion_into_fixed_list)
6082 << DiagSelect << ArgLoc.getSourceRange();
6084 return true;
6085 }
6086 }
6087 }
6088
6089 // We're now done with this argument.
6090 ++ArgIdx;
6091
6092 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6093 // Directly convert the remaining arguments, because we don't know what
6094 // parameters they'll match up with.
6095
6096 if (!SugaredArgumentPack.empty()) {
6097 // If we were part way through filling in an expanded parameter pack,
6098 // fall back to just producing individual arguments.
6099 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
6100 SugaredArgumentPack.begin(),
6101 SugaredArgumentPack.end());
6102 SugaredArgumentPack.clear();
6103
6104 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
6105 CanonicalArgumentPack.begin(),
6106 CanonicalArgumentPack.end());
6107 CanonicalArgumentPack.clear();
6108 }
6109
6110 while (ArgIdx < NumArgs) {
6111 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6112 CTAI.SugaredConverted.push_back(Arg);
6113 CTAI.CanonicalConverted.push_back(
6114 Context.getCanonicalTemplateArgument(Arg));
6115 ++ArgIdx;
6116 }
6117
6118 return false;
6119 }
6120
6121 if ((*Param)->isTemplateParameterPack()) {
6122 // The template parameter was a template parameter pack, so take the
6123 // deduced argument and place it on the argument pack. Note that we
6124 // stay on the same template parameter so that we can deduce more
6125 // arguments.
6126 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
6127 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
6128 } else {
6129 // Move to the next template parameter.
6130 ++Param;
6131 }
6132 continue;
6133 }
6134
6135 // If we're checking a partial template argument list, we're done.
6136 if (PartialTemplateArgs) {
6137 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6138 CTAI.SugaredConverted.push_back(
6139 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6140 CTAI.CanonicalConverted.push_back(
6141 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6142 }
6143 return false;
6144 }
6145
6146 // If we have a template parameter pack with no more corresponding
6147 // arguments, just break out now and we'll fill in the argument pack below.
6148 if ((*Param)->isTemplateParameterPack()) {
6149 assert(!getExpandedPackSize(*Param) &&
6150 "Should have dealt with this already");
6151
6152 // A non-expanded parameter pack before the end of the parameter list
6153 // only occurs for an ill-formed template parameter list, unless we've
6154 // got a partial argument list for a function template, so just bail out.
6155 if (Param + 1 != ParamEnd) {
6156 assert(
6157 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6158 "Concept templates must have parameter packs at the end.");
6159 return true;
6160 }
6161
6162 CTAI.SugaredConverted.push_back(
6163 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6164 SugaredArgumentPack.clear();
6165
6166 CTAI.CanonicalConverted.push_back(
6167 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6168 CanonicalArgumentPack.clear();
6169
6170 ++Param;
6171 continue;
6172 }
6173
6174 // Check whether we have a default argument.
6175 bool HasDefaultArg;
6176
6177 // Retrieve the default template argument from the template
6178 // parameter. For each kind of template parameter, we substitute the
6179 // template arguments provided thus far and any "outer" template arguments
6180 // (when the template parameter was part of a nested template) into
6181 // the default argument.
6183 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6184 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6185
6186 if (Arg.getArgument().isNull()) {
6187 if (!HasDefaultArg) {
6188 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6189 diagnoseMissingArgument(*this, TemplateLoc, Template, TTP);
6190 else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*Param))
6191 diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP);
6192 else
6193 diagnoseMissingArgument(*this, TemplateLoc, Template,
6195 }
6196 return true;
6197 }
6198
6199 // Introduce an instantiation record that describes where we are using
6200 // the default template argument. We're not actually instantiating a
6201 // template here, we just create this object to put a note into the
6202 // context stack.
6203 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6204 CTAI.SugaredConverted,
6205 SourceRange(TemplateLoc, RAngleLoc));
6206 if (Inst.isInvalid())
6207 return true;
6208
6209 SaveAndRestore _1(CTAI.PartialOrdering, false);
6210 SaveAndRestore _2(CTAI.MatchingTTP, false);
6211 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6212 // Check the default template argument.
6213 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6214 CTAI, CTAK_Specified))
6215 return true;
6216
6217 CTAI.SugaredConverted.back().setIsDefaulted(true);
6218 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6219
6220 // Core issue 150 (assumed resolution): if this is a template template
6221 // parameter, keep track of the default template arguments from the
6222 // template definition.
6223 if (isTemplateTemplateParameter)
6224 NewArgs.addArgument(Arg);
6225
6226 // Move to the next template parameter and argument.
6227 ++Param;
6228 ++ArgIdx;
6229 }
6230
6231 // If we're performing a partial argument substitution, allow any trailing
6232 // pack expansions; they might be empty. This can happen even if
6233 // PartialTemplateArgs is false (the list of arguments is complete but
6234 // still dependent).
6235 if (CTAI.MatchingTTP ||
6237 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6238 while (ArgIdx < NumArgs &&
6239 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6240 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6241 CTAI.SugaredConverted.push_back(Arg);
6242 CTAI.CanonicalConverted.push_back(
6243 Context.getCanonicalTemplateArgument(Arg));
6244 }
6245 }
6246
6247 // If we have any leftover arguments, then there were too many arguments.
6248 // Complain and fail.
6249 if (ArgIdx < NumArgs) {
6250 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6251 << /*too many args*/1
6253 << Template
6254 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6256 return true;
6257 }
6258
6259 // No problems found with the new argument list, propagate changes back
6260 // to caller.
6261 if (UpdateArgsWithConversions)
6262 TemplateArgs = std::move(NewArgs);
6263
6264 if (!PartialTemplateArgs) {
6265 // Setup the context/ThisScope for the case where we are needing to
6266 // re-instantiate constraints outside of normal instantiation.
6267 DeclContext *NewContext = Template->getDeclContext();
6268
6269 // If this template is in a template, make sure we extract the templated
6270 // decl.
6271 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6272 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6273 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6274
6275 Qualifiers ThisQuals;
6276 if (const auto *Method =
6277 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6278 ThisQuals = Method->getMethodQualifiers();
6279
6280 ContextRAII Context(*this, NewContext);
6281 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6282
6284 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,
6285 /*RelativeToPrimary=*/true,
6286 /*Pattern=*/nullptr,
6287 /*ForConceptInstantiation=*/true);
6288 if (!isa<ConceptDecl>(Template) &&
6290 Template, MLTAL,
6291 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6294 return true;
6295 }
6296 }
6297
6298 return false;
6299}
6300
6301namespace {
6302 class UnnamedLocalNoLinkageFinder
6303 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6304 {
6305 Sema &S;
6306 SourceRange SR;
6307
6309
6310 public:
6311 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6312
6313 bool Visit(QualType T) {
6314 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6315 }
6316
6317#define TYPE(Class, Parent) \
6318 bool Visit##Class##Type(const Class##Type *);
6319#define ABSTRACT_TYPE(Class, Parent) \
6320 bool Visit##Class##Type(const Class##Type *) { return false; }
6321#define NON_CANONICAL_TYPE(Class, Parent) \
6322 bool Visit##Class##Type(const Class##Type *) { return false; }
6323#include "clang/AST/TypeNodes.inc"
6324
6325 bool VisitTagDecl(const TagDecl *Tag);
6326 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6327 };
6328} // end anonymous namespace
6329
6330bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6331 return false;
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6335 return Visit(T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6339 return Visit(T->getPointeeType());
6340}
6341
6342bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6343 const BlockPointerType* T) {
6344 return Visit(T->getPointeeType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6348 const LValueReferenceType* T) {
6349 return Visit(T->getPointeeType());
6350}
6351
6352bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6353 const RValueReferenceType* T) {
6354 return Visit(T->getPointeeType());
6355}
6356
6357bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6358 const MemberPointerType *T) {
6359 if (Visit(T->getPointeeType()))
6360 return true;
6361 if (auto *RD = T->getMostRecentCXXRecordDecl())
6362 return VisitTagDecl(RD);
6363 return VisitNestedNameSpecifier(T->getQualifier());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6367 const ConstantArrayType* T) {
6368 return Visit(T->getElementType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6372 const IncompleteArrayType* T) {
6373 return Visit(T->getElementType());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6377 const VariableArrayType* T) {
6378 return Visit(T->getElementType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6382 const DependentSizedArrayType* T) {
6383 return Visit(T->getElementType());
6384}
6385
6386bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6388 return Visit(T->getElementType());
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6392 const DependentSizedMatrixType *T) {
6393 return Visit(T->getElementType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6398 return Visit(T->getPointeeType());
6399}
6400
6401bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6402 return Visit(T->getElementType());
6403}
6404
6405bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6406 const DependentVectorType *T) {
6407 return Visit(T->getElementType());
6408}
6409
6410bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6411 return Visit(T->getElementType());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6415 const ConstantMatrixType *T) {
6416 return Visit(T->getElementType());
6417}
6418
6419bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6420 const FunctionProtoType* T) {
6421 for (const auto &A : T->param_types()) {
6422 if (Visit(A))
6423 return true;
6424 }
6425
6426 return Visit(T->getReturnType());
6427}
6428
6429bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6430 const FunctionNoProtoType* T) {
6431 return Visit(T->getReturnType());
6432}
6433
6434bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6435 const UnresolvedUsingType*) {
6436 return false;
6437}
6438
6439bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6440 return false;
6441}
6442
6443bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6444 return Visit(T->getUnmodifiedType());
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6448 return false;
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6452 const PackIndexingType *) {
6453 return false;
6454}
6455
6456bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6457 const UnaryTransformType*) {
6458 return false;
6459}
6460
6461bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6462 return Visit(T->getDeducedType());
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6466 const DeducedTemplateSpecializationType *T) {
6467 return Visit(T->getDeducedType());
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6471 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6472}
6473
6474bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6475 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6476}
6477
6478bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6479 const TemplateTypeParmType*) {
6480 return false;
6481}
6482
6483bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6484 const SubstTemplateTypeParmPackType *) {
6485 return false;
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6489 const SubstBuiltinTemplatePackType *) {
6490 return false;
6491}
6492
6493bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6494 const TemplateSpecializationType*) {
6495 return false;
6496}
6497
6498bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6499 const InjectedClassNameType* T) {
6500 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());
6501}
6502
6503bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6504 const DependentNameType* T) {
6505 return VisitNestedNameSpecifier(T->getQualifier());
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6509 const PackExpansionType* T) {
6510 return Visit(T->getPattern());
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6514 return false;
6515}
6516
6517bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6518 const ObjCInterfaceType *) {
6519 return false;
6520}
6521
6522bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6523 const ObjCObjectPointerType *) {
6524 return false;
6525}
6526
6527bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6528 return Visit(T->getValueType());
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6532 const OverflowBehaviorType *T) {
6533 return Visit(T->getUnderlyingType());
6534}
6535
6536bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6537 return false;
6538}
6539
6540bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6541 return false;
6542}
6543
6544bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6545 const ArrayParameterType *T) {
6546 return VisitConstantArrayType(T);
6547}
6548
6549bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6550 const DependentBitIntType *T) {
6551 return false;
6552}
6553
6554bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6555 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6556 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6557 ? diag::warn_cxx98_compat_template_arg_local_type
6558 : diag::ext_template_arg_local_type)
6559 << S.Context.getCanonicalTagType(Tag) << SR;
6560 return true;
6561 }
6562
6563 if (!Tag->hasNameForLinkage()) {
6564 S.Diag(SR.getBegin(),
6565 S.getLangOpts().CPlusPlus11 ?
6566 diag::warn_cxx98_compat_template_arg_unnamed_type :
6567 diag::ext_template_arg_unnamed_type) << SR;
6568 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6569 return true;
6570 }
6571
6572 return false;
6573}
6574
6575bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6576 NestedNameSpecifier NNS) {
6577 switch (NNS.getKind()) {
6582 return false;
6584 return Visit(QualType(NNS.getAsType(), 0));
6585 }
6586 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6587}
6588
6589bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6590 const HLSLAttributedResourceType *T) {
6591 if (T->hasContainedType() && Visit(T->getContainedType()))
6592 return true;
6593 return Visit(T->getWrappedType());
6594}
6595
6596bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6597 const HLSLInlineSpirvType *T) {
6598 for (auto &Operand : T->getOperands())
6599 if (Operand.isConstant() && Operand.isLiteral())
6600 if (Visit(Operand.getResultType()))
6601 return true;
6602 return false;
6603}
6604
6606 assert(ArgInfo && "invalid TypeSourceInfo");
6607 QualType Arg = ArgInfo->getType();
6608 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6609 QualType CanonArg = Context.getCanonicalType(Arg);
6610
6611 if (CanonArg->isVariablyModifiedType()) {
6612 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6613 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6614 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6615 }
6616
6617 // C++03 [temp.arg.type]p2:
6618 // A local type, a type with no linkage, an unnamed type or a type
6619 // compounded from any of these types shall not be used as a
6620 // template-argument for a template type-parameter.
6621 //
6622 // C++11 allows these, and even in C++03 we allow them as an extension with
6623 // a warning.
6624 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6625 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6626 (void)Finder.Visit(CanonArg);
6627 }
6628
6629 return false;
6630}
6631
6637
6638/// Determine whether the given template argument is a null pointer
6639/// value of the appropriate type.
6642 QualType ParamType, Expr *Arg,
6643 Decl *Entity = nullptr) {
6644 if (Arg->isValueDependent() || Arg->isTypeDependent())
6645 return NPV_NotNullPointer;
6646
6647 // dllimport'd entities aren't constant but are available inside of template
6648 // arguments.
6649 if (Entity && Entity->hasAttr<DLLImportAttr>())
6650 return NPV_NotNullPointer;
6651
6652 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6653 llvm_unreachable(
6654 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6655
6656 if (!S.getLangOpts().CPlusPlus11)
6657 return NPV_NotNullPointer;
6658
6659 // Determine whether we have a constant expression.
6661 if (ArgRV.isInvalid())
6662 return NPV_Error;
6663 Arg = ArgRV.get();
6664
6665 Expr::EvalResult EvalResult;
6667 EvalResult.Diag = &Notes;
6668 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6669 EvalResult.HasSideEffects) {
6670 SourceLocation DiagLoc = Arg->getExprLoc();
6671
6672 // If our only note is the usual "invalid subexpression" note, just point
6673 // the caret at its location rather than producing an essentially
6674 // redundant note.
6675 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6676 diag::note_invalid_subexpr_in_const_expr) {
6677 DiagLoc = Notes[0].first;
6678 Notes.clear();
6679 }
6680
6681 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6682 << Arg->getType() << Arg->getSourceRange();
6683 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6684 S.Diag(Notes[I].first, Notes[I].second);
6685
6687 return NPV_Error;
6688 }
6689
6690 // C++11 [temp.arg.nontype]p1:
6691 // - an address constant expression of type std::nullptr_t
6692 if (Arg->getType()->isNullPtrType())
6693 return NPV_NullPointer;
6694
6695 // - a constant expression that evaluates to a null pointer value (4.10); or
6696 // - a constant expression that evaluates to a null member pointer value
6697 // (4.11); or
6698 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6699 (EvalResult.Val.isMemberPointer() &&
6700 !EvalResult.Val.getMemberPointerDecl())) {
6701 // If our expression has an appropriate type, we've succeeded.
6702 bool ObjCLifetimeConversion;
6703 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6704 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6705 ObjCLifetimeConversion))
6706 return NPV_NullPointer;
6707
6708 // The types didn't match, but we know we got a null pointer; complain,
6709 // then recover as if the types were correct.
6710 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6711 << Arg->getType() << ParamType << Arg->getSourceRange();
6713 return NPV_NullPointer;
6714 }
6715
6716 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6717 // We found a pointer that isn't null, but doesn't refer to an object.
6718 // We could just return NPV_NotNullPointer, but we can print a better
6719 // message with the information we have here.
6720 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6721 << EvalResult.Val.getAsString(S.Context, ParamType);
6723 return NPV_Error;
6724 }
6725
6726 // If we don't have a null pointer value, but we do have a NULL pointer
6727 // constant, suggest a cast to the appropriate type.
6729 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6730 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6731 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6733 ")");
6735 return NPV_NullPointer;
6736 }
6737
6738 // FIXME: If we ever want to support general, address-constant expressions
6739 // as non-type template arguments, we should return the ExprResult here to
6740 // be interpreted by the caller.
6741 return NPV_NotNullPointer;
6742}
6743
6744/// Checks whether the given template argument is compatible with its
6745/// template parameter.
6746static bool
6748 QualType ParamType, Expr *ArgIn,
6749 Expr *Arg, QualType ArgType) {
6750 bool ObjCLifetimeConversion;
6751 if (ParamType->isPointerType() &&
6752 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6753 S.IsQualificationConversion(ArgType, ParamType, false,
6754 ObjCLifetimeConversion)) {
6755 // For pointer-to-object types, qualification conversions are
6756 // permitted.
6757 } else {
6758 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6759 if (!ParamRef->getPointeeType()->isFunctionType()) {
6760 // C++ [temp.arg.nontype]p5b3:
6761 // For a non-type template-parameter of type reference to
6762 // object, no conversions apply. The type referred to by the
6763 // reference may be more cv-qualified than the (otherwise
6764 // identical) type of the template- argument. The
6765 // template-parameter is bound directly to the
6766 // template-argument, which shall be an lvalue.
6767
6768 // FIXME: Other qualifiers?
6769 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6770 unsigned ArgQuals = ArgType.getCVRQualifiers();
6771
6772 if ((ParamQuals | ArgQuals) != ParamQuals) {
6773 S.Diag(Arg->getBeginLoc(),
6774 diag::err_template_arg_ref_bind_ignores_quals)
6775 << ParamType << Arg->getType() << Arg->getSourceRange();
6777 return true;
6778 }
6779 }
6780 }
6781
6782 // At this point, the template argument refers to an object or
6783 // function with external linkage. We now need to check whether the
6784 // argument and parameter types are compatible.
6785 if (!S.Context.hasSameUnqualifiedType(ArgType,
6786 ParamType.getNonReferenceType())) {
6787 // We can't perform this conversion or binding.
6788 if (ParamType->isReferenceType())
6789 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6790 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6791 else
6792 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6793 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6795 return true;
6796 }
6797 }
6798
6799 return false;
6800}
6801
6802/// Checks whether the given template argument is the address
6803/// of an object or function according to C++ [temp.arg.nontype]p1.
6805 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6806 bool IsSpecified, TemplateArgument &SugaredConverted,
6807 TemplateArgument &CanonicalConverted) {
6808 Expr *Arg = ArgIn;
6809 QualType ArgType = Arg->getType();
6810
6811 bool AddressTaken = false;
6812 SourceLocation AddrOpLoc;
6813 if (S.getLangOpts().MicrosoftExt) {
6814 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6815 // dereference and address-of operators.
6816 Arg = Arg->IgnoreParenCasts();
6817
6818 bool ExtWarnMSTemplateArg = false;
6819 UnaryOperatorKind FirstOpKind;
6820 SourceLocation FirstOpLoc;
6821 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6822 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6823 if (UnOpKind == UO_Deref)
6824 ExtWarnMSTemplateArg = true;
6825 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6826 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6827 if (!AddrOpLoc.isValid()) {
6828 FirstOpKind = UnOpKind;
6829 FirstOpLoc = UnOp->getOperatorLoc();
6830 }
6831 } else
6832 break;
6833 }
6834 if (FirstOpLoc.isValid()) {
6835 if (ExtWarnMSTemplateArg)
6836 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6837 << ArgIn->getSourceRange();
6838
6839 if (FirstOpKind == UO_AddrOf)
6840 AddressTaken = true;
6841 else if (Arg->getType()->isPointerType()) {
6842 // We cannot let pointers get dereferenced here, that is obviously not a
6843 // constant expression.
6844 assert(FirstOpKind == UO_Deref);
6845 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6846 << Arg->getSourceRange();
6847 }
6848 }
6849 } else {
6850 // See through any implicit casts we added to fix the type.
6851 // Also ignore parentheses for deduced template arguments.
6852 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6853
6854 // C++ [temp.arg.nontype]p1:
6855 //
6856 // A template-argument for a non-type, non-template
6857 // template-parameter shall be one of: [...]
6858 //
6859 // -- the address of an object or function with external
6860 // linkage, including function templates and function
6861 // template-ids but excluding non-static class members,
6862 // expressed as & id-expression where the & is optional if
6863 // the name refers to a function or array, or if the
6864 // corresponding template-parameter is a reference; or
6865
6866 // In C++98/03 mode, give an extension warning on any extra parentheses.
6867 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6868 if (IsSpecified) {
6869 bool ExtraParens = false;
6870 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6871 if (!ExtraParens) {
6872 S.DiagCompat(Arg->getBeginLoc(),
6873 diag_compat::template_arg_extra_parens)
6874 << Arg->getSourceRange();
6875 ExtraParens = true;
6876 }
6877
6878 Arg = Parens->getSubExpr();
6879 }
6880 }
6881
6882 while (SubstNonTypeTemplateParmExpr *subst =
6883 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6884 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6885
6886 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6887 if (UnOp->getOpcode() == UO_AddrOf) {
6888 Arg = UnOp->getSubExpr();
6889 AddressTaken = true;
6890 AddrOpLoc = UnOp->getOperatorLoc();
6891 }
6892 }
6893
6894 while (SubstNonTypeTemplateParmExpr *subst =
6895 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6896 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6897 }
6898
6899 ValueDecl *Entity = nullptr;
6900 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6901 Entity = DRE->getDecl();
6902 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6903 Entity = CUE->getGuidDecl();
6904
6905 // If our parameter has pointer type, check for a null template value.
6906 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6907 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6908 Entity)) {
6909 case NPV_NullPointer:
6910 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6911 SugaredConverted = TemplateArgument(ParamType,
6912 /*isNullPtr=*/true);
6913 CanonicalConverted =
6915 /*isNullPtr=*/true);
6916 return false;
6917
6918 case NPV_Error:
6919 return true;
6920
6921 case NPV_NotNullPointer:
6922 break;
6923 }
6924 }
6925
6926 // Stop checking the precise nature of the argument if it is value dependent,
6927 // it should be checked when instantiated.
6928 if (Arg->isValueDependent()) {
6929 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6930 CanonicalConverted =
6931 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6932 return false;
6933 }
6934
6935 if (!Entity) {
6936 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6937 << Arg->getSourceRange();
6939 return true;
6940 }
6941
6942 // Cannot refer to non-static data members
6943 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6944 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6945 << Entity << Arg->getSourceRange();
6947 return true;
6948 }
6949
6950 // Cannot refer to non-static member functions
6951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6952 if (!Method->isStatic()) {
6953 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6954 << Method << Arg->getSourceRange();
6956 return true;
6957 }
6958 }
6959
6960 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6961 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6962 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6963
6964 // A non-type template argument must refer to an object or function.
6965 if (!Func && !Var && !Guid) {
6966 // We found something, but we don't know specifically what it is.
6967 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6968 << Arg->getSourceRange();
6969 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6970 return true;
6971 }
6972
6973 // Address / reference template args must have external linkage in C++98.
6974 if (Entity->getFormalLinkage() == Linkage::Internal) {
6975 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_object_internal)
6976 << !Func << Entity << Arg->getSourceRange();
6977 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6978 << !Func;
6979 } else if (!Entity->hasLinkage()) {
6980 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6981 << !Func << Entity << Arg->getSourceRange();
6982 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6983 << !Func;
6984 return true;
6985 }
6986
6987 if (Var) {
6988 // A value of reference type is not an object.
6989 if (Var->getType()->isReferenceType()) {
6990 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6991 << Var->getType() << Arg->getSourceRange();
6993 return true;
6994 }
6995
6996 // A template argument must have static storage duration.
6997 if (Var->getTLSKind()) {
6998 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6999 << Arg->getSourceRange();
7000 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7001 return true;
7002 }
7003 }
7004
7005 if (AddressTaken && ParamType->isReferenceType()) {
7006 // If we originally had an address-of operator, but the
7007 // parameter has reference type, complain and (if things look
7008 // like they will work) drop the address-of operator.
7009 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7010 ParamType.getNonReferenceType())) {
7011 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7012 << ParamType;
7014 return true;
7015 }
7016
7017 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7018 << ParamType
7019 << FixItHint::CreateRemoval(AddrOpLoc);
7021
7022 ArgType = Entity->getType();
7023 }
7024
7025 // If the template parameter has pointer type, either we must have taken the
7026 // address or the argument must decay to a pointer.
7027 if (!AddressTaken && ParamType->isPointerType()) {
7028 if (Func) {
7029 // Function-to-pointer decay.
7030 ArgType = S.Context.getPointerType(Func->getType());
7031 } else if (Entity->getType()->isArrayType()) {
7032 // Array-to-pointer decay.
7033 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7034 } else {
7035 // If the template parameter has pointer type but the address of
7036 // this object was not taken, complain and (possibly) recover by
7037 // taking the address of the entity.
7038 ArgType = S.Context.getPointerType(Entity->getType());
7039 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7040 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7041 << ParamType;
7043 return true;
7044 }
7045
7046 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7047 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7048
7050 }
7051 }
7052
7053 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7054 Arg, ArgType))
7055 return true;
7056
7057 // Create the template argument.
7058 SugaredConverted = TemplateArgument(Entity, ParamType);
7059 CanonicalConverted =
7061 S.Context.getCanonicalType(ParamType));
7062 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7063 return false;
7064}
7065
7066/// Checks whether the given template argument is a pointer to
7067/// member constant according to C++ [temp.arg.nontype]p1.
7069 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7070 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7071 bool Invalid = false;
7072
7073 Expr *Arg = ResultArg;
7074 bool ObjCLifetimeConversion;
7075
7076 // C++ [temp.arg.nontype]p1:
7077 //
7078 // A template-argument for a non-type, non-template
7079 // template-parameter shall be one of: [...]
7080 //
7081 // -- a pointer to member expressed as described in 5.3.1.
7082 DeclRefExpr *DRE = nullptr;
7083
7084 // In C++98/03 mode, give an extension warning on any extra parentheses.
7085 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7086 bool ExtraParens = false;
7087 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7088 if (!Invalid && !ExtraParens) {
7089 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
7090 << Arg->getSourceRange();
7091 ExtraParens = true;
7092 }
7093
7094 Arg = Parens->getSubExpr();
7095 }
7096
7097 while (SubstNonTypeTemplateParmExpr *subst =
7098 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7099 Arg = subst->getReplacement()->IgnoreImpCasts();
7100
7101 // A pointer-to-member constant written &Class::member.
7102 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7103 if (UnOp->getOpcode() == UO_AddrOf) {
7104 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7105 if (DRE && !DRE->getQualifier())
7106 DRE = nullptr;
7107 }
7108 }
7109 // A constant of pointer-to-member type.
7110 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7111 ValueDecl *VD = DRE->getDecl();
7112 if (VD->getType()->isMemberPointerType()) {
7114 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7115 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7116 CanonicalConverted =
7117 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7118 } else {
7119 SugaredConverted = TemplateArgument(VD, ParamType);
7120 CanonicalConverted =
7122 S.Context.getCanonicalType(ParamType));
7123 }
7124 return Invalid;
7125 }
7126 }
7127
7128 DRE = nullptr;
7129 }
7130
7131 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7132
7133 // Check for a null pointer value.
7134 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7135 Entity)) {
7136 case NPV_Error:
7137 return true;
7138 case NPV_NullPointer:
7139 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7140 SugaredConverted = TemplateArgument(ParamType,
7141 /*isNullPtr*/ true);
7142 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7143 /*isNullPtr*/ true);
7144 return false;
7145 case NPV_NotNullPointer:
7146 break;
7147 }
7148
7149 if (S.IsQualificationConversion(ResultArg->getType(),
7150 ParamType.getNonReferenceType(), false,
7151 ObjCLifetimeConversion)) {
7152 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7153 ResultArg->getValueKind())
7154 .get();
7155 } else if (!S.Context.hasSameUnqualifiedType(
7156 ResultArg->getType(), ParamType.getNonReferenceType())) {
7157 // We can't perform this conversion.
7158 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7159 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7161 return true;
7162 }
7163
7164 if (!DRE)
7165 return S.Diag(Arg->getBeginLoc(),
7166 diag::err_template_arg_not_pointer_to_member_form)
7167 << Arg->getSourceRange();
7168
7169 if (isa<FieldDecl>(DRE->getDecl()) ||
7171 isa<CXXMethodDecl>(DRE->getDecl())) {
7172 assert((isa<FieldDecl>(DRE->getDecl()) ||
7175 ->isImplicitObjectMemberFunction()) &&
7176 "Only non-static member pointers can make it here");
7177
7178 // Okay: this is the address of a non-static member, and therefore
7179 // a member pointer constant.
7180 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7181 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7182 CanonicalConverted =
7183 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7184 } else {
7185 ValueDecl *D = DRE->getDecl();
7186 SugaredConverted = TemplateArgument(D, ParamType);
7187 CanonicalConverted =
7189 S.Context.getCanonicalType(ParamType));
7190 }
7191 return Invalid;
7192 }
7193
7194 // We found something else, but we don't know specifically what it is.
7195 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7196 << Arg->getSourceRange();
7197 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7198 return true;
7199}
7200
7201/// Check a template argument against its corresponding
7202/// non-type template parameter.
7203///
7204/// This routine implements the semantics of C++ [temp.arg.nontype].
7205/// If an error occurred, it returns ExprError(); otherwise, it
7206/// returns the converted template argument. \p ParamType is the
7207/// type of the non-type template parameter after it has been instantiated.
7209 Expr *Arg,
7210 TemplateArgument &SugaredConverted,
7211 TemplateArgument &CanonicalConverted,
7212 bool StrictCheck,
7214 SourceLocation StartLoc = Arg->getBeginLoc();
7215 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7216 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7217 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7218 DeductionArg = NewDeductionArg;
7219 if (ArgPE) {
7220 // Recreate a pack expansion if we unwrapped one.
7221 Arg = new (Context) PackExpansionExpr(
7222 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7223 } else {
7224 Arg = DeductionArg;
7225 }
7226 };
7227
7228 // If the parameter type somehow involves auto, deduce the type now.
7229 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7230 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7231 if (IsDeduced) {
7232 // When checking a deduced template argument, deduce from its type even if
7233 // the type is dependent, in order to check the types of non-type template
7234 // arguments line up properly in partial ordering.
7235 TypeSourceInfo *TSI =
7236 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7238 InitializedEntity Entity =
7241 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7242 Expr *Inits[1] = {DeductionArg};
7243 ParamType =
7245 if (ParamType.isNull())
7246 return ExprError();
7247 } else {
7248 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7249 Param->getTemplateDepth() + 1);
7250 ParamType = QualType();
7252 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7253 /*DependentDeduction=*/true,
7254 // We do not check constraints right now because the
7255 // immediately-declared constraint of the auto type is
7256 // also an associated constraint, and will be checked
7257 // along with the other associated constraints after
7258 // checking the template argument list.
7259 /*IgnoreConstraints=*/true);
7261 ParamType = TSI->getType();
7262 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7264 return ExprError();
7265 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
7266 Diag(Arg->getExprLoc(),
7267 diag::err_non_type_template_parm_type_deduction_failure)
7268 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7269 << Arg->getSourceRange();
7271 return ExprError();
7272 }
7273 ParamType = SubstAutoTypeDependent(ParamType);
7274 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7275 }
7276 }
7277 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7278 // an error. The error message normally references the parameter
7279 // declaration, but here we'll pass the argument location because that's
7280 // where the parameter type is deduced.
7281 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7282 if (ParamType.isNull()) {
7284 return ExprError();
7285 }
7286 }
7287
7288 // We should have already dropped all cv-qualifiers by now.
7289 assert(!ParamType.hasQualifiers() &&
7290 "non-type template parameter type cannot be qualified");
7291
7292 // If either the parameter has a dependent type or the argument is
7293 // type-dependent, there's nothing we can check now.
7294 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7295 // Force the argument to the type of the parameter to maintain invariants.
7296 if (!IsDeduced) {
7298 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7299 ParamType->isLValueReferenceType() ? VK_LValue
7300 : ParamType->isRValueReferenceType() ? VK_XValue
7301 : VK_PRValue);
7302 if (E.isInvalid())
7303 return ExprError();
7304 setDeductionArg(E.get());
7305 }
7306 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7307 CanonicalConverted = TemplateArgument(
7308 Context.getCanonicalTemplateArgument(SugaredConverted));
7309 return Arg;
7310 }
7311
7312 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7313 if (CTAK == CTAK_Deduced && !StrictCheck &&
7314 (ParamType->isReferenceType()
7315 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7316 DeductionArg->getType())
7317 : !Context.hasSameUnqualifiedType(ParamType,
7318 DeductionArg->getType()))) {
7319 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7320 // we should actually be checking the type of the template argument in P,
7321 // not the type of the template argument deduced from A, against the
7322 // template parameter type.
7323 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7324 << Arg->getType() << ParamType.getUnqualifiedType();
7326 return ExprError();
7327 }
7328
7329 // If the argument is a pack expansion, we don't know how many times it would
7330 // expand. If we continue checking the argument, this will make the template
7331 // definition ill-formed if it would be ill-formed for any number of
7332 // expansions during instantiation time. When partial ordering or matching
7333 // template template parameters, this is exactly what we want. Otherwise, the
7334 // normal template rules apply: we accept the template if it would be valid
7335 // for any number of expansions (i.e. none).
7336 if (ArgPE && !StrictCheck) {
7337 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7338 CanonicalConverted = TemplateArgument(
7339 Context.getCanonicalTemplateArgument(SugaredConverted));
7340 return Arg;
7341 }
7342
7343 // Avoid making a copy when initializing a template parameter of class type
7344 // from a template parameter object of the same type. This is going beyond
7345 // the standard, but is required for soundness: in
7346 // template<A a> struct X { X *p; X<a> *q; };
7347 // ... we need p and q to have the same type.
7348 //
7349 // Similarly, don't inject a call to a copy constructor when initializing
7350 // from a template parameter of the same type.
7351 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7352 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7353 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7354 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7355 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7356
7357 SugaredConverted = TemplateArgument(TPO, ParamType);
7358 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7359 ParamType.getCanonicalType());
7360 return Arg;
7361 }
7363 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7364 CanonicalConverted =
7365 Context.getCanonicalTemplateArgument(SugaredConverted);
7366 return Arg;
7367 }
7368 }
7369
7370 // The initialization of the parameter from the argument is
7371 // a constant-evaluated context.
7374
7375 bool IsConvertedConstantExpression = true;
7376 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7378 StartLoc, /*DirectInit=*/false, DeductionArg);
7379 Expr *Inits[1] = {DeductionArg};
7380 InitializedEntity Entity =
7382 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7383 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7384 if (Result.isInvalid() || !Result.get())
7385 return ExprError();
7387 if (Result.isInvalid() || !Result.get())
7388 return ExprError();
7389 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7390 /*DiscardedValue=*/false,
7391 /*IsConstexpr=*/true,
7392 /*IsTemplateArgument=*/true)
7393 .get());
7394 IsConvertedConstantExpression = false;
7395 }
7396
7397 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7398 // C++17 [temp.arg.nontype]p1:
7399 // A template-argument for a non-type template parameter shall be
7400 // a converted constant expression of the type of the template-parameter.
7401 APValue Value;
7402 ExprResult ArgResult;
7403 if (IsConvertedConstantExpression) {
7405 DeductionArg, ParamType,
7406 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7407 assert(!ArgResult.isUnset());
7408 if (ArgResult.isInvalid()) {
7410 return ExprError();
7411 }
7412 } else {
7413 ArgResult = DeductionArg;
7414 }
7415
7416 // For a value-dependent argument, CheckConvertedConstantExpression is
7417 // permitted (and expected) to be unable to determine a value.
7418 if (ArgResult.get()->isValueDependent()) {
7419 setDeductionArg(ArgResult.get());
7420 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7421 CanonicalConverted =
7422 Context.getCanonicalTemplateArgument(SugaredConverted);
7423 return Arg;
7424 }
7425
7426 APValue PreNarrowingValue;
7428 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7429 false, PreNarrowingValue);
7430 if (ArgResult.isInvalid())
7431 return ExprError();
7432 setDeductionArg(ArgResult.get());
7433
7434 if (Value.isLValue()) {
7435 APValue::LValueBase Base = Value.getLValueBase();
7436 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7437 // For a non-type template-parameter of pointer or reference type,
7438 // the value of the constant expression shall not refer to
7439 assert(ParamType->isPointerOrReferenceType() ||
7440 ParamType->isNullPtrType());
7441 // -- a temporary object
7442 // -- a string literal
7443 // -- the result of a typeid expression, or
7444 // -- a predefined __func__ variable
7445 if (Base &&
7446 (!VD ||
7448 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7449 << Arg->getSourceRange();
7450 return ExprError();
7451 }
7452
7453 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7454 VD->getType()->isArrayType() &&
7455 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7456 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7457 if (ArgPE) {
7458 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7459 CanonicalConverted =
7460 Context.getCanonicalTemplateArgument(SugaredConverted);
7461 } else {
7462 SugaredConverted = TemplateArgument(VD, ParamType);
7463 CanonicalConverted =
7464 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7465 ParamType.getCanonicalType());
7466 }
7467 return Arg;
7468 }
7469
7470 // -- a subobject [until C++20]
7471 if (!getLangOpts().CPlusPlus20) {
7472 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7473 Value.isLValueOnePastTheEnd()) {
7474 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7475 << Value.getAsString(Context, ParamType);
7476 return ExprError();
7477 }
7478 assert((VD || !ParamType->isReferenceType()) &&
7479 "null reference should not be a constant expression");
7480 assert((!VD || !ParamType->isNullPtrType()) &&
7481 "non-null value of type nullptr_t?");
7482 }
7483 }
7484
7485 if (Value.isAddrLabelDiff())
7486 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7487
7488 if (ArgPE) {
7489 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7490 CanonicalConverted =
7491 Context.getCanonicalTemplateArgument(SugaredConverted);
7492 } else {
7493 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7494 CanonicalConverted =
7496 }
7497 return Arg;
7498 }
7499
7500 // These should have all been handled above using the C++17 rules.
7501 assert(!ArgPE && !StrictCheck);
7502
7503 // C++ [temp.arg.nontype]p5:
7504 // The following conversions are performed on each expression used
7505 // as a non-type template-argument. If a non-type
7506 // template-argument cannot be converted to the type of the
7507 // corresponding template-parameter then the program is
7508 // ill-formed.
7509 if (ParamType->isIntegralOrEnumerationType()) {
7510 // C++11:
7511 // -- for a non-type template-parameter of integral or
7512 // enumeration type, conversions permitted in a converted
7513 // constant expression are applied.
7514 //
7515 // C++98:
7516 // -- for a non-type template-parameter of integral or
7517 // enumeration type, integral promotions (4.5) and integral
7518 // conversions (4.7) are applied.
7519
7520 if (getLangOpts().CPlusPlus11) {
7521 // C++ [temp.arg.nontype]p1:
7522 // A template-argument for a non-type, non-template template-parameter
7523 // shall be one of:
7524 //
7525 // -- for a non-type template-parameter of integral or enumeration
7526 // type, a converted constant expression of the type of the
7527 // template-parameter; or
7528 llvm::APSInt Value;
7530 Arg, ParamType, Value, CCEKind::TemplateArg);
7531 if (ArgResult.isInvalid())
7532 return ExprError();
7533 Arg = ArgResult.get();
7534
7535 // We can't check arbitrary value-dependent arguments.
7536 if (Arg->isValueDependent()) {
7537 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7538 CanonicalConverted =
7539 Context.getCanonicalTemplateArgument(SugaredConverted);
7540 return Arg;
7541 }
7542
7543 // Widen the argument value to sizeof(parameter type). This is almost
7544 // always a no-op, except when the parameter type is bool. In
7545 // that case, this may extend the argument from 1 bit to 8 bits.
7546 QualType IntegerType = ParamType;
7547 if (const auto *ED = IntegerType->getAsEnumDecl())
7548 IntegerType = ED->getIntegerType();
7549 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7550 ? Context.getIntWidth(IntegerType)
7551 : Context.getTypeSize(IntegerType));
7552
7553 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7554 CanonicalConverted =
7555 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7556 return Arg;
7557 }
7558
7559 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7560 if (ArgResult.isInvalid())
7561 return ExprError();
7562 Arg = ArgResult.get();
7563
7564 QualType ArgType = Arg->getType();
7565
7566 // C++ [temp.arg.nontype]p1:
7567 // A template-argument for a non-type, non-template
7568 // template-parameter shall be one of:
7569 //
7570 // -- an integral constant-expression of integral or enumeration
7571 // type; or
7572 // -- the name of a non-type template-parameter; or
7573 llvm::APSInt Value;
7574 if (!ArgType->isIntegralOrEnumerationType()) {
7575 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7576 << ArgType << Arg->getSourceRange();
7578 return ExprError();
7579 }
7580 if (!Arg->isValueDependent()) {
7581 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7582 QualType T;
7583
7584 public:
7585 TmplArgICEDiagnoser(QualType T) : T(T) { }
7586
7587 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7588 SourceLocation Loc) override {
7589 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7590 }
7591 } Diagnoser(ArgType);
7592
7593 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7594 if (!Arg)
7595 return ExprError();
7596 }
7597
7598 // From here on out, all we care about is the unqualified form
7599 // of the argument type.
7600 ArgType = ArgType.getUnqualifiedType();
7601
7602 // Try to convert the argument to the parameter's type.
7603 if (Context.hasSameType(ParamType, ArgType)) {
7604 // Okay: no conversion necessary
7605 } else if (ParamType->isBooleanType()) {
7606 // This is an integral-to-boolean conversion.
7607 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7608 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7609 !ParamType->isEnumeralType()) {
7610 // This is an integral promotion or conversion.
7611 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7612 } else {
7613 // We can't perform this conversion.
7614 Diag(StartLoc, diag::err_template_arg_not_convertible)
7615 << Arg->getType() << ParamType << Arg->getSourceRange();
7617 return ExprError();
7618 }
7619
7620 // Add the value of this argument to the list of converted
7621 // arguments. We use the bitwidth and signedness of the template
7622 // parameter.
7623 if (Arg->isValueDependent()) {
7624 // The argument is value-dependent. Create a new
7625 // TemplateArgument with the converted expression.
7626 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7627 CanonicalConverted =
7628 Context.getCanonicalTemplateArgument(SugaredConverted);
7629 return Arg;
7630 }
7631
7632 QualType IntegerType = ParamType;
7633 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7634 IntegerType = ED->getIntegerType();
7635 }
7636
7637 if (ParamType->isBooleanType()) {
7638 // Value must be zero or one.
7639 Value = Value != 0;
7640 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7641 if (Value.getBitWidth() != AllowedBits)
7642 Value = Value.extOrTrunc(AllowedBits);
7643 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7644 } else {
7645 llvm::APSInt OldValue = Value;
7646
7647 // Coerce the template argument's value to the value it will have
7648 // based on the template parameter's type.
7649 unsigned AllowedBits = IntegerType->isBitIntType()
7650 ? Context.getIntWidth(IntegerType)
7651 : Context.getTypeSize(IntegerType);
7652 if (Value.getBitWidth() != AllowedBits)
7653 Value = Value.extOrTrunc(AllowedBits);
7654 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7655
7656 // Complain if an unsigned parameter received a negative value.
7657 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7658 (OldValue.isSigned() && OldValue.isNegative())) {
7659 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7660 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7661 << Arg->getSourceRange();
7663 }
7664
7665 // Complain if we overflowed the template parameter's type.
7666 unsigned RequiredBits;
7667 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7668 RequiredBits = OldValue.getActiveBits();
7669 else if (OldValue.isUnsigned())
7670 RequiredBits = OldValue.getActiveBits() + 1;
7671 else
7672 RequiredBits = OldValue.getSignificantBits();
7673 if (RequiredBits > AllowedBits) {
7674 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7675 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7676 << Arg->getSourceRange();
7678 }
7679 }
7680
7681 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7682 SugaredConverted = TemplateArgument(Context, Value, T);
7683 CanonicalConverted =
7684 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7685 return Arg;
7686 }
7687
7688 QualType ArgType = Arg->getType();
7689 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7690 bool IsSpecified = CTAK == CTAK_Specified;
7691
7692 // Handle pointer-to-function, reference-to-function, and
7693 // pointer-to-member-function all in (roughly) the same way.
7694 if (// -- For a non-type template-parameter of type pointer to
7695 // function, only the function-to-pointer conversion (4.3) is
7696 // applied. If the template-argument represents a set of
7697 // overloaded functions (or a pointer to such), the matching
7698 // function is selected from the set (13.4).
7699 (ParamType->isPointerType() &&
7700 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7701 // -- For a non-type template-parameter of type reference to
7702 // function, no conversions apply. If the template-argument
7703 // represents a set of overloaded functions, the matching
7704 // function is selected from the set (13.4).
7705 (ParamType->isReferenceType() &&
7706 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7707 // -- For a non-type template-parameter of type pointer to
7708 // member function, no conversions apply. If the
7709 // template-argument represents a set of overloaded member
7710 // functions, the matching member function is selected from
7711 // the set (13.4).
7712 (ParamType->isMemberPointerType() &&
7713 ParamType->castAs<MemberPointerType>()->getPointeeType()
7714 ->isFunctionType())) {
7715
7716 if (Arg->getType() == Context.OverloadTy) {
7717 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7718 true,
7719 FoundResult)) {
7720 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7721 return ExprError();
7722
7723 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7724 if (Res.isInvalid())
7725 return ExprError();
7726 Arg = Res.get();
7727 ArgType = Arg->getType();
7728 } else
7729 return ExprError();
7730 }
7731
7732 if (!ParamType->isMemberPointerType()) {
7734 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7735 CanonicalConverted))
7736 return ExprError();
7737 return Arg;
7738 }
7739
7741 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7742 return ExprError();
7743 return Arg;
7744 }
7745
7746 if (ParamType->isPointerType()) {
7747 // -- for a non-type template-parameter of type pointer to
7748 // object, qualification conversions (4.4) and the
7749 // array-to-pointer conversion (4.2) are applied.
7750 // C++0x also allows a value of std::nullptr_t.
7751 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7752 "Only object pointers allowed here");
7753
7755 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7756 CanonicalConverted))
7757 return ExprError();
7758 return Arg;
7759 }
7760
7761 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7762 // -- For a non-type template-parameter of type reference to
7763 // object, no conversions apply. The type referred to by the
7764 // reference may be more cv-qualified than the (otherwise
7765 // identical) type of the template-argument. The
7766 // template-parameter is bound directly to the
7767 // template-argument, which must be an lvalue.
7768 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7769 "Only object references allowed here");
7770
7771 if (Arg->getType() == Context.OverloadTy) {
7773 ParamRefType->getPointeeType(),
7774 true,
7775 FoundResult)) {
7776 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7777 return ExprError();
7778 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7779 if (Res.isInvalid())
7780 return ExprError();
7781 Arg = Res.get();
7782 ArgType = Arg->getType();
7783 } else
7784 return ExprError();
7785 }
7786
7788 *this, Param, ParamType, Arg, IsSpecified, SugaredConverted,
7789 CanonicalConverted))
7790 return ExprError();
7791 return Arg;
7792 }
7793
7794 // Deal with parameters of type std::nullptr_t.
7795 if (ParamType->isNullPtrType()) {
7796 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7797 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7798 CanonicalConverted =
7799 Context.getCanonicalTemplateArgument(SugaredConverted);
7800 return Arg;
7801 }
7802
7803 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7804 case NPV_NotNullPointer:
7805 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7806 << Arg->getType() << ParamType;
7808 return ExprError();
7809
7810 case NPV_Error:
7811 return ExprError();
7812
7813 case NPV_NullPointer:
7814 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7815 SugaredConverted = TemplateArgument(ParamType,
7816 /*isNullPtr=*/true);
7817 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7818 /*isNullPtr=*/true);
7819 return Arg;
7820 }
7821 }
7822
7823 // -- For a non-type template-parameter of type pointer to data
7824 // member, qualification conversions (4.4) are applied.
7825 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7826
7828 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7829 return ExprError();
7830 return Arg;
7831}
7832
7836
7839 const TemplateArgumentLoc &Arg) {
7840 // C++0x [temp.arg.template]p1:
7841 // A template-argument for a template template-parameter shall be
7842 // the name of a class template or an alias template, expressed as an
7843 // id-expression. When the template-argument names a class template, only
7844 // primary class templates are considered when matching the
7845 // template template argument with the corresponding parameter;
7846 // partial specializations are not considered even if their
7847 // parameter lists match that of the template template parameter.
7848 //
7849
7851 unsigned DiagFoundKind = 0;
7852
7853 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7854 switch (TTP->templateParameterKind()) {
7856 DiagFoundKind = 3;
7857 break;
7859 DiagFoundKind = 2;
7860 break;
7861 default:
7862 DiagFoundKind = 1;
7863 break;
7864 }
7865 Kind = TTP->templateParameterKind();
7866 } else if (isa<ConceptDecl>(Template)) {
7868 DiagFoundKind = 3;
7869 } else if (isa<FunctionTemplateDecl>(Template)) {
7871 DiagFoundKind = 0;
7872 } else if (isa<VarTemplateDecl>(Template)) {
7874 DiagFoundKind = 2;
7875 } else if (isa<ClassTemplateDecl>(Template) ||
7879 DiagFoundKind = 1;
7880 } else {
7881 assert(false && "Unexpected Decl");
7882 }
7883
7884 if (Kind == Param->templateParameterKind()) {
7885 return true;
7886 }
7887
7888 unsigned DiagKind = 0;
7889 switch (Param->templateParameterKind()) {
7891 DiagKind = 2;
7892 break;
7894 DiagKind = 1;
7895 break;
7896 default:
7897 DiagKind = 0;
7898 break;
7899 }
7900 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7901 << DiagKind;
7902 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7903 << DiagFoundKind << Template;
7904 return false;
7905}
7906
7907/// Check a template argument against its corresponding
7908/// template template parameter.
7909///
7910/// This routine implements the semantics of C++ [temp.arg.template].
7911/// It returns true if an error occurred, and false otherwise.
7913 TemplateParameterList *Params,
7915 bool PartialOrdering,
7916 bool *StrictPackMatch) {
7918 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7919 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7920 if (!Template) {
7921 // FIXME: Handle AssumedTemplateNames
7922 // Any dependent template name is fine.
7923 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7924 return false;
7925 }
7926
7927 if (Template->isInvalidDecl())
7928 return true;
7929
7931 return true;
7932 }
7933
7934 // C++1z [temp.arg.template]p3: (DR 150)
7935 // A template-argument matches a template template-parameter P when P
7936 // is at least as specialized as the template-argument A.
7938 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7939 PartialOrdering, StrictPackMatch))
7940 return true;
7941 // P2113
7942 // C++20[temp.func.order]p2
7943 // [...] If both deductions succeed, the partial ordering selects the
7944 // more constrained template (if one exists) as determined below.
7945 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7946 Params->getAssociatedConstraints(ParamsAC);
7947 // C++20[temp.arg.template]p3
7948 // [...] In this comparison, if P is unconstrained, the constraints on A
7949 // are not considered.
7950 if (ParamsAC.empty())
7951 return false;
7952
7953 Template->getAssociatedConstraints(TemplateAC);
7954
7955 bool IsParamAtLeastAsConstrained;
7956 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7957 IsParamAtLeastAsConstrained))
7958 return true;
7959 if (!IsParamAtLeastAsConstrained) {
7960 Diag(Arg.getLocation(),
7961 diag::err_template_template_parameter_not_at_least_as_constrained)
7962 << Template << Param << Arg.getSourceRange();
7963 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7964 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7966 TemplateAC);
7967 return true;
7968 }
7969 return false;
7970}
7971
7973 unsigned HereDiagID,
7974 unsigned ExternalDiagID) {
7975 if (Decl.getLocation().isValid())
7976 return S.Diag(Decl.getLocation(), HereDiagID);
7977
7978 SmallString<128> Str;
7979 llvm::raw_svector_ostream Out(Str);
7981 PP.TerseOutput = 1;
7982 Decl.print(Out, PP);
7983 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7984}
7985
7987 std::optional<SourceRange> ParamRange) {
7989 noteLocation(*this, Decl, diag::note_template_decl_here,
7990 diag::note_template_decl_external);
7991 if (ParamRange && ParamRange->isValid()) {
7992 assert(Decl.getLocation().isValid() &&
7993 "Parameter range has location when Decl does not");
7994 DB << *ParamRange;
7995 }
7996}
7997
7999 noteLocation(*this, Decl, diag::note_template_param_here,
8000 diag::note_template_param_external);
8001}
8002
8003/// Given a non-type template argument that refers to a
8004/// declaration and the type of its corresponding non-type template
8005/// parameter, produce an expression that properly refers to that
8006/// declaration.
8008 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
8009 // C++ [temp.param]p8:
8010 //
8011 // A non-type template-parameter of type "array of T" or
8012 // "function returning T" is adjusted to be of type "pointer to
8013 // T" or "pointer to function returning T", respectively.
8014 if (ParamType->isArrayType())
8015 ParamType = Context.getArrayDecayedType(ParamType);
8016 else if (ParamType->isFunctionType())
8017 ParamType = Context.getPointerType(ParamType);
8018
8019 // For a NULL non-type template argument, return nullptr casted to the
8020 // parameter's type.
8021 if (Arg.getKind() == TemplateArgument::NullPtr) {
8022 return ImpCastExprToType(
8023 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8024 ParamType,
8025 ParamType->getAs<MemberPointerType>()
8026 ? CK_NullToMemberPointer
8027 : CK_NullToPointer);
8028 }
8029 assert(Arg.getKind() == TemplateArgument::Declaration &&
8030 "Only declaration template arguments permitted here");
8031
8032 ValueDecl *VD = Arg.getAsDecl();
8033
8034 CXXScopeSpec SS;
8035 if (ParamType->isMemberPointerType()) {
8036 // If this is a pointer to member, we need to use a qualified name to
8037 // form a suitable pointer-to-member constant.
8038 assert(VD->getDeclContext()->isRecord() &&
8039 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8041 CanQualType ClassType =
8042 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
8043 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8044 SS.MakeTrivial(Context, Qualifier, Loc);
8045 }
8046
8048 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8049 if (RefExpr.isInvalid())
8050 return ExprError();
8051
8052 // For a pointer, the argument declaration is the pointee. Take its address.
8053 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8054 if (ParamType->isPointerType() && !ElemT.isNull() &&
8055 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8056 // Decay an array argument if we want a pointer to its first element.
8057 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8058 if (RefExpr.isInvalid())
8059 return ExprError();
8060 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8061 // For any other pointer, take the address (or form a pointer-to-member).
8062 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8063 if (RefExpr.isInvalid())
8064 return ExprError();
8065 } else if (ParamType->isRecordType()) {
8066 assert(isa<TemplateParamObjectDecl>(VD) &&
8067 "arg for class template param not a template parameter object");
8068 // No conversions apply in this case.
8069 return RefExpr;
8070 } else {
8071 assert(ParamType->isReferenceType() &&
8072 "unexpected type for decl template argument");
8073 // If the parameter has reference type, wrap it in paretheses so that this
8074 // expression will have the correct type under `decltype`.
8075 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8076 }
8077
8078 // At this point we should have the right value category.
8079 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8080 "value kind mismatch for non-type template argument");
8081
8082 // The type of the template parameter can differ from the type of the
8083 // argument in various ways; convert it now if necessary.
8084 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8085 QualType SrcExprType = RefExpr.get()->getType();
8086 if (!Context.hasSameType(SrcExprType, DestExprType)) {
8087 CastKind CK;
8088 if (Context.hasSimilarType(SrcExprType, DestExprType) ||
8089 IsFunctionConversion(SrcExprType, DestExprType)) {
8090 CK = CK_NoOp;
8091 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8092 CK = CK_BitCast;
8093 } else {
8094 // FIXME: Pointers to members can need conversion derived-to-base or
8095 // base-to-derived conversions. We currently don't retain enough
8096 // information to convert properly (we need to track a cast path or
8097 // subobject number in the template argument).
8098 llvm_unreachable(
8099 "unexpected conversion required for non-type template argument");
8100 }
8101 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8102 RefExpr.get()->getValueKind());
8103 }
8104
8105 return RefExpr;
8106}
8107
8108/// Construct a new expression that refers to the given
8109/// integral template argument with the given source-location
8110/// information.
8111///
8112/// This routine takes care of the mapping from an integral template
8113/// argument (which may have any integral type) to the appropriate
8114/// literal value.
8116 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8117 assert(OrigT->isIntegralOrEnumerationType());
8118
8119 // If this is an enum type that we're instantiating, we need to use an integer
8120 // type the same size as the enumerator. We don't want to build an
8121 // IntegerLiteral with enum type. The integer type of an enum type can be of
8122 // any integral type with C++11 enum classes, make sure we create the right
8123 // type of literal for it.
8124 QualType T = OrigT;
8125 if (const auto *ED = OrigT->getAsEnumDecl())
8126 T = ED->getIntegerType();
8127
8128 Expr *E;
8129 if (T->isAnyCharacterType()) {
8131 if (T->isWideCharType())
8133 else if (T->isChar8Type() && S.getLangOpts().Char8)
8135 else if (T->isChar16Type())
8137 else if (T->isChar32Type())
8139 else
8141
8142 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8143 } else if (T->isBooleanType()) {
8144 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8145 } else {
8146 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8147 }
8148
8149 if (OrigT->isEnumeralType()) {
8150 // FIXME: This is a hack. We need a better way to handle substituted
8151 // non-type template parameters.
8152 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8153 nullptr, S.CurFPFeatureOverrides(),
8154 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8155 Loc, Loc);
8156 }
8157
8158 return E;
8159}
8160
8161/// Construct a new reflect expression that refers to the given
8162/// entity with the given source-location of the reflection operator.
8164 SourceLocation CaretCaretLoc) {
8165 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8166 // and DeclRefExpr.
8168 S.Context, CaretCaretLoc,
8169 static_cast<TypeSourceInfo *>(
8170 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8171}
8172
8174 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8175 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8176 auto *ILE = new (S.Context)
8177 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8178 ILE->setType(T);
8179 return ILE;
8180 };
8181
8182 switch (Val.getKind()) {
8184 // This cannot occur in a template argument at all.
8185 case APValue::Array:
8186 case APValue::Struct:
8187 case APValue::Union:
8188 // These can only occur within a template parameter object, which is
8189 // represented as a TemplateArgument::Declaration.
8190 llvm_unreachable("unexpected template argument value");
8191
8192 case APValue::Int:
8194 Loc);
8195
8196 case APValue::Float:
8197 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8198 T, Loc);
8199
8202 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8203 Val.getFixedPoint().getScale());
8204
8205 case APValue::ComplexInt: {
8206 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8208 S, ElemT, Val.getComplexIntReal(), Loc),
8210 S, ElemT, Val.getComplexIntImag(), Loc)});
8211 }
8212
8213 case APValue::ComplexFloat: {
8214 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8215 return MakeInitList(
8217 ElemT, Loc),
8219 ElemT, Loc)});
8220 }
8221
8222 case APValue::Vector: {
8223 QualType ElemT = T->castAs<VectorType>()->getElementType();
8225 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8227 S, ElemT, Val.getVectorElt(I), Loc));
8228 return MakeInitList(Elts);
8229 }
8230
8231 case APValue::Matrix:
8232 llvm_unreachable("Matrix template argument expression not yet supported");
8233
8234 case APValue::None:
8236 llvm_unreachable("Unexpected APValue kind.");
8237 case APValue::LValue:
8239 // There isn't necessarily a valid equivalent source-level syntax for
8240 // these; in particular, a naive lowering might violate access control.
8241 // So for now we lower to a ConstantExpr holding the value, wrapped around
8242 // an OpaqueValueExpr.
8243 // FIXME: We should have a better representation for this.
8245 if (T->isReferenceType()) {
8246 T = T->getPointeeType();
8247 VK = VK_LValue;
8248 }
8249 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8250 return ConstantExpr::Create(S.Context, OVE, Val);
8251 }
8253 return BuildExpressionFromReflection(S, Val, Loc).get();
8254 }
8255 llvm_unreachable("Unhandled APValue::ValueKind enum");
8256}
8257
8260 SourceLocation Loc) {
8261 switch (Arg.getKind()) {
8267 llvm_unreachable("not a non-type template argument");
8268
8270 return Arg.getAsExpr();
8271
8275 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8276
8279 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8280
8283 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8284 }
8285 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8286}
8287
8288/// Match two template parameters within template parameter lists.
8290 Sema &S, NamedDecl *New,
8291 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8292 const NamedDecl *OldInstFrom, bool Complain,
8294 // Check the actual kind (type, non-type, template).
8295 if (Old->getKind() != New->getKind()) {
8296 if (Complain) {
8297 unsigned NextDiag = diag::err_template_param_different_kind;
8298 if (TemplateArgLoc.isValid()) {
8299 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8300 NextDiag = diag::note_template_param_different_kind;
8301 }
8302 S.Diag(New->getLocation(), NextDiag)
8303 << (Kind != Sema::TPL_TemplateMatch);
8304 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8305 << (Kind != Sema::TPL_TemplateMatch);
8306 }
8307
8308 return false;
8309 }
8310
8311 // Check that both are parameter packs or neither are parameter packs.
8312 // However, if we are matching a template template argument to a
8313 // template template parameter, the template template parameter can have
8314 // a parameter pack where the template template argument does not.
8315 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8316 if (Complain) {
8317 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8318 if (TemplateArgLoc.isValid()) {
8319 S.Diag(TemplateArgLoc,
8320 diag::err_template_arg_template_params_mismatch);
8321 NextDiag = diag::note_template_parameter_pack_non_pack;
8322 }
8323
8324 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8326 : 2;
8327 S.Diag(New->getLocation(), NextDiag)
8328 << ParamKind << New->isParameterPack();
8329 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8330 << ParamKind << Old->isParameterPack();
8331 }
8332
8333 return false;
8334 }
8335 // For non-type template parameters, check the type of the parameter.
8336 if (NonTypeTemplateParmDecl *OldNTTP =
8337 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8339
8340 // If we are matching a template template argument to a template
8341 // template parameter and one of the non-type template parameter types
8342 // is dependent, then we must wait until template instantiation time
8343 // to actually compare the arguments.
8345 (!OldNTTP->getType()->isDependentType() &&
8346 !NewNTTP->getType()->isDependentType())) {
8347 // C++20 [temp.over.link]p6:
8348 // Two [non-type] template-parameters are equivalent [if] they have
8349 // equivalent types ignoring the use of type-constraints for
8350 // placeholder types
8351 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8352 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8353 if (!S.Context.hasSameType(OldType, NewType)) {
8354 if (Complain) {
8355 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8356 if (TemplateArgLoc.isValid()) {
8357 S.Diag(TemplateArgLoc,
8358 diag::err_template_arg_template_params_mismatch);
8359 NextDiag = diag::note_template_nontype_parm_different_type;
8360 }
8361 S.Diag(NewNTTP->getLocation(), NextDiag)
8362 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8363 S.Diag(OldNTTP->getLocation(),
8364 diag::note_template_nontype_parm_prev_declaration)
8365 << OldNTTP->getType();
8366 }
8367 return false;
8368 }
8369 }
8370 }
8371 // For template template parameters, check the template parameter types.
8372 // The template parameter lists of template template
8373 // parameters must agree.
8374 else if (TemplateTemplateParmDecl *OldTTP =
8375 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8377 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8378 return false;
8380 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8381 OldTTP->getTemplateParameters(), Complain,
8384 : Kind),
8385 TemplateArgLoc))
8386 return false;
8387 }
8388
8392 const Expr *NewC = nullptr, *OldC = nullptr;
8393
8395 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8396 NewC = TC->getImmediatelyDeclaredConstraint();
8397 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8398 OldC = TC->getImmediatelyDeclaredConstraint();
8399 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8400 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8401 ->getPlaceholderTypeConstraint())
8402 NewC = E;
8403 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8404 ->getPlaceholderTypeConstraint())
8405 OldC = E;
8406 } else
8407 llvm_unreachable("unexpected template parameter type");
8408
8409 auto Diagnose = [&] {
8410 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8411 diag::err_template_different_type_constraint);
8412 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8413 diag::note_template_prev_declaration) << /*declaration*/0;
8414 };
8415
8416 if (!NewC != !OldC) {
8417 if (Complain)
8418 Diagnose();
8419 return false;
8420 }
8421
8422 if (NewC) {
8423 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8424 NewC)) {
8425 if (Complain)
8426 Diagnose();
8427 return false;
8428 }
8429 }
8430 }
8431
8432 return true;
8433}
8434
8435/// Diagnose a known arity mismatch when comparing template argument
8436/// lists.
8437static
8442 SourceLocation TemplateArgLoc) {
8443 unsigned NextDiag = diag::err_template_param_list_different_arity;
8444 if (TemplateArgLoc.isValid()) {
8445 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8446 NextDiag = diag::note_template_param_list_different_arity;
8447 }
8448 S.Diag(New->getTemplateLoc(), NextDiag)
8449 << (New->size() > Old->size())
8450 << (Kind != Sema::TPL_TemplateMatch)
8451 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8452 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8453 << (Kind != Sema::TPL_TemplateMatch)
8454 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8455}
8456
8459 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8460 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8461 if (Old->size() != New->size()) {
8462 if (Complain)
8464 TemplateArgLoc);
8465
8466 return false;
8467 }
8468
8469 // C++0x [temp.arg.template]p3:
8470 // A template-argument matches a template template-parameter (call it P)
8471 // when each of the template parameters in the template-parameter-list of
8472 // the template-argument's corresponding class template or alias template
8473 // (call it A) matches the corresponding template parameter in the
8474 // template-parameter-list of P. [...]
8475 TemplateParameterList::iterator NewParm = New->begin();
8476 TemplateParameterList::iterator NewParmEnd = New->end();
8477 for (TemplateParameterList::iterator OldParm = Old->begin(),
8478 OldParmEnd = Old->end();
8479 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8480 if (NewParm == NewParmEnd) {
8481 if (Complain)
8483 TemplateArgLoc);
8484 return false;
8485 }
8486 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8487 OldInstFrom, Complain, Kind,
8488 TemplateArgLoc))
8489 return false;
8490 }
8491
8492 // Make sure we exhausted all of the arguments.
8493 if (NewParm != NewParmEnd) {
8494 if (Complain)
8496 TemplateArgLoc);
8497
8498 return false;
8499 }
8500
8501 if (Kind != TPL_TemplateParamsEquivalent) {
8502 const Expr *NewRC = New->getRequiresClause();
8503 const Expr *OldRC = Old->getRequiresClause();
8504
8505 auto Diagnose = [&] {
8506 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8507 diag::err_template_different_requires_clause);
8508 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8509 diag::note_template_prev_declaration) << /*declaration*/0;
8510 };
8511
8512 if (!NewRC != !OldRC) {
8513 if (Complain)
8514 Diagnose();
8515 return false;
8516 }
8517
8518 if (NewRC) {
8519 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8520 NewRC)) {
8521 if (Complain)
8522 Diagnose();
8523 return false;
8524 }
8525 }
8526 }
8527
8528 return true;
8529}
8530
8531bool
8533 if (!S)
8534 return false;
8535
8536 // Find the nearest enclosing declaration scope.
8537 S = S->getDeclParent();
8538
8539 // C++ [temp.pre]p6: [P2096]
8540 // A template, explicit specialization, or partial specialization shall not
8541 // have C linkage.
8542 DeclContext *Ctx = S->getEntity();
8543 if (Ctx && Ctx->isExternCContext()) {
8544 SourceRange Range =
8545 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8546 ? TemplateParams->getParam(0)->getSourceRange()
8547 : TemplateParams->getSourceRange();
8548 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8549 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8550 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8551 return true;
8552 }
8553 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8554
8555 // C++ [temp]p2:
8556 // A template-declaration can appear only as a namespace scope or
8557 // class scope declaration.
8558 // C++ [temp.expl.spec]p3:
8559 // An explicit specialization may be declared in any scope in which the
8560 // corresponding primary template may be defined.
8561 // C++ [temp.class.spec]p6: [P2096]
8562 // A partial specialization may be declared in any scope in which the
8563 // corresponding primary template may be defined.
8564 if (Ctx) {
8565 if (Ctx->isFileContext())
8566 return false;
8567 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8568 // C++ [temp.mem]p2:
8569 // A local class shall not have member templates.
8570
8571 // Trace the outer context chain, bypassing nested records and OpenMP
8572 // captured regions, to determine if the class in defined inside a
8573 // function or method.
8574 const DeclContext *OutCtx = RD->getDeclContext();
8575 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(OutCtx))
8576 OutCtx = OutCtx->getParent();
8577
8578 if (OutCtx && OutCtx->isFunctionOrMethod())
8579 return Diag(TemplateParams->getTemplateLoc(),
8580 diag::err_template_inside_local_class)
8581 << TemplateParams->getSourceRange();
8582
8583 return false;
8584 }
8585 }
8586
8587 return Diag(TemplateParams->getTemplateLoc(),
8588 diag::err_template_outside_namespace_or_class_scope)
8589 << TemplateParams->getSourceRange();
8590}
8591
8592/// Determine what kind of template specialization the given declaration
8593/// is.
8595 if (!D)
8596 return TSK_Undeclared;
8597
8598 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8599 return Record->getTemplateSpecializationKind();
8600 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8601 return Function->getTemplateSpecializationKind();
8602 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8603 return Var->getTemplateSpecializationKind();
8604
8605 return TSK_Undeclared;
8606}
8607
8608/// Check whether a specialization is well-formed in the current
8609/// context.
8610///
8611/// This routine determines whether a template specialization can be declared
8612/// in the current context (C++ [temp.expl.spec]p2).
8613///
8614/// \param S the semantic analysis object for which this check is being
8615/// performed.
8616///
8617/// \param Specialized the entity being specialized or instantiated, which
8618/// may be a kind of template (class template, function template, etc.) or
8619/// a member of a class template (member function, static data member,
8620/// member class).
8621///
8622/// \param PrevDecl the previous declaration of this entity, if any.
8623///
8624/// \param Loc the location of the explicit specialization or instantiation of
8625/// this entity.
8626///
8627/// \param IsPartialSpecialization whether this is a partial specialization of
8628/// a class template.
8629///
8630/// \returns true if there was an error that we cannot recover from, false
8631/// otherwise.
8633 NamedDecl *Specialized,
8634 NamedDecl *PrevDecl,
8635 SourceLocation Loc,
8637 // Keep these "kind" numbers in sync with the %select statements in the
8638 // various diagnostics emitted by this routine.
8639 int EntityKind = 0;
8640 if (isa<ClassTemplateDecl>(Specialized))
8641 EntityKind = IsPartialSpecialization? 1 : 0;
8642 else if (isa<VarTemplateDecl>(Specialized))
8643 EntityKind = IsPartialSpecialization ? 3 : 2;
8644 else if (isa<FunctionTemplateDecl>(Specialized))
8645 EntityKind = 4;
8646 else if (isa<CXXMethodDecl>(Specialized))
8647 EntityKind = 5;
8648 else if (isa<VarDecl>(Specialized))
8649 EntityKind = 6;
8650 else if (isa<RecordDecl>(Specialized))
8651 EntityKind = 7;
8652 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8653 EntityKind = 8;
8654 else {
8655 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8656 << S.getLangOpts().CPlusPlus11;
8657 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8658 return true;
8659 }
8660
8661 // C++ [temp.expl.spec]p2:
8662 // An explicit specialization may be declared in any scope in which
8663 // the corresponding primary template may be defined.
8665 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8666 << Specialized;
8667 return true;
8668 }
8669
8670 // C++ [temp.class.spec]p6:
8671 // A class template partial specialization may be declared in any
8672 // scope in which the primary template may be defined.
8673 DeclContext *SpecializedContext =
8674 Specialized->getDeclContext()->getRedeclContext();
8676
8677 // Make sure that this redeclaration (or definition) occurs in the same
8678 // scope or an enclosing namespace.
8679 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8680 : DC->Equals(SpecializedContext))) {
8681 if (isa<TranslationUnitDecl>(SpecializedContext))
8682 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8683 << EntityKind << Specialized;
8684 else {
8685 auto *ND = cast<NamedDecl>(SpecializedContext);
8686 int Diag = diag::err_template_spec_redecl_out_of_scope;
8687 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8688 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8689 S.Diag(Loc, Diag) << EntityKind << Specialized
8690 << ND << isa<CXXRecordDecl>(ND);
8691 }
8692
8693 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8694
8695 // Don't allow specializing in the wrong class during error recovery.
8696 // Otherwise, things can go horribly wrong.
8697 if (DC->isRecord())
8698 return true;
8699 }
8700
8701 return false;
8702}
8703
8705 if (!E->isTypeDependent())
8706 return SourceLocation();
8707 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8708 Checker.TraverseStmt(E);
8709 if (Checker.MatchLoc.isInvalid())
8710 return E->getSourceRange();
8711 return Checker.MatchLoc;
8712}
8713
8714static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8715 if (!TL.getType()->isDependentType())
8716 return SourceLocation();
8717 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8718 Checker.TraverseTypeLoc(TL);
8719 if (Checker.MatchLoc.isInvalid())
8720 return TL.getSourceRange();
8721 return Checker.MatchLoc;
8722}
8723
8724/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8725/// that checks non-type template partial specialization arguments.
8727 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8728 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8729 bool HasError = false;
8730 for (unsigned I = 0; I != NumArgs; ++I) {
8731 if (Args[I].getKind() == TemplateArgument::Pack) {
8733 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8734 Args[I].pack_size(), IsDefaultArgument))
8735 return true;
8736
8737 continue;
8738 }
8739
8740 if (Args[I].getKind() != TemplateArgument::Expression)
8741 continue;
8742
8743 Expr *ArgExpr = Args[I].getAsExpr();
8744 if (ArgExpr->containsErrors()) {
8745 HasError = true;
8746 continue;
8747 }
8748
8749 // We can have a pack expansion of any of the bullets below.
8750 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8751 ArgExpr = Expansion->getPattern();
8752
8753 // Strip off any implicit casts we added as part of type checking.
8754 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8755 ArgExpr = ICE->getSubExpr();
8756
8757 // C++ [temp.class.spec]p8:
8758 // A non-type argument is non-specialized if it is the name of a
8759 // non-type parameter. All other non-type arguments are
8760 // specialized.
8761 //
8762 // Below, we check the two conditions that only apply to
8763 // specialized non-type arguments, so skip any non-specialized
8764 // arguments.
8765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8766 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8767 continue;
8768
8769 if (isa<DependentTemplateIdExpr>(ArgExpr))
8770 continue;
8771
8772 // C++ [temp.class.spec]p9:
8773 // Within the argument list of a class template partial
8774 // specialization, the following restrictions apply:
8775 // -- A partially specialized non-type argument expression
8776 // shall not involve a template parameter of the partial
8777 // specialization except when the argument expression is a
8778 // simple identifier.
8779 // -- The type of a template parameter corresponding to a
8780 // specialized non-type argument shall not be dependent on a
8781 // parameter of the specialization.
8782 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8783 // We implement a compromise between the original rules and DR1315:
8784 // -- A specialized non-type template argument shall not be
8785 // type-dependent and the corresponding template parameter
8786 // shall have a non-dependent type.
8787 SourceRange ParamUseRange =
8788 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8789 if (ParamUseRange.isValid()) {
8790 if (IsDefaultArgument) {
8791 S.Diag(TemplateNameLoc,
8792 diag::err_dependent_non_type_arg_in_partial_spec);
8793 S.Diag(ParamUseRange.getBegin(),
8794 diag::note_dependent_non_type_default_arg_in_partial_spec)
8795 << ParamUseRange;
8796 } else {
8797 S.Diag(ParamUseRange.getBegin(),
8798 diag::err_dependent_non_type_arg_in_partial_spec)
8799 << ParamUseRange;
8800 }
8801 return true;
8802 }
8803
8804 ParamUseRange = findTemplateParameter(
8805 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8806 if (ParamUseRange.isValid()) {
8807 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8808 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8809 << Param->getType();
8811 return true;
8812 }
8813 }
8814
8815 return HasError;
8816}
8817
8819 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8820 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8821 // We have to be conservative when checking a template in a dependent
8822 // context.
8823 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8824 return false;
8825
8826 TemplateParameterList *TemplateParams =
8827 PrimaryTemplate->getTemplateParameters();
8828 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8830 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8831 if (!Param)
8832 continue;
8833
8834 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8835 Param, &TemplateArgs[I],
8836 1, I >= NumExplicit))
8837 return true;
8838 }
8839
8840 return false;
8841}
8842
8844 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8845 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8847 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8848 assert(TUK != TagUseKind::Reference && "References are not specializations");
8849
8850 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8851 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8852 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8853
8854 // Find the class template we're specializing
8855 TemplateName Name = TemplateId.Template.get();
8857 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8858
8859 if (!ClassTemplate) {
8860 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8861 << (Name.getAsTemplateDecl() &&
8863 return true;
8864 }
8865
8866 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8867 auto Message = DSA->getMessage();
8868 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8869 << ClassTemplate << !Message.empty() << Message;
8870 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8871 }
8872
8873 if (S->isTemplateParamScope())
8874 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8875
8876 DeclContext *DC = ClassTemplate->getDeclContext();
8877
8878 bool isMemberSpecialization = false;
8879 bool isPartialSpecialization = false;
8880
8881 if (SS.isSet()) {
8882 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8883 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8884 TemplateNameLoc, &TemplateId,
8885 /*IsMemberSpecialization=*/false))
8886 return true;
8887 }
8888
8889 // Check the validity of the template headers that introduce this
8890 // template.
8891 // FIXME: We probably shouldn't complain about these headers for
8892 // friend declarations.
8893 bool Invalid = false;
8894 TemplateParameterList *TemplateParams =
8896 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8897 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8898 if (Invalid)
8899 return true;
8900
8901 // Check that we can declare a template specialization here.
8902 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8903 return true;
8904
8905 if (TemplateParams && DC->isDependentContext()) {
8906 ContextRAII SavedContext(*this, DC);
8908 return true;
8909 }
8910
8911 if (TemplateParams && TemplateParams->size() > 0) {
8912 isPartialSpecialization = true;
8913
8914 if (TUK == TagUseKind::Friend) {
8915 Diag(KWLoc, diag::err_partial_specialization_friend)
8916 << SourceRange(LAngleLoc, RAngleLoc);
8917 return true;
8918 }
8919
8920 // C++ [temp.class.spec]p10:
8921 // The template parameter list of a specialization shall not
8922 // contain default template argument values.
8923 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8924 Decl *Param = TemplateParams->getParam(I);
8925 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8926 if (TTP->hasDefaultArgument()) {
8927 Diag(TTP->getDefaultArgumentLoc(),
8928 diag::err_default_arg_in_partial_spec);
8929 TTP->removeDefaultArgument();
8930 }
8931 } else if (NonTypeTemplateParmDecl *NTTP
8932 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8933 if (NTTP->hasDefaultArgument()) {
8934 Diag(NTTP->getDefaultArgumentLoc(),
8935 diag::err_default_arg_in_partial_spec)
8936 << NTTP->getDefaultArgument().getSourceRange();
8937 NTTP->removeDefaultArgument();
8938 }
8939 } else {
8941 if (TTP->hasDefaultArgument()) {
8943 diag::err_default_arg_in_partial_spec)
8945 TTP->removeDefaultArgument();
8946 }
8947 }
8948 }
8949 } else if (TemplateParams) {
8950 if (TUK == TagUseKind::Friend)
8951 Diag(KWLoc, diag::err_template_spec_friend)
8953 SourceRange(TemplateParams->getTemplateLoc(),
8954 TemplateParams->getRAngleLoc()))
8955 << SourceRange(LAngleLoc, RAngleLoc);
8956 } else {
8957 assert(TUK == TagUseKind::Friend &&
8958 "should have a 'template<>' for this decl");
8959 }
8960
8961 // Check that the specialization uses the same tag kind as the
8962 // original template.
8964 assert(Kind != TagTypeKind::Enum &&
8965 "Invalid enum tag in class template spec!");
8966 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8967 TUK == TagUseKind::Definition, KWLoc,
8968 ClassTemplate->getIdentifier())) {
8969 Diag(KWLoc, diag::err_use_with_wrong_tag)
8970 << ClassTemplate
8972 ClassTemplate->getTemplatedDecl()->getKindName());
8973 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8974 diag::note_previous_use);
8975 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8976 }
8977
8978 // Translate the parser's template argument list in our AST format.
8979 TemplateArgumentListInfo TemplateArgs =
8980 makeTemplateArgumentListInfo(*this, TemplateId);
8981
8982 // Check for unexpanded parameter packs in any of the template arguments.
8983 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8984 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8985 isPartialSpecialization
8988 return true;
8989
8990 // Check that the template argument list is well-formed for this
8991 // template.
8993 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8994 /*DefaultArgs=*/{},
8995 /*PartialTemplateArgs=*/false, CTAI,
8996 /*UpdateArgsWithConversions=*/true))
8997 return true;
8998
8999 // Find the class template (partial) specialization declaration that
9000 // corresponds to these arguments.
9001 if (isPartialSpecialization) {
9003 TemplateArgs.size(),
9004 CTAI.CanonicalConverted))
9005 return true;
9006
9007 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9008 // also do it during instantiation.
9009 if (!Name.isDependent() &&
9010 !TemplateSpecializationType::anyDependentTemplateArguments(
9011 TemplateArgs, CTAI.CanonicalConverted)) {
9012 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9013 << ClassTemplate->getDeclName();
9014 isPartialSpecialization = false;
9015 Invalid = true;
9016 }
9017 }
9018
9019 llvm::FoldingSetInsertToken InsertToken;
9020 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9021
9022 if (isPartialSpecialization)
9023 PrevDecl = ClassTemplate->findPartialSpecialization(
9024 CTAI.CanonicalConverted, TemplateParams, InsertToken);
9025 else
9026 PrevDecl =
9027 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
9028
9030
9031 // Check whether we can declare a class template specialization in
9032 // the current scope.
9033 if (TUK != TagUseKind::Friend &&
9035 TemplateNameLoc,
9036 isPartialSpecialization))
9037 return true;
9038
9039 if (!isPartialSpecialization) {
9040 // Create a new class template specialization declaration node for
9041 // this explicit specialization or friend declaration.
9043 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9044 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
9045 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9047 if (TemplateParameterLists.size() > 0) {
9048 Specialization->setTemplateParameterListsInfo(Context,
9049 TemplateParameterLists);
9050 }
9051
9052 if (!PrevDecl)
9053 ClassTemplate->AddSpecialization(Specialization, InsertToken);
9054 } else {
9056 Context.getCanonicalTemplateSpecializationType(
9058 TemplateName(ClassTemplate->getCanonicalDecl()),
9059 CTAI.CanonicalConverted));
9060 if (Context.hasSameType(
9061 CanonType,
9062 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
9063 (!Context.getLangOpts().CPlusPlus20 ||
9064 !TemplateParams->hasAssociatedConstraints())) {
9065 // C++ [temp.class.spec]p9b3:
9066 //
9067 // -- The argument list of the specialization shall not be identical
9068 // to the implicit argument list of the primary template.
9069 //
9070 // This rule has since been removed, because it's redundant given DR1495,
9071 // but we keep it because it produces better diagnostics and recovery.
9072 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9073 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9074 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9075 return CheckClassTemplate(
9076 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
9077 TemplateNameLoc, Attr, TemplateParams, AS_none,
9078 /*ModulePrivateLoc=*/SourceLocation(),
9079 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
9080 TemplateParameterLists.data(), isMemberSpecialization);
9081 }
9082
9083 // Create a new class template partial specialization declaration node.
9085 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9088 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
9089 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
9090 Partial->setTemplateArgsAsWritten(TemplateArgs);
9091 SetNestedNameSpecifier(*this, Partial, SS);
9092 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9094 Context, TemplateParameterLists.drop_back(1));
9095 }
9096
9097 if (!PrevPartial)
9098 ClassTemplate->AddPartialSpecialization(Partial, InsertToken);
9099 Specialization = Partial;
9100
9101 // If we are providing an explicit specialization of a member class
9102 // template specialization, make a note of that.
9103 if (isMemberSpecialization)
9104 Partial->setMemberSpecialization();
9105
9107 }
9108
9109 // C++ [temp.expl.spec]p6:
9110 // If a template, a member template or the member of a class template is
9111 // explicitly specialized then that specialization shall be declared
9112 // before the first use of that specialization that would cause an implicit
9113 // instantiation to take place, in every translation unit in which such a
9114 // use occurs; no diagnostic is required.
9115 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9116 bool Okay = false;
9117 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9118 // Is there any previous explicit specialization declaration?
9120 Okay = true;
9121 break;
9122 }
9123 }
9124
9125 if (!Okay) {
9126 SourceRange Range(TemplateNameLoc, RAngleLoc);
9127 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9128 << Context.getCanonicalTagType(Specialization) << Range;
9129
9130 Diag(PrevDecl->getPointOfInstantiation(),
9131 diag::note_instantiation_required_here)
9132 << (PrevDecl->getTemplateSpecializationKind()
9134 return true;
9135 }
9136 }
9137
9138 // If this is not a friend, note that this is an explicit specialization.
9139 if (TUK != TagUseKind::Friend)
9140 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9141
9142 // Check that this isn't a redefinition of this specialization.
9143 if (TUK == TagUseKind::Definition) {
9144 RecordDecl *Def = Specialization->getDefinition();
9145 NamedDecl *Hidden = nullptr;
9146 bool HiddenDefVisible = false;
9147 if (Def && SkipBody &&
9148 isRedefinitionAllowedFor(Def, TemplateNameLoc, &Hidden,
9149 HiddenDefVisible)) {
9150 SkipBody->ShouldSkip = true;
9151 SkipBody->Previous = Def;
9152 if (!HiddenDefVisible && Hidden)
9154 } else if (Def) {
9155 SourceRange Range(TemplateNameLoc, RAngleLoc);
9156 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9157 Diag(Def->getLocation(), diag::note_previous_definition);
9158 Specialization->setInvalidDecl();
9159 return true;
9160 }
9161 }
9162
9165
9166 // Add alignment attributes if necessary; these attributes are checked when
9167 // the ASTContext lays out the structure.
9168 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9169 if (LangOpts.HLSL)
9170 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9173 }
9174
9175 if (ModulePrivateLoc.isValid())
9176 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9177 << (isPartialSpecialization? 1 : 0)
9178 << FixItHint::CreateRemoval(ModulePrivateLoc);
9179
9180 // C++ [temp.expl.spec]p9:
9181 // A template explicit specialization is in the scope of the
9182 // namespace in which the template was defined.
9183 //
9184 // We actually implement this paragraph where we set the semantic
9185 // context (in the creation of the ClassTemplateSpecializationDecl),
9186 // but we also maintain the lexical context where the actual
9187 // definition occurs.
9188 Specialization->setLexicalDeclContext(CurContext);
9189
9190 // We may be starting the definition of this specialization.
9191 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9192 Specialization->startDefinition();
9193
9194 if (TUK == TagUseKind::Friend) {
9195 CanQualType CanonType = Context.getCanonicalTagType(Specialization);
9196 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9197 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9199 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9200 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9201
9202 // Build the fully-sugared type for this class template
9203 // specialization as the user wrote in the specialization
9204 // itself. This means that we'll pretty-print the type retrieved
9205 // from the specialization's declaration the way that the user
9206 // actually wrote the specialization, rather than formatting the
9207 // name based on the "canonical" representation used to store the
9208 // template arguments in the specialization.
9210 TemplateNameLoc,
9211 WrittenTy,
9212 /*FIXME:*/KWLoc);
9213 Friend->setAccess(AS_public);
9214 CurContext->addDecl(Friend);
9215 } else {
9216 // Add the specialization into its lexical context, so that it can
9217 // be seen when iterating through the list of declarations in that
9218 // context. However, specializations are not found by name lookup.
9219 CurContext->addDecl(Specialization);
9220 }
9221
9222 if (SkipBody && SkipBody->ShouldSkip)
9223 return SkipBody->Previous;
9224
9225 Specialization->setInvalidDecl(Invalid);
9227 return Specialization;
9228}
9229
9231 MultiTemplateParamsArg TemplateParameterLists,
9232 Declarator &D) {
9233 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9234 ActOnDocumentableDecl(NewDecl);
9235 return NewDecl;
9236}
9237
9239 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9240 const IdentifierInfo *Name, SourceLocation NameLoc) {
9241 DeclContext *DC = CurContext;
9242
9243 if (!DC->getRedeclContext()->isFileContext()) {
9244 Diag(NameLoc,
9245 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9246 return nullptr;
9247 }
9248
9249 if (TemplateParameterLists.size() > 1) {
9250 Diag(NameLoc, diag::err_concept_extra_headers);
9251 return nullptr;
9252 }
9253
9254 TemplateParameterList *Params = TemplateParameterLists.front();
9255
9256 if (Params->size() == 0) {
9257 Diag(NameLoc, diag::err_concept_no_parameters);
9258 return nullptr;
9259 }
9260
9261 // Ensure that the parameter pack, if present, is the last parameter in the
9262 // template.
9263 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9264 ParamEnd = Params->end();
9265 ParamIt != ParamEnd; ++ParamIt) {
9266 Decl const *Param = *ParamIt;
9267 if (Param->isParameterPack()) {
9268 if (++ParamIt == ParamEnd)
9269 break;
9270 Diag(Param->getLocation(),
9271 diag::err_template_param_pack_must_be_last_template_parameter);
9272 return nullptr;
9273 }
9274 }
9275
9276 ConceptDecl *NewDecl =
9277 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9278
9279 if (NewDecl->hasAssociatedConstraints()) {
9280 // C++2a [temp.concept]p4:
9281 // A concept shall not have associated constraints.
9282 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9283 NewDecl->setInvalidDecl();
9284 }
9285
9286 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9287 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9289 LookupName(Previous, S);
9290 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9291 /*AllowInlineNamespace*/ false);
9292
9293 // We cannot properly handle redeclarations until we parse the constraint
9294 // expression, so only inject the name if we are sure we are not redeclaring a
9295 // symbol
9296 if (Previous.empty())
9297 PushOnScopeChains(NewDecl, S, true);
9298
9299 return NewDecl;
9300}
9301
9303 bool Found = false;
9304 LookupResult::Filter F = R.makeFilter();
9305 while (F.hasNext()) {
9306 NamedDecl *D = F.next();
9307 if (D == C) {
9308 F.erase();
9309 Found = true;
9310 break;
9311 }
9312 }
9313 F.done();
9314 return Found;
9315}
9316
9319 Expr *ConstraintExpr,
9320 const ParsedAttributesView &Attrs) {
9321 assert(!C->hasDefinition() && "Concept already defined");
9322 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9323 C->setInvalidDecl();
9324 return nullptr;
9325 }
9326 C->setDefinition(ConstraintExpr);
9327 ProcessDeclAttributeList(S, C, Attrs);
9328
9329 // Check for conflicting previous declaration.
9330 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9331 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9333 LookupName(Previous, S);
9334 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9335 /*AllowInlineNamespace*/ false);
9336 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9337 bool AddToScope = true;
9338 CheckConceptRedefinition(C, Previous, AddToScope);
9339
9341 if (!WasAlreadyAdded && AddToScope)
9342 PushOnScopeChains(C, S);
9343
9344 return C;
9345}
9346
9348 LookupResult &Previous, bool &AddToScope) {
9349 AddToScope = true;
9350
9351 if (Previous.empty())
9352 return;
9353
9354 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9355 if (!OldConcept) {
9356 auto *Old = Previous.getRepresentativeDecl();
9357 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9358 << NewDecl->getDeclName();
9359 notePreviousDefinition(Old, NewDecl->getLocation());
9360 AddToScope = false;
9361 return;
9362 }
9363 // Check if we can merge with a concept declaration.
9364 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9365 if (!IsSame) {
9366 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9367 << NewDecl->getDeclName();
9368 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9369 AddToScope = false;
9370 return;
9371 }
9372 if (hasReachableDefinition(OldConcept) &&
9373 IsRedefinitionInModule(NewDecl, OldConcept)) {
9374 Diag(NewDecl->getLocation(), diag::err_redefinition)
9375 << NewDecl->getDeclName();
9376 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9377 AddToScope = false;
9378 return;
9379 }
9380 if (!Previous.isSingleResult()) {
9381 // FIXME: we should produce an error in case of ambig and failed lookups.
9382 // Other decls (e.g. namespaces) also have this shortcoming.
9383 return;
9384 }
9385 // We unwrap canonical decl late to check for module visibility.
9386 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9387}
9388
9390 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9391 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9392 Diag(Loc, diag::err_recursive_concept) << CE;
9393 Diag(CE->getLocation(), diag::note_declared_at);
9394 CE->setInvalidDecl();
9395 return true;
9396 }
9397 // Concept template parameters don't have a definition and can't
9398 // be defined recursively.
9399 return false;
9400}
9401
9402/// \brief Strips various properties off an implicit instantiation
9403/// that has just been explicitly specialized.
9404static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9405 if (MinGW || (isa<FunctionDecl>(D) &&
9406 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9407 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9408
9409 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9410 FD->setInlineSpecified(false);
9411}
9412
9413/// Create an ExplicitInstantiationDecl to record source-location info for an
9414/// explicit template instantiation statement, and add it to \p CurContext.
9415///
9416/// For class templates / nested classes, the caller should build a
9417/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9418/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9419///
9420/// For function / variable templates, the caller should pass TypeAsWritten for
9421/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9423 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9424 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9425 NestedNameSpecifierLoc QualifierLoc,
9426 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9427 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9429 Context, CurContext, Spec, ExternLoc, TemplateLoc, QualifierLoc,
9430 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9431 Context.addExplicitInstantiationDecl(Spec, EID);
9432 CurContext->addDecl(EID);
9433}
9434
9435/// Compute the diagnostic location for an explicit instantiation
9436// declaration or definition.
9437static SourceLocation
9439 SourceLocation PointOfInstantiation) {
9440 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(D))
9441 if (EID->getTemplateSpecializationKind() ==
9443 return EID->getTemplateLoc();
9444
9445 // Explicit instantiations following a specialization have no effect and
9446 // hence no PointOfInstantiation. In that case, walk decl backwards
9447 // until a valid name loc is found.
9448 SourceLocation PrevDiagLoc = PointOfInstantiation;
9449 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9450 Prev = Prev->getPreviousDecl()) {
9451 PrevDiagLoc = Prev->getLocation();
9452 }
9453 assert(PrevDiagLoc.isValid() &&
9454 "Explicit instantiation without point of instantiation?");
9455 return PrevDiagLoc;
9456}
9457
9458bool
9461 NamedDecl *PrevDecl,
9463 SourceLocation PrevPointOfInstantiation,
9464 bool &HasNoEffect) {
9465 HasNoEffect = false;
9466
9467 switch (NewTSK) {
9468 case TSK_Undeclared:
9470 assert(
9471 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9472 "previous declaration must be implicit!");
9473 return false;
9474
9476 switch (PrevTSK) {
9477 case TSK_Undeclared:
9479 // Okay, we're just specializing something that is either already
9480 // explicitly specialized or has merely been mentioned without any
9481 // instantiation.
9482 return false;
9483
9485 if (PrevPointOfInstantiation.isInvalid()) {
9486 // The declaration itself has not actually been instantiated, so it is
9487 // still okay to specialize it.
9489 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9490 return false;
9491 }
9492 // Fall through
9493 [[fallthrough]];
9494
9497 assert((PrevTSK == TSK_ImplicitInstantiation ||
9498 PrevPointOfInstantiation.isValid()) &&
9499 "Explicit instantiation without point of instantiation?");
9500
9501 // C++ [temp.expl.spec]p6:
9502 // If a template, a member template or the member of a class template
9503 // is explicitly specialized then that specialization shall be declared
9504 // before the first use of that specialization that would cause an
9505 // implicit instantiation to take place, in every translation unit in
9506 // which such a use occurs; no diagnostic is required.
9507 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9508 // Is there any previous explicit specialization declaration?
9510 return false;
9511 }
9512
9513 Diag(NewLoc, diag::err_specialization_after_instantiation)
9514 << PrevDecl;
9515 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9516 << (PrevTSK != TSK_ImplicitInstantiation);
9517
9518 return true;
9519 }
9520 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9521
9523 switch (PrevTSK) {
9525 // This explicit instantiation declaration is redundant (that's okay).
9526 HasNoEffect = true;
9527 return false;
9528
9529 case TSK_Undeclared:
9531 // We're explicitly instantiating something that may have already been
9532 // implicitly instantiated; that's fine.
9533 return false;
9534
9536 // C++0x [temp.explicit]p4:
9537 // For a given set of template parameters, if an explicit instantiation
9538 // of a template appears after a declaration of an explicit
9539 // specialization for that template, the explicit instantiation has no
9540 // effect.
9541 HasNoEffect = true;
9542 return false;
9543
9545 // C++0x [temp.explicit]p10:
9546 // If an entity is the subject of both an explicit instantiation
9547 // declaration and an explicit instantiation definition in the same
9548 // translation unit, the definition shall follow the declaration.
9549 Diag(NewLoc,
9550 diag::err_explicit_instantiation_declaration_after_definition);
9551
9552 // Explicit instantiations following a specialization have no effect and
9553 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9554 // until a valid name loc is found.
9555 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9556 diag::note_explicit_instantiation_definition_here);
9557 HasNoEffect = true;
9558 return false;
9559 }
9560 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9561
9563 switch (PrevTSK) {
9564 case TSK_Undeclared:
9566 // We're explicitly instantiating something that may have already been
9567 // implicitly instantiated; that's fine.
9568 return false;
9569
9571 // C++ DR 259, C++0x [temp.explicit]p4:
9572 // For a given set of template parameters, if an explicit
9573 // instantiation of a template appears after a declaration of
9574 // an explicit specialization for that template, the explicit
9575 // instantiation has no effect.
9576 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9577 << PrevDecl;
9578 Diag(PrevDecl->getLocation(),
9579 diag::note_previous_template_specialization);
9580 HasNoEffect = true;
9581 return false;
9582
9584 // We're explicitly instantiating a definition for something for which we
9585 // were previously asked to suppress instantiations. That's fine.
9586
9587 // C++0x [temp.explicit]p4:
9588 // For a given set of template parameters, if an explicit instantiation
9589 // of a template appears after a declaration of an explicit
9590 // specialization for that template, the explicit instantiation has no
9591 // effect.
9592 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9593 // Is there any previous explicit specialization declaration?
9595 HasNoEffect = true;
9596 break;
9597 }
9598 }
9599
9600 return false;
9601
9603 // C++0x [temp.spec]p5:
9604 // For a given template and a given set of template-arguments,
9605 // - an explicit instantiation definition shall appear at most once
9606 // in a program,
9607
9608 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9609 Diag(NewLoc, (getLangOpts().MSVCCompat)
9610 ? diag::ext_explicit_instantiation_duplicate
9611 : diag::err_explicit_instantiation_duplicate)
9612 << PrevDecl;
9613 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9614 diag::note_previous_explicit_instantiation);
9615 HasNoEffect = true;
9616 return false;
9617 }
9618 }
9619
9620 llvm_unreachable("Missing specialization/instantiation case?");
9621}
9622
9624 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9626 // Remove anything from Previous that isn't a function template in
9627 // the correct context.
9628 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9629 LookupResult::Filter F = Previous.makeFilter();
9630 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9631 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9632 while (F.hasNext()) {
9633 NamedDecl *D = F.next()->getUnderlyingDecl();
9634 if (!isa<FunctionTemplateDecl>(D)) {
9635 F.erase();
9636 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9637 continue;
9638 }
9639
9640 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9642 F.erase();
9643 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9644 continue;
9645 }
9646 }
9647 F.done();
9648
9649 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9650 if (Previous.empty()) {
9651 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9652 if (IsFriend && FriendQualifier.isDependent() &&
9653 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9654 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9656 Context, Previous.asUnresolvedSet(), ExplicitTemplateArgs);
9657 return false;
9658 }
9659
9660 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9661 << IsFriend;
9662 for (auto &P : DiscardedCandidates)
9663 Diag(P.second->getLocation(),
9664 diag::note_dependent_function_template_spec_discard_reason)
9665 << P.first << IsFriend;
9666 return true;
9667 }
9668
9670 ExplicitTemplateArgs);
9671 return false;
9672}
9673
9675 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9676 LookupResult &Previous, bool QualifiedFriend) {
9677 // The set of function template specializations that could match this
9678 // explicit function template specialization.
9679 UnresolvedSet<8> Candidates;
9680 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9681 /*ForTakingAddress=*/false);
9682
9683 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9684 ConvertedTemplateArgs;
9685
9686 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9687 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9688 I != E; ++I) {
9689 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9690 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9691 // Only consider templates found within the same semantic lookup scope as
9692 // FD.
9693 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9695 continue;
9696
9697 QualType FT = FD->getType();
9698 // C++11 [dcl.constexpr]p8:
9699 // A constexpr specifier for a non-static member function that is not
9700 // a constructor declares that member function to be const.
9701 //
9702 // When matching a constexpr member function template specialization
9703 // against the primary template, we don't yet know whether the
9704 // specialization has an implicit 'const' (because we don't know whether
9705 // it will be a static member function until we know which template it
9706 // specializes). This rule was removed in C++14.
9707 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9708 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9710 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9711 if (OldMD && OldMD->isConst()) {
9712 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9714 EPI.TypeQuals.addConst();
9715 FT = Context.getFunctionType(FPT->getReturnType(),
9716 FPT->getParamTypes(), EPI);
9717 }
9718 }
9719
9721 if (ExplicitTemplateArgs)
9722 Args = *ExplicitTemplateArgs;
9723
9724 // C++ [temp.expl.spec]p11:
9725 // A trailing template-argument can be left unspecified in the
9726 // template-id naming an explicit function template specialization
9727 // provided it can be deduced from the function argument type.
9728 // Perform template argument deduction to determine whether we may be
9729 // specializing this template.
9730 // FIXME: It is somewhat wasteful to build
9731 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9732 FunctionDecl *Specialization = nullptr;
9734 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9735 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9737 // Template argument deduction failed; record why it failed, so
9738 // that we can provide nifty diagnostics.
9739 FailedCandidates.addCandidate().set(
9740 I.getPair(), FunTmpl->getTemplatedDecl(),
9741 MakeDeductionFailureInfo(Context, TDK, Info));
9742 (void)TDK;
9743 continue;
9744 }
9745
9746 // Target attributes are part of the cuda function signature, so
9747 // the deduced template's cuda target must match that of the
9748 // specialization. Given that C++ template deduction does not
9749 // take target attributes into account, we reject candidates
9750 // here that have a different target.
9751 if (LangOpts.CUDA &&
9752 CUDA().IdentifyTarget(Specialization,
9753 /* IgnoreImplicitHDAttr = */ true) !=
9754 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9755 FailedCandidates.addCandidate().set(
9756 I.getPair(), FunTmpl->getTemplatedDecl(),
9759 continue;
9760 }
9761
9762 // Record this candidate.
9763 if (ExplicitTemplateArgs)
9764 ConvertedTemplateArgs[Specialization] = std::move(Args);
9765 Candidates.addDecl(Specialization, I.getAccess());
9766 }
9767 }
9768
9769 // For a qualified friend declaration (with no explicit marker to indicate
9770 // that a template specialization was intended), note all (template and
9771 // non-template) candidates.
9772 if (QualifiedFriend && Candidates.empty()) {
9773 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9774 << FD->getDeclName() << FDLookupContext;
9775 // FIXME: We should form a single candidate list and diagnose all
9776 // candidates at once, to get proper sorting and limiting.
9777 for (auto *OldND : Previous) {
9778 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9779 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9780 }
9781 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9782 return true;
9783 }
9784
9785 // Find the most specialized function template.
9787 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9788 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9789 PDiag(diag::err_function_template_spec_ambiguous)
9790 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9791 PDiag(diag::note_function_template_spec_matched));
9792
9793 if (Result == Candidates.end())
9794 return true;
9795
9796 // Ignore access information; it doesn't figure into redeclaration checking.
9798
9799 if (const auto *PT = Specialization->getPrimaryTemplate();
9800 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9801 auto Message = DSA->getMessage();
9802 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9803 << PT << !Message.empty() << Message;
9804 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9805 }
9806
9807 // C++23 [except.spec]p13:
9808 // An exception specification is considered to be needed when:
9809 // - [...]
9810 // - the exception specification is compared to that of another declaration
9811 // (e.g., an explicit specialization or an overriding virtual function);
9812 // - [...]
9813 //
9814 // The exception specification of a defaulted function is evaluated as
9815 // described above only when needed; similarly, the noexcept-specifier of a
9816 // specialization of a function template or member function of a class
9817 // template is instantiated only when needed.
9818 //
9819 // The standard doesn't specify what the "comparison with another declaration"
9820 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9821 // not state which properties of an explicit specialization must match the
9822 // primary template.
9823 //
9824 // We assume that an explicit specialization must correspond with (per
9825 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9826 // the declaration produced by substitution into the function template.
9827 //
9828 // Since the determination whether two function declarations correspond does
9829 // not consider exception specification, we only need to instantiate it once
9830 // we determine the primary template when comparing types per
9831 // [basic.link]p11.1.
9832 auto *SpecializationFPT =
9833 Specialization->getType()->castAs<FunctionProtoType>();
9834 // If the function has a dependent exception specification, resolve it after
9835 // we have selected the primary template so we can check whether it matches.
9836 if (getLangOpts().CPlusPlus17 &&
9837 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9838 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9839 return true;
9840
9842 = Specialization->getTemplateSpecializationInfo();
9843 assert(SpecInfo && "Function template specialization info missing?");
9844
9845 // Note: do not overwrite location info if previous template
9846 // specialization kind was explicit.
9848 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9849 Specialization->setLocation(FD->getLocation());
9850 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9851 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9852 // function can differ from the template declaration with respect to
9853 // the constexpr specifier.
9854 // FIXME: We need an update record for this AST mutation.
9855 // FIXME: What if there are multiple such prior declarations (for instance,
9856 // from different modules)?
9857 Specialization->setConstexprKind(FD->getConstexprKind());
9858 }
9859
9860 // FIXME: Check if the prior specialization has a point of instantiation.
9861 // If so, we have run afoul of .
9862
9863 // If this is a friend declaration, then we're not really declaring
9864 // an explicit specialization.
9865 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9866
9867 // Check the scope of this explicit specialization.
9868 if (!isFriend &&
9870 Specialization->getPrimaryTemplate(),
9872 false))
9873 return true;
9874
9875 // C++ [temp.expl.spec]p6:
9876 // If a template, a member template or the member of a class template is
9877 // explicitly specialized then that specialization shall be declared
9878 // before the first use of that specialization that would cause an implicit
9879 // instantiation to take place, in every translation unit in which such a
9880 // use occurs; no diagnostic is required.
9881 bool HasNoEffect = false;
9882 if (!isFriend &&
9887 SpecInfo->getPointOfInstantiation(),
9888 HasNoEffect))
9889 return true;
9890
9891 // Mark the prior declaration as an explicit specialization, so that later
9892 // clients know that this is an explicit specialization.
9893 // A dependent friend specialization which has a definition should be treated
9894 // as explicit specialization, despite being invalid.
9895 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9896 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9897 // Since explicit specializations do not inherit '=delete' from their
9898 // primary function template - check if the 'specialization' that was
9899 // implicitly generated (during template argument deduction for partial
9900 // ordering) from the most specialized of all the function templates that
9901 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9902 // first check that it was implicitly generated during template argument
9903 // deduction by making sure it wasn't referenced, and then reset the deleted
9904 // flag to not-deleted, so that we can inherit that information from 'FD'.
9905 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9906 !Specialization->getCanonicalDecl()->isReferenced()) {
9907 // FIXME: This assert will not hold in the presence of modules.
9908 assert(
9909 Specialization->getCanonicalDecl() == Specialization &&
9910 "This must be the only existing declaration of this specialization");
9911 // FIXME: We need an update record for this AST mutation.
9912 Specialization->setDeletedAsWritten(false);
9913 }
9914 // FIXME: We need an update record for this AST mutation.
9917 }
9918
9919 // Turn the given function declaration into a function template
9920 // specialization, with the template arguments from the previous
9921 // specialization.
9922 // Take copies of (semantic and syntactic) template argument lists.
9924 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9925 FD->setFunctionTemplateSpecialization(
9926 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertToken=*/{},
9928 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9929
9930 // A function template specialization inherits the target attributes
9931 // of its template. (We require the attributes explicitly in the
9932 // code to match, but a template may have implicit attributes by
9933 // virtue e.g. of being constexpr, and it passes these implicit
9934 // attributes on to its specializations.)
9935 if (LangOpts.CUDA)
9936 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9937
9938 // The "previous declaration" for this function template specialization is
9939 // the prior function template specialization.
9940 Previous.clear();
9941 Previous.addDecl(Specialization);
9942 return false;
9943}
9944
9945bool
9947 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9948 "Only for non-template members");
9949
9950 // Try to find the member we are instantiating.
9951 NamedDecl *FoundInstantiation = nullptr;
9952 NamedDecl *Instantiation = nullptr;
9953 NamedDecl *InstantiatedFrom = nullptr;
9954 MemberSpecializationInfo *MSInfo = nullptr;
9955
9956 if (Previous.empty()) {
9957 // Nowhere to look anyway.
9958 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9959 UnresolvedSet<8> Candidates;
9960 for (NamedDecl *Candidate : Previous) {
9961 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9962 // Ignore any candidates that aren't member functions.
9963 if (!Method)
9964 continue;
9965
9966 QualType Adjusted = Function->getType();
9967 if (!hasExplicitCallingConv(Adjusted))
9968 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9969 // Ignore any candidates with the wrong type.
9970 // This doesn't handle deduced return types, but both function
9971 // declarations should be undeduced at this point.
9972 // FIXME: The exception specification should probably be ignored when
9973 // comparing the types.
9974 if (!Context.hasSameType(Adjusted, Method->getType()))
9975 continue;
9976
9977 // Ignore any candidates with unsatisfied constraints.
9978 if (ConstraintSatisfaction Satisfaction;
9979 Method->getTrailingRequiresClause() &&
9980 (CheckFunctionConstraints(Method, Satisfaction,
9981 /*UsageLoc=*/Member->getLocation(),
9982 /*ForOverloadResolution=*/true) ||
9983 !Satisfaction.IsSatisfied))
9984 continue;
9985
9986 Candidates.addDecl(Candidate);
9987 }
9988
9989 // If we have no viable candidates left after filtering, we are done.
9990 if (Candidates.empty())
9991 return false;
9992
9993 // Find the function that is more constrained than every other function it
9994 // has been compared to.
9995 UnresolvedSetIterator Best = Candidates.begin();
9996 CXXMethodDecl *BestMethod = nullptr;
9997 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9998 I != E; ++I) {
9999 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
10000 if (I == Best ||
10001 getMoreConstrainedFunction(Method, BestMethod) == Method) {
10002 Best = I;
10003 BestMethod = Method;
10004 }
10005 }
10006
10007 FoundInstantiation = *Best;
10008 Instantiation = BestMethod;
10009 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
10010 MSInfo = BestMethod->getMemberSpecializationInfo();
10011
10012 // Make sure the best candidate is more constrained than all of the others.
10013 bool Ambiguous = false;
10014 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
10015 I != E; ++I) {
10016 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
10017 if (I != Best &&
10018 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
10019 Ambiguous = true;
10020 break;
10021 }
10022 }
10023
10024 if (Ambiguous) {
10025 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
10026 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10027 for (NamedDecl *Candidate : Candidates) {
10028 Candidate = Candidate->getUnderlyingDecl();
10029 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
10030 << Candidate;
10031 }
10032 return true;
10033 }
10034 } else if (isa<VarDecl>(Member)) {
10035 VarDecl *PrevVar;
10036 if (Previous.isSingleResult() &&
10037 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10038 if (PrevVar->isStaticDataMember()) {
10039 FoundInstantiation = Previous.getRepresentativeDecl();
10040 Instantiation = PrevVar;
10041 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10042 MSInfo = PrevVar->getMemberSpecializationInfo();
10043 }
10044 } else if (isa<RecordDecl>(Member)) {
10045 CXXRecordDecl *PrevRecord;
10046 if (Previous.isSingleResult() &&
10047 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10048 FoundInstantiation = Previous.getRepresentativeDecl();
10049 Instantiation = PrevRecord;
10050 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10051 MSInfo = PrevRecord->getMemberSpecializationInfo();
10052 }
10053 } else if (isa<EnumDecl>(Member)) {
10054 EnumDecl *PrevEnum;
10055 if (Previous.isSingleResult() &&
10056 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10057 FoundInstantiation = Previous.getRepresentativeDecl();
10058 Instantiation = PrevEnum;
10059 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10060 MSInfo = PrevEnum->getMemberSpecializationInfo();
10061 }
10062 }
10063
10064 if (!Instantiation) {
10065 // There is no previous declaration that matches. Since member
10066 // specializations are always out-of-line, the caller will complain about
10067 // this mismatch later.
10068 return false;
10069 }
10070
10071 // A member specialization in a friend declaration isn't really declaring
10072 // an explicit specialization, just identifying a specific (possibly implicit)
10073 // specialization. Don't change the template specialization kind.
10074 //
10075 // FIXME: Is this really valid? Other compilers reject.
10076 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10077 // Preserve instantiation information.
10078 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10079 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10080 cast<CXXMethodDecl>(InstantiatedFrom),
10082 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10083 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10084 cast<CXXRecordDecl>(InstantiatedFrom),
10086 }
10087
10088 Previous.clear();
10089 Previous.addDecl(FoundInstantiation);
10090 return false;
10091 }
10092
10093 // Make sure that this is a specialization of a member.
10094 if (!InstantiatedFrom) {
10095 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10096 << Member;
10097 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10098 return true;
10099 }
10100
10101 // C++ [temp.expl.spec]p6:
10102 // If a template, a member template or the member of a class template is
10103 // explicitly specialized then that specialization shall be declared
10104 // before the first use of that specialization that would cause an implicit
10105 // instantiation to take place, in every translation unit in which such a
10106 // use occurs; no diagnostic is required.
10107 assert(MSInfo && "Member specialization info missing?");
10108
10109 bool HasNoEffect = false;
10112 Instantiation,
10114 MSInfo->getPointOfInstantiation(),
10115 HasNoEffect))
10116 return true;
10117
10118 // Check the scope of this explicit specialization.
10120 InstantiatedFrom,
10121 Instantiation, Member->getLocation(),
10122 false))
10123 return true;
10124
10125 // Note that this member specialization is an "instantiation of" the
10126 // corresponding member of the original template.
10127 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10128 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10129 if (InstantiationFunction->getTemplateSpecializationKind() ==
10131 // Explicit specializations of member functions of class templates do not
10132 // inherit '=delete' from the member function they are specializing.
10133 if (InstantiationFunction->isDeleted()) {
10134 // FIXME: This assert will not hold in the presence of modules.
10135 assert(InstantiationFunction->getCanonicalDecl() ==
10136 InstantiationFunction);
10137 // FIXME: We need an update record for this AST mutation.
10138 InstantiationFunction->setDeletedAsWritten(false);
10139 }
10140 }
10141
10142 MemberFunction->setInstantiationOfMemberFunction(
10144 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10145 MemberVar->setInstantiationOfStaticDataMember(
10146 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10147 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10148 MemberClass->setInstantiationOfMemberClass(
10150 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10151 MemberEnum->setInstantiationOfMemberEnum(
10152 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10153 } else {
10154 llvm_unreachable("unknown member specialization kind");
10155 }
10156
10157 // Save the caller the trouble of having to figure out which declaration
10158 // this specialization matches.
10159 Previous.clear();
10160 Previous.addDecl(FoundInstantiation);
10161 return false;
10162}
10163
10164/// Complete the explicit specialization of a member of a class template by
10165/// updating the instantiated member to be marked as an explicit specialization.
10166///
10167/// \param OrigD The member declaration instantiated from the template.
10168/// \param Loc The location of the explicit specialization of the member.
10169template<typename DeclT>
10170static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10171 SourceLocation Loc) {
10172 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10173 return;
10174
10175 // FIXME: Inform AST mutation listeners of this AST mutation.
10176 // FIXME: If there are multiple in-class declarations of the member (from
10177 // multiple modules, or a declaration and later definition of a member type),
10178 // should we update all of them?
10179 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10180 OrigD->setLocation(Loc);
10181}
10182
10185 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10186 if (Instantiation == Member)
10187 return;
10188
10189 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10190 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10191 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10192 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10193 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10194 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10195 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10196 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10197 else
10198 llvm_unreachable("unknown member specialization kind");
10199}
10200
10201/// Check the scope of an explicit instantiation.
10202///
10203/// \returns true if a serious error occurs, false otherwise.
10205 SourceLocation InstLoc,
10206 bool WasQualifiedName) {
10208 DeclContext *CurContext = S.CurContext->getRedeclContext();
10209
10210 if (CurContext->isRecord()) {
10211 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10212 << D;
10213 return true;
10214 }
10215
10216 // C++11 [temp.explicit]p3:
10217 // An explicit instantiation shall appear in an enclosing namespace of its
10218 // template. If the name declared in the explicit instantiation is an
10219 // unqualified name, the explicit instantiation shall appear in the
10220 // namespace where its template is declared or, if that namespace is inline
10221 // (7.3.1), any namespace from its enclosing namespace set.
10222 //
10223 // This is DR275, which we do not retroactively apply to C++98/03.
10224 if (WasQualifiedName) {
10225 if (CurContext->Encloses(OrigContext))
10226 return false;
10227 } else {
10228 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10229 return false;
10230 }
10231
10232 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10233 if (WasQualifiedName)
10234 S.Diag(InstLoc,
10235 S.getLangOpts().CPlusPlus11?
10236 diag::err_explicit_instantiation_out_of_scope :
10237 diag::warn_explicit_instantiation_out_of_scope_0x)
10238 << D << NS;
10239 else
10240 S.Diag(InstLoc,
10241 S.getLangOpts().CPlusPlus11?
10242 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10243 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10244 << D << NS;
10245 } else
10246 S.Diag(InstLoc,
10247 S.getLangOpts().CPlusPlus11?
10248 diag::err_explicit_instantiation_must_be_global :
10249 diag::warn_explicit_instantiation_must_be_global_0x)
10250 << D;
10251 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10252 return false;
10253}
10254
10255/// Common checks for whether an explicit instantiation of \p D is valid.
10257 SourceLocation InstLoc,
10258 bool WasQualifiedName,
10260 // C++ [temp.explicit]p13:
10261 // An explicit instantiation declaration shall not name a specialization of
10262 // a template with internal linkage.
10265 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10266 return true;
10267 }
10268
10269 // C++11 [temp.explicit]p3: [DR 275]
10270 // An explicit instantiation shall appear in an enclosing namespace of its
10271 // template.
10272 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10273 return true;
10274
10275 return false;
10276}
10277
10278/// Determine whether the given scope specifier has a template-id in it.
10280 // C++11 [temp.explicit]p3:
10281 // If the explicit instantiation is for a member function, a member class
10282 // or a static data member of a class template specialization, the name of
10283 // the class template specialization in the qualified-id for the member
10284 // name shall be a simple-template-id.
10285 //
10286 // C++98 has the same restriction, just worded differently.
10287 for (NestedNameSpecifier NNS = SS.getScopeRep();
10289 /**/) {
10290 const Type *T = NNS.getAsType();
10292 return true;
10293 NNS = T->getPrefix();
10294 }
10295 return false;
10296}
10297
10298/// Make a dllexport or dllimport attr on a class template specialization take
10299/// effect.
10302 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10303 assert(A && "dllExportImportClassTemplateSpecialization called "
10304 "on Def without dllexport or dllimport");
10305
10306 // We reject explicit instantiations in class scope, so there should
10307 // never be any delayed exported classes to worry about.
10308 assert(S.DelayedDllExportClasses.empty() &&
10309 "delayed exports present at explicit instantiation");
10311
10312 // Propagate attribute to base class templates.
10313 for (auto &B : Def->bases()) {
10314 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10315 B.getType()->getAsCXXRecordDecl()))
10317 }
10318
10320}
10321
10323 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10324 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10325 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10326 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10327 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10328 // Find the class template we're specializing
10329 TemplateName Name = TemplateD.get();
10330 TemplateDecl *TD = Name.getAsTemplateDecl();
10331 // Check that the specialization uses the same tag kind as the
10332 // original template.
10334 assert(Kind != TagTypeKind::Enum &&
10335 "Invalid enum tag in class template explicit instantiation!");
10336
10337 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10338
10339 if (!ClassTemplate) {
10340 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10341 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10342 Diag(TD->getLocation(), diag::note_previous_use);
10343 return true;
10344 }
10345
10346 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10347 Kind, /*isDefinition*/false, KWLoc,
10348 ClassTemplate->getIdentifier())) {
10349 Diag(KWLoc, diag::err_use_with_wrong_tag)
10350 << ClassTemplate
10352 ClassTemplate->getTemplatedDecl()->getKindName());
10353 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10354 diag::note_previous_use);
10355 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10356 }
10357
10358 // C++0x [temp.explicit]p2:
10359 // There are two forms of explicit instantiation: an explicit instantiation
10360 // definition and an explicit instantiation declaration. An explicit
10361 // instantiation declaration begins with the extern keyword. [...]
10362 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10365
10367 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10368 // Check for dllexport class template instantiation declarations,
10369 // except for MinGW mode.
10370 for (const ParsedAttr &AL : Attr) {
10371 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10372 Diag(ExternLoc,
10373 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10374 Diag(AL.getLoc(), diag::note_attribute);
10375 break;
10376 }
10377 }
10378
10379 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10380 Diag(ExternLoc,
10381 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10382 Diag(A->getLocation(), diag::note_attribute);
10383 }
10384 }
10385
10386 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10387 // instantiation declarations for most purposes.
10388 bool DLLImportExplicitInstantiationDef = false;
10390 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10391 // Check for dllimport class template instantiation definitions.
10392 bool DLLImport =
10393 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10394 for (const ParsedAttr &AL : Attr) {
10395 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10396 DLLImport = true;
10397 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10398 // dllexport trumps dllimport here.
10399 DLLImport = false;
10400 break;
10401 }
10402 }
10403 if (DLLImport) {
10405 DLLImportExplicitInstantiationDef = true;
10406 }
10407 }
10408
10409 // Translate the parser's template argument list in our AST format.
10410 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10411 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10412
10413 // Check that the template argument list is well-formed for this
10414 // template.
10416 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10417 /*DefaultArgs=*/{}, false, CTAI,
10418 /*UpdateArgsWithConversions=*/true,
10419 /*ConstraintsNotSatisfied=*/nullptr))
10420 return true;
10421
10422 // Find the class template specialization declaration that
10423 // corresponds to these arguments.
10424 llvm::FoldingSetInsertToken InsertToken;
10426 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertToken);
10427
10428 TemplateSpecializationKind PrevDecl_TSK
10429 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10430
10431 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10432 Context.getTargetInfo().getTriple().isOSCygMing()) {
10433 // Check for dllexport class template instantiation definitions in MinGW
10434 // mode, if a previous declaration of the instantiation was seen.
10435 for (const ParsedAttr &AL : Attr) {
10436 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10437 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10438 Diag(AL.getLoc(), diag::warn_attr_dllexport_explicit_inst_def);
10439 } else {
10440 Diag(AL.getLoc(),
10441 diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10442 Diag(PrevDecl->getLocation(), diag::note_prev_decl_missing_dllexport);
10443 }
10444 break;
10445 }
10446 }
10447 }
10448
10449 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10450 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10451 llvm::none_of(Attr, [](const ParsedAttr &AL) {
10452 return AL.getKind() == ParsedAttr::AT_DLLExport;
10453 })) {
10454 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10455 Diag(TemplateLoc, diag::warn_dllexport_on_decl_ignored);
10456 Diag(DEA->getLoc(), diag::note_dllexport_on_decl);
10457 }
10458 }
10459
10460 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10461 SS.isSet(), TSK))
10462 return true;
10463
10465
10466 bool HasNoEffect = false;
10467 if (PrevDecl) {
10468 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10469 PrevDecl, PrevDecl_TSK,
10470 PrevDecl->getPointOfInstantiation(),
10471 HasNoEffect))
10472 return PrevDecl;
10473
10474 // Even though HasNoEffect == true means that this explicit instantiation
10475 // has no effect on semantics, we go on to put its syntax in the AST.
10476
10477 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10478 PrevDecl_TSK == TSK_Undeclared) {
10479 // Since the only prior class template specialization with these
10480 // arguments was referenced but not declared, reuse that
10481 // declaration node as our own, updating the source location
10482 // for the template name to reflect our new declaration.
10483 // (Other source locations will be updated later.)
10484 Specialization = PrevDecl;
10485 Specialization->setLocation(TemplateNameLoc);
10486 PrevDecl = nullptr;
10487 }
10488
10489 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10490 DLLImportExplicitInstantiationDef) {
10491 // The new specialization might add a dllimport attribute.
10492 HasNoEffect = false;
10493 }
10494 }
10495
10496 if (!Specialization) {
10497 // Create a new class template specialization declaration node for
10498 // this explicit specialization.
10500 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10501 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10503
10504 // A MSInheritanceAttr attached to the previous declaration must be
10505 // propagated to the new node prior to instantiation.
10506 if (PrevDecl) {
10507 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10508 auto *Clone = A->clone(getASTContext());
10509 Clone->setInherited(true);
10510 Specialization->addAttr(Clone);
10511 Consumer.AssignInheritanceModel(Specialization);
10512 }
10513 }
10514
10515 if (!HasNoEffect && !PrevDecl) {
10516 // Insert the new specialization.
10517 ClassTemplate->AddSpecialization(Specialization, InsertToken);
10518 }
10519 }
10520
10521 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10522
10523 // Set source locations for keywords.
10524 Specialization->setExternKeywordLoc(ExternLoc);
10525 Specialization->setTemplateKeywordLoc(TemplateLoc);
10526 Specialization->setBraceRange(SourceRange());
10527
10528 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10531
10532 // Add the explicit instantiation into its lexical context. However,
10533 // since explicit instantiations are never found by name lookup, we
10534 // just put it into the declaration context directly.
10535 Specialization->setLexicalDeclContext(CurContext);
10536 CurContext->addDecl(Specialization);
10537
10538 // Syntax is now OK, so return if it has no other effect on semantics.
10539 if (HasNoEffect) {
10540 // Set the template specialization kind.
10541 Specialization->setTemplateSpecializationKind(TSK);
10542
10544 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10545 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10546 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10547 Context.getCanonicalTagType(Specialization));
10549 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10550 TemplateNameLoc, TSI, TSK);
10551 return Specialization;
10552 }
10553
10554 // C++ [temp.explicit]p3:
10555 // A definition of a class template or class member template
10556 // shall be in scope at the point of the explicit instantiation of
10557 // the class template or class member template.
10558 //
10559 // This check comes when we actually try to perform the
10560 // instantiation.
10562 = cast_or_null<ClassTemplateSpecializationDecl>(
10563 Specialization->getDefinition());
10564 if (!Def)
10566 /*Complain=*/true,
10567 CTAI.StrictPackMatch);
10568 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10569 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10570 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10571 }
10572
10573 // Instantiate the members of this class template specialization.
10574 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10575 Specialization->getDefinition());
10576 if (Def) {
10578 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10579 // TSK_ExplicitInstantiationDefinition
10580 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10582 DLLImportExplicitInstantiationDef)) {
10583 // FIXME: Need to notify the ASTMutationListener that we did this.
10585
10586 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10587 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10588 // An explicit instantiation definition can add a dll attribute to a
10589 // template with a previous instantiation declaration. MinGW doesn't
10590 // allow this.
10591 auto *A = cast<InheritableAttr>(
10593 A->setInherited(true);
10594 Def->addAttr(A);
10596 }
10597 }
10598
10599 // Fix a TSK_ImplicitInstantiation followed by a
10600 // TSK_ExplicitInstantiationDefinition
10601 bool NewlyDLLExported =
10602 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10603 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10604 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10605 // An explicit instantiation definition can add a dll attribute to a
10606 // template with a previous implicit instantiation. MinGW doesn't allow
10607 // this. We limit clang to only adding dllexport, to avoid potentially
10608 // strange codegen behavior. For example, if we extend this conditional
10609 // to dllimport, and we have a source file calling a method on an
10610 // implicitly instantiated template class instance and then declaring a
10611 // dllimport explicit instantiation definition for the same template
10612 // class, the codegen for the method call will not respect the dllimport,
10613 // while it will with cl. The Def will already have the DLL attribute,
10614 // since the Def and Specialization will be the same in the case of
10615 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10616 // attribute to the Specialization; we just need to make it take effect.
10617 assert(Def == Specialization &&
10618 "Def and Specialization should match for implicit instantiation");
10620 }
10621
10622 // In MinGW mode, export the template instantiation if the declaration
10623 // was marked dllexport.
10624 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10625 Context.getTargetInfo().getTriple().isOSCygMing() &&
10626 PrevDecl->hasAttr<DLLExportAttr>()) {
10628 }
10629
10630 // Set the template specialization kind. Make sure it is set before
10631 // instantiating the members which will trigger ASTConsumer callbacks.
10632 Specialization->setTemplateSpecializationKind(TSK);
10633 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10634 } else {
10635
10636 // Set the template specialization kind.
10637 Specialization->setTemplateSpecializationKind(TSK);
10638 }
10639
10641 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10642 KW, KWLoc, SS.getWithLocInContext(Context), SourceLocation(), Name,
10643 TemplateNameLoc, TemplateArgs, CTAI.CanonicalConverted,
10644 Context.getCanonicalTagType(Specialization));
10646 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10647 TemplateNameLoc, TSI, TSK);
10648 return Specialization;
10649}
10650
10653 SourceLocation TemplateLoc, unsigned TagSpec,
10654 SourceLocation KWLoc, CXXScopeSpec &SS,
10655 IdentifierInfo *Name, SourceLocation NameLoc,
10656 const ParsedAttributesView &Attr) {
10657
10658 bool Owned = false;
10659 bool IsDependent = false;
10660 Decl *TagD =
10661 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10662 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10663 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10664 false, TypeResult(), /*IsTypeSpecifier*/ false,
10665 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10666 .get();
10667
10668 if (!TagD)
10669 return true;
10670
10671 assert(!IsDependent &&
10672 "explicit instantiation of dependent name not yet handled");
10673
10674 TagDecl *Tag = cast<TagDecl>(TagD);
10675 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10676
10677 if (Tag->isInvalidDecl())
10678 return true;
10679
10681 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10682 if (!Pattern) {
10683 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10684 << Context.getCanonicalTagType(Record);
10685 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10686 return true;
10687 }
10688
10689 // C++0x [temp.explicit]p2:
10690 // If the explicit instantiation is for a class or member class, the
10691 // elaborated-type-specifier in the declaration shall include a
10692 // simple-template-id.
10693 //
10694 // C++98 has the same restriction, just worded differently.
10696 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10697 << Record << SS.getRange();
10698
10699 // C++0x [temp.explicit]p2:
10700 // There are two forms of explicit instantiation: an explicit instantiation
10701 // definition and an explicit instantiation declaration. An explicit
10702 // instantiation declaration begins with the extern keyword. [...]
10706
10707 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10708
10709 // Verify that it is okay to explicitly instantiate here.
10710 CXXRecordDecl *PrevDecl
10711 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10712 if (!PrevDecl && Record->getDefinition())
10713 PrevDecl = Record;
10714 if (PrevDecl) {
10716 bool HasNoEffect = false;
10717 assert(MSInfo && "No member specialization information?");
10718 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10719 PrevDecl,
10721 MSInfo->getPointOfInstantiation(),
10722 HasNoEffect))
10723 return true;
10724 if (HasNoEffect) {
10728 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10729 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10730 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10731 TL.setElaboratedKeywordLoc(KWLoc);
10732 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10733 TL.setNameLoc(NameLoc);
10735 TemplateLoc, NestedNameSpecifierLoc(),
10736 nullptr, NameLoc, TSI, TSK);
10737 return TagD;
10738 }
10739 }
10740
10741 CXXRecordDecl *RecordDef
10742 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10743 if (!RecordDef) {
10744 // C++ [temp.explicit]p3:
10745 // A definition of a member class of a class template shall be in scope
10746 // at the point of an explicit instantiation of the member class.
10747 CXXRecordDecl *Def
10748 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10749 if (!Def) {
10750 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10751 << 0 << Record->getDeclName() << Record->getDeclContext();
10752 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10753 << Pattern;
10754 return true;
10755 } else {
10756 if (InstantiateClass(NameLoc, Record, Def,
10758 TSK))
10759 return true;
10760
10761 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10762 if (!RecordDef)
10763 return true;
10764 }
10765 }
10766
10767 // Instantiate all of the members of the class.
10768 InstantiateClassMembers(NameLoc, RecordDef,
10770
10772 MarkVTableUsed(NameLoc, RecordDef, true);
10773
10776 QualType TagTy = Context.getTagType(KW, SS.getScopeRep(), Record, false);
10777 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(TagTy);
10778 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10779 TL.setElaboratedKeywordLoc(KWLoc);
10780 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10781 TL.setNameLoc(NameLoc);
10783 TemplateLoc, NestedNameSpecifierLoc(), nullptr,
10784 NameLoc, TSI, TSK);
10785 return TagD;
10786}
10787
10789 SourceLocation ExternLoc,
10790 SourceLocation TemplateLoc,
10791 Declarator &D) {
10792 // Explicit instantiations always require a name.
10793 // TODO: check if/when DNInfo should replace Name.
10795 DeclarationName Name = NameInfo.getName();
10796 if (!Name) {
10797 if (!D.isInvalidType())
10799 diag::err_explicit_instantiation_requires_name)
10801
10802 return true;
10803 }
10804
10805 // Get the innermost enclosing declaration scope.
10806 S = S->getDeclParent();
10807
10808 // Determine the type of the declaration.
10810 QualType R = T->getType();
10811 if (R.isNull())
10812 return true;
10813
10814 // C++ [dcl.stc]p1:
10815 // A storage-class-specifier shall not be specified in [...] an explicit
10816 // instantiation (14.7.2) directive.
10818 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10819 << Name;
10820 return true;
10821 } else if (D.getDeclSpec().getStorageClassSpec()
10823 // Complain about then remove the storage class specifier.
10824 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10826
10828 }
10829
10830 // C++0x [temp.explicit]p1:
10831 // [...] An explicit instantiation of a function template shall not use the
10832 // inline or constexpr specifiers.
10833 // Presumably, this also applies to member functions of class templates as
10834 // well.
10838 diag::err_explicit_instantiation_inline :
10839 diag::warn_explicit_instantiation_inline_0x)
10841 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10842 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10843 // not already specified.
10845 diag::err_explicit_instantiation_constexpr);
10846
10847 // A deduction guide is not on the list of entities that can be explicitly
10848 // instantiated.
10850 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10851 << /*explicit instantiation*/ 0;
10852 return true;
10853 }
10854
10855 // C++0x [temp.explicit]p2:
10856 // There are two forms of explicit instantiation: an explicit instantiation
10857 // definition and an explicit instantiation declaration. An explicit
10858 // instantiation declaration begins with the extern keyword. [...]
10862
10863 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10865 /*ObjectType=*/QualType());
10866
10867 if (!R->isFunctionType()) {
10868 // C++ [temp.explicit]p1:
10869 // A [...] static data member of a class template can be explicitly
10870 // instantiated from the member definition associated with its class
10871 // template.
10872 // C++1y [temp.explicit]p1:
10873 // A [...] variable [...] template specialization can be explicitly
10874 // instantiated from its template.
10875 if (Previous.isAmbiguous())
10876 return true;
10877
10878 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10879 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10880 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10881
10882 if (!PrevTemplate) {
10883 if (!Prev || !Prev->isStaticDataMember()) {
10884 // We expect to see a static data member here.
10885 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10886 << Name;
10887 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10888 P != PEnd; ++P)
10889 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10890 return true;
10891 }
10892
10894 // FIXME: Check for explicit specialization?
10896 diag::err_explicit_instantiation_data_member_not_instantiated)
10897 << Prev;
10898 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10899 // FIXME: Can we provide a note showing where this was declared?
10900 return true;
10901 }
10902 } else {
10903 // Explicitly instantiate a variable template.
10904
10905 // C++1y [dcl.spec.auto]p6:
10906 // ... A program that uses auto or decltype(auto) in a context not
10907 // explicitly allowed in this section is ill-formed.
10908 //
10909 // This includes auto-typed variable template instantiations.
10910 if (R->isUndeducedType()) {
10911 Diag(T->getTypeLoc().getBeginLoc(),
10912 diag::err_auto_not_allowed_var_inst);
10913 return true;
10914 }
10915
10917 // C++1y [temp.explicit]p3:
10918 // If the explicit instantiation is for a variable, the unqualified-id
10919 // in the declaration shall be a template-id.
10921 diag::err_explicit_instantiation_without_template_id)
10922 << PrevTemplate;
10923 Diag(PrevTemplate->getLocation(),
10924 diag::note_explicit_instantiation_here);
10925 return true;
10926 }
10927
10928 // Translate the parser's template argument list into our AST format.
10929 TemplateArgumentListInfo TemplateArgs =
10931
10932 DeclResult Res =
10933 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),
10934 TemplateArgs, /*SetWrittenArgs=*/true);
10935 if (Res.isInvalid())
10936 return true;
10937
10938 if (!Res.isUsable()) {
10939 // We somehow specified dependent template arguments in an explicit
10940 // instantiation. This should probably only happen during error
10941 // recovery.
10942 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10943 return true;
10944 }
10945
10946 // Ignore access control bits, we don't need them for redeclaration
10947 // checking.
10948 Prev = cast<VarDecl>(Res.get());
10949 ArgsAsWritten =
10951 }
10952
10953 // C++0x [temp.explicit]p2:
10954 // If the explicit instantiation is for a member function, a member class
10955 // or a static data member of a class template specialization, the name of
10956 // the class template specialization in the qualified-id for the member
10957 // name shall be a simple-template-id.
10958 //
10959 // C++98 has the same restriction, just worded differently.
10960 //
10961 // This does not apply to variable template specializations, where the
10962 // template-id is in the unqualified-id instead.
10963 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10965 diag::ext_explicit_instantiation_without_qualified_id)
10966 << Prev << D.getCXXScopeSpec().getRange();
10967
10968 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10969
10970 // Verify that it is okay to explicitly instantiate here.
10973 bool HasNoEffect = false;
10975 PrevTSK, POI, HasNoEffect))
10976 return true;
10977
10978 if (!HasNoEffect) {
10979 // Instantiate static data member or variable template.
10981 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Prev)) {
10982 VTSD->setExternKeywordLoc(ExternLoc);
10983 VTSD->setTemplateKeywordLoc(TemplateLoc);
10984 }
10985
10986 // Merge attributes.
10988 if (PrevTemplate)
10989 ProcessAPINotes(Prev);
10990
10993 }
10994
10995 // Check the new variable specialization against the parsed input.
10996 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10997 Diag(T->getTypeLoc().getBeginLoc(),
10998 diag::err_invalid_var_template_spec_type)
10999 << 0 << PrevTemplate << R << Prev->getType();
11000 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11001 << 2 << PrevTemplate->getDeclName();
11002 return true;
11003 }
11004
11006 Context, CurContext, Prev, ExternLoc, TemplateLoc,
11007 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11008 D.getIdentifierLoc(), T, TSK);
11009 return (Decl *)nullptr;
11010 }
11011
11012 // If the declarator is a template-id, translate the parser's template
11013 // argument list into our AST format.
11014 bool HasExplicitTemplateArgs = false;
11015 TemplateArgumentListInfo TemplateArgs;
11017 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11018 HasExplicitTemplateArgs = true;
11019 }
11020
11021 // C++ [temp.explicit]p1:
11022 // A [...] function [...] can be explicitly instantiated from its template.
11023 // A member function [...] of a class template can be explicitly
11024 // instantiated from the member definition associated with its class
11025 // template.
11026 UnresolvedSet<8> TemplateMatches;
11027 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11029 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11030 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11031 P != PEnd; ++P) {
11032 NamedDecl *Prev = *P;
11033 if (!HasExplicitTemplateArgs) {
11034 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11035 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11036 /*AdjustExceptionSpec*/true);
11037 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11038 if (Method->getPrimaryTemplate()) {
11039 TemplateMatches.addDecl(Method, P.getAccess());
11040 } else {
11041 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11042 C.FoundDecl = P.getPair();
11043 C.Function = Method;
11044 C.Viable = true;
11046 if (Method->getTrailingRequiresClause() &&
11048 /*ForOverloadResolution=*/true) ||
11049 !S.IsSatisfied)) {
11050 C.Viable = false;
11052 }
11053 }
11054 }
11055 }
11056 }
11057
11058 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11059 if (!FunTmpl)
11060 continue;
11061
11062 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11063 FunctionDecl *Specialization = nullptr;
11065 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11066 Specialization, Info);
11068 // Keep track of almost-matches.
11069 FailedTemplateCandidates.addCandidate().set(
11070 P.getPair(), FunTmpl->getTemplatedDecl(),
11071 MakeDeductionFailureInfo(Context, TDK, Info));
11072 (void)TDK;
11073 continue;
11074 }
11075
11076 // Target attributes are part of the cuda function signature, so
11077 // the cuda target of the instantiated function must match that of its
11078 // template. Given that C++ template deduction does not take
11079 // target attributes into account, we reject candidates here that
11080 // have a different target.
11081 if (LangOpts.CUDA &&
11082 CUDA().IdentifyTarget(Specialization,
11083 /* IgnoreImplicitHDAttr = */ true) !=
11084 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
11085 FailedTemplateCandidates.addCandidate().set(
11086 P.getPair(), FunTmpl->getTemplatedDecl(),
11089 continue;
11090 }
11091
11092 TemplateMatches.addDecl(Specialization, P.getAccess());
11093 }
11094
11095 FunctionDecl *Specialization = nullptr;
11096 if (!NonTemplateMatches.empty()) {
11097 unsigned Msg = 0;
11098 OverloadCandidateDisplayKind DisplayKind;
11100 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
11101 Best)) {
11102 case OR_Success:
11103 case OR_Deleted:
11104 Specialization = cast<FunctionDecl>(Best->Function);
11105 break;
11106 case OR_Ambiguous:
11107 Msg = diag::err_explicit_instantiation_ambiguous;
11108 DisplayKind = OCD_AmbiguousCandidates;
11109 break;
11111 Msg = diag::err_explicit_instantiation_no_candidate;
11112 DisplayKind = OCD_AllCandidates;
11113 break;
11114 }
11115 if (Msg) {
11116 PartialDiagnostic Diag = PDiag(Msg) << Name;
11117 NonTemplateMatches.NoteCandidates(
11118 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
11119 {});
11120 return true;
11121 }
11122 }
11123
11124 if (!Specialization) {
11125 // Find the most specialized function template specialization.
11127 TemplateMatches.begin(), TemplateMatches.end(),
11128 FailedTemplateCandidates, D.getIdentifierLoc(),
11129 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11130 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11131 PDiag(diag::note_explicit_instantiation_candidate));
11132
11133 if (Result == TemplateMatches.end())
11134 return true;
11135
11136 // Ignore access control bits, we don't need them for redeclaration checking.
11138 }
11139
11140 // C++11 [except.spec]p4
11141 // In an explicit instantiation an exception-specification may be specified,
11142 // but is not required.
11143 // If an exception-specification is specified in an explicit instantiation
11144 // directive, it shall be compatible with the exception-specifications of
11145 // other declarations of that function.
11146 if (auto *FPT = R->getAs<FunctionProtoType>())
11147 if (FPT->hasExceptionSpec()) {
11148 unsigned DiagID =
11149 diag::err_mismatched_exception_spec_explicit_instantiation;
11150 if (getLangOpts().MicrosoftExt)
11151 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11153 PDiag(DiagID) << Specialization->getType(),
11154 PDiag(diag::note_explicit_instantiation_here),
11155 Specialization->getType()->getAs<FunctionProtoType>(),
11156 Specialization->getLocation(), FPT, D.getBeginLoc());
11157 // In Microsoft mode, mismatching exception specifications just cause a
11158 // warning.
11159 if (!getLangOpts().MicrosoftExt && Result)
11160 return true;
11161 }
11162
11163 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11165 diag::err_explicit_instantiation_member_function_not_instantiated)
11167 << (Specialization->getTemplateSpecializationKind() ==
11169 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11170 return true;
11171 }
11172
11173 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11174 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11175 PrevDecl = Specialization;
11176
11177 if (PrevDecl) {
11178 bool HasNoEffect = false;
11180 PrevDecl,
11182 PrevDecl->getPointOfInstantiation(),
11183 HasNoEffect))
11184 return true;
11185
11186 if (HasNoEffect) {
11187 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11188 if (HasExplicitTemplateArgs)
11189 ArgsAsWritten =
11192 Context, CurContext, Specialization, ExternLoc, TemplateLoc,
11193 D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11194 D.getIdentifierLoc(), T, TSK);
11195 return (Decl *)nullptr;
11196 }
11197 }
11198
11199 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11200 // functions
11201 // valarray<size_t>::valarray(size_t) and
11202 // valarray<size_t>::~valarray()
11203 // that it declared to have internal linkage with the internal_linkage
11204 // attribute. Ignore the explicit instantiation declaration in this case.
11205 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11207 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11208 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11209 RD->isInStdNamespace())
11210 return (Decl*) nullptr;
11211 }
11212
11215
11216 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11217 // instantiation declarations.
11219 Specialization->hasAttr<DLLImportAttr>() &&
11220 Context.getTargetInfo().getCXXABI().isMicrosoft())
11222
11223 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11224 if (Specialization->isDefined()) {
11225 // Let the ASTConsumer know that this function has been explicitly
11226 // instantiated now, and its linkage might have changed.
11227 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
11228 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11229 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11230 // be explicitly instantiated.
11231 if (const auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getParent());
11232 RD && RD->isLambda()) {
11233 Diag(D.getBeginLoc(), diag::err_lambda_explicit_temp_spec)
11234 << /*instantiation*/ 1;
11235 Diag(RD->getLocation(), diag::note_defined_here) << RD;
11236 return (Decl *)nullptr;
11237 }
11239 }
11240
11241 // C++0x [temp.explicit]p2:
11242 // If the explicit instantiation is for a member function, a member class
11243 // or a static data member of a class template specialization, the name of
11244 // the class template specialization in the qualified-id for the member
11245 // name shall be a simple-template-id.
11246 //
11247 // C++98 has the same restriction, just worded differently.
11248 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11249 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11250 D.getCXXScopeSpec().isSet() &&
11253 diag::ext_explicit_instantiation_without_qualified_id)
11255
11257 *this,
11258 FunTmpl ? (NamedDecl *)FunTmpl
11259 : Specialization->getInstantiatedFromMemberFunction(),
11260 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11261
11262 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11263 if (HasExplicitTemplateArgs)
11264 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(Context, TemplateArgs);
11266 TemplateLoc,
11268 ArgsAsWritten, D.getIdentifierLoc(), T, TSK);
11269 return (Decl *)nullptr;
11270}
11271
11273 const CXXScopeSpec &SS,
11274 const IdentifierInfo *Name,
11275 SourceLocation TagLoc,
11276 SourceLocation NameLoc) {
11277 // This has to hold, because SS is expected to be defined.
11278 assert(Name && "Expected a name in a dependent tag");
11279
11281 if (!NNS)
11282 return true;
11283
11284 if (TUK == TagUseKind::Friend &&
11286 return true;
11287
11289
11290 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11291 Diag(NameLoc, diag::err_dependent_tag_decl)
11292 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11293 return true;
11294 }
11295
11296 // Create the resulting type.
11298 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11299
11300 // Create type-source location information for this type.
11301 TypeLocBuilder TLB;
11303 TL.setElaboratedKeywordLoc(TagLoc);
11305 TL.setNameLoc(NameLoc);
11307}
11308
11310 const CXXScopeSpec &SS,
11311 const IdentifierInfo &II,
11312 SourceLocation IdLoc,
11313 ImplicitTypenameContext IsImplicitTypename) {
11314 if (SS.isInvalid())
11315 return true;
11316
11317 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11318 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11319 << FixItHint::CreateRemoval(TypenameLoc);
11320
11322 TypeSourceInfo *TSI = nullptr;
11323 QualType T =
11326 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11327 /*DeducedTSTContext=*/true);
11328 if (T.isNull())
11329 return true;
11330 return CreateParsedType(T, TSI);
11331}
11332
11335 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11336 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11337 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11338 ASTTemplateArgsPtr TemplateArgsIn,
11339 SourceLocation RAngleLoc) {
11340 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11341 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11342 ? diag::compat_cxx11_typename_outside_of_template
11343 : diag::compat_pre_cxx11_typename_outside_of_template)
11344 << FixItHint::CreateRemoval(TypenameLoc);
11345
11346 // Strangely, non-type results are not ignored by this lookup, so the
11347 // program is ill-formed if it finds an injected-class-name.
11348 if (TypenameLoc.isValid()) {
11349 auto *LookupRD =
11350 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11351 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11352 Diag(TemplateIILoc,
11353 diag::ext_out_of_line_qualified_id_type_names_constructor)
11354 << TemplateII << 0 /*injected-class-name used as template name*/
11355 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11356 }
11357 }
11358
11359 // Translate the parser's template argument list in our AST format.
11360 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11361 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11362
11366 TemplateIn.get(), TemplateIILoc, TemplateArgs,
11367 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11368 if (T.isNull())
11369 return true;
11370
11371 // Provide source-location information for the template specialization type.
11372 TypeLocBuilder Builder;
11374 = Builder.push<TemplateSpecializationTypeLoc>(T);
11375 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11376 TemplateIILoc, TemplateArgs);
11377 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11378 return CreateParsedType(T, TSI);
11379}
11380
11381/// Determine whether this failed name lookup should be treated as being
11382/// disabled by a usage of std::enable_if.
11384 SourceRange &CondRange, Expr *&Cond) {
11385 // We must be looking for a ::type...
11386 if (!II.isStr("type"))
11387 return false;
11388
11389 // ... within an explicitly-written template specialization...
11391 return false;
11392
11393 // FIXME: Look through sugar.
11394 auto EnableIfTSTLoc =
11396 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11397 return false;
11398 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11399
11400 // ... which names a complete class template declaration...
11401 const TemplateDecl *EnableIfDecl =
11402 EnableIfTST->getTemplateName().getAsTemplateDecl();
11403 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11404 return false;
11405
11406 // ... called "enable_if".
11407 const IdentifierInfo *EnableIfII =
11408 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11409 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11410 return false;
11411
11412 // Assume the first template argument is the condition.
11413 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11414
11415 // Dig out the condition.
11416 Cond = nullptr;
11417 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11419 return true;
11420
11421 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11422
11423 // Ignore Boolean literals; they add no value.
11425 Cond = nullptr;
11426
11427 return true;
11428}
11429
11432 SourceLocation KeywordLoc,
11433 NestedNameSpecifierLoc QualifierLoc,
11434 const IdentifierInfo &II,
11435 SourceLocation IILoc,
11436 TypeSourceInfo **TSI,
11437 bool DeducedTSTContext) {
11438 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11439 DeducedTSTContext);
11440 if (T.isNull())
11441 return QualType();
11442
11443 TypeLocBuilder TLB;
11445 auto TL = TLB.push<DependentNameTypeLoc>(T);
11446 TL.setElaboratedKeywordLoc(KeywordLoc);
11447 TL.setQualifierLoc(QualifierLoc);
11448 TL.setNameLoc(IILoc);
11451 TL.setElaboratedKeywordLoc(KeywordLoc);
11452 TL.setQualifierLoc(QualifierLoc);
11453 TL.setNameLoc(IILoc);
11454 } else if (isa<TemplateTypeParmType>(T)) {
11455 // FIXME: There might be a 'typename' keyword here, but we just drop it
11456 // as it can't be represented.
11457 assert(!QualifierLoc);
11458 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11459 } else if (isa<TagType>(T)) {
11460 auto TL = TLB.push<TagTypeLoc>(T);
11461 TL.setElaboratedKeywordLoc(KeywordLoc);
11462 TL.setQualifierLoc(QualifierLoc);
11463 TL.setNameLoc(IILoc);
11464 } else if (isa<TypedefType>(T)) {
11465 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11466 } else {
11467 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11468 }
11469 *TSI = TLB.getTypeSourceInfo(Context, T);
11470 return T;
11471}
11472
11473/// Build the type that describes a C++ typename specifier,
11474/// e.g., "typename T::type".
11477 SourceLocation KeywordLoc,
11478 NestedNameSpecifierLoc QualifierLoc,
11479 const IdentifierInfo &II,
11480 SourceLocation IILoc, bool DeducedTSTContext) {
11481 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11482
11483 CXXScopeSpec SS;
11484 SS.Adopt(QualifierLoc);
11485
11486 DeclContext *Ctx = nullptr;
11487 if (QualifierLoc) {
11488 Ctx = computeDeclContext(SS);
11489 if (!Ctx) {
11490 // If the nested-name-specifier is dependent and couldn't be
11491 // resolved to a type, build a typename type.
11492 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11493 return Context.getDependentNameType(Keyword,
11494 QualifierLoc.getNestedNameSpecifier(),
11495 &II);
11496 }
11497
11498 // If the nested-name-specifier refers to the current instantiation,
11499 // the "typename" keyword itself is superfluous. In C++03, the
11500 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11501 // allows such extraneous "typename" keywords, and we retroactively
11502 // apply this DR to C++03 code with only a warning. In any case we continue.
11503
11504 if (RequireCompleteDeclContext(SS, Ctx))
11505 return QualType();
11506 }
11507
11508 DeclarationName Name(&II);
11509 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11510 if (Ctx)
11511 LookupQualifiedName(Result, Ctx, SS);
11512 else
11513 LookupName(Result, CurScope);
11514 unsigned DiagID = 0;
11515 Decl *Referenced = nullptr;
11516 switch (Result.getResultKind()) {
11518 // If we're looking up 'type' within a template named 'enable_if', produce
11519 // a more specific diagnostic.
11520 SourceRange CondRange;
11521 Expr *Cond = nullptr;
11522 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11523 // If we have a condition, narrow it down to the specific failed
11524 // condition.
11525 if (Cond) {
11526 Expr *FailedCond;
11527 std::string FailedDescription;
11528 std::tie(FailedCond, FailedDescription) =
11530
11531 Diag(FailedCond->getExprLoc(),
11532 diag::err_typename_nested_not_found_requirement)
11533 << FailedDescription
11534 << FailedCond->getSourceRange();
11535 return QualType();
11536 }
11537
11538 Diag(CondRange.getBegin(),
11539 diag::err_typename_nested_not_found_enable_if)
11540 << Ctx << CondRange;
11541 return QualType();
11542 }
11543
11544 DiagID = Ctx ? diag::err_typename_nested_not_found
11545 : diag::err_unknown_typename;
11546 break;
11547 }
11548
11550 // We found a using declaration that is a value. Most likely, the using
11551 // declaration itself is meant to have the 'typename' keyword.
11552 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11553 IILoc);
11554 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11555 << Name << Ctx << FullRange;
11556 if (UnresolvedUsingValueDecl *Using
11557 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11558 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11559 Diag(Loc, diag::note_using_value_decl_missing_typename)
11560 << FixItHint::CreateInsertion(Loc, "typename ");
11561 }
11562 }
11563 // Fall through to create a dependent typename type, from which we can
11564 // recover better.
11565 [[fallthrough]];
11566
11568 // Okay, it's a member of an unknown instantiation.
11569 return Context.getDependentNameType(Keyword,
11570 QualifierLoc.getNestedNameSpecifier(),
11571 &II);
11572
11574 // FXIME: Missing support for UsingShadowDecl on this path?
11575 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11576 // C++ [class.qual]p2:
11577 // In a lookup in which function names are not ignored and the
11578 // nested-name-specifier nominates a class C, if the name specified
11579 // after the nested-name-specifier, when looked up in C, is the
11580 // injected-class-name of C [...] then the name is instead considered
11581 // to name the constructor of class C.
11582 //
11583 // Unlike in an elaborated-type-specifier, function names are not ignored
11584 // in typename-specifier lookup. However, they are ignored in all the
11585 // contexts where we form a typename type with no keyword (that is, in
11586 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11587 //
11588 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11589 // ignore functions, but that appears to be an oversight.
11594 Type, IILoc);
11595 // FIXME: This appears to be the only case where a template type parameter
11596 // can have an elaborated keyword. We should preserve it somehow.
11599 assert(!QualifierLoc);
11601 }
11602 return Context.getTypeDeclType(
11603 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11604 }
11605
11606 // C++ [dcl.type.simple]p2:
11607 // A type-specifier of the form
11608 // typename[opt] nested-name-specifier[opt] template-name
11609 // is a placeholder for a deduced class type [...].
11610 if (getLangOpts().CPlusPlus17) {
11611 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11612 if (!DeducedTSTContext) {
11613 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11614 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11615 Diag(IILoc, diag::err_dependent_deduced_tst)
11617 << QualType(Qualifier.getAsType(), 0);
11618 else
11619 Diag(IILoc, diag::err_deduced_tst)
11622 return QualType();
11623 }
11624 TemplateName Name = Context.getQualifiedTemplateName(
11625 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11626 TemplateName(TD));
11627 return Context.getDeducedTemplateSpecializationType(
11628 DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11629 Name);
11630 }
11631 }
11632
11633 DiagID = Ctx ? diag::err_typename_nested_not_type
11634 : diag::err_typename_not_type;
11635 Referenced = Result.getFoundDecl();
11636 break;
11637
11639 DiagID = Ctx ? diag::err_typename_nested_not_type
11640 : diag::err_typename_not_type;
11641 Referenced = *Result.begin();
11642 break;
11643
11645 return QualType();
11646 }
11647
11648 // If we get here, it's because name lookup did not find a
11649 // type. Emit an appropriate diagnostic and return an error.
11650 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11651 IILoc);
11652 if (Ctx)
11653 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11654 else
11655 Diag(IILoc, DiagID) << FullRange << Name;
11656 if (Referenced)
11657 Diag(Referenced->getLocation(),
11658 Ctx ? diag::note_typename_member_refers_here
11659 : diag::note_typename_refers_here)
11660 << Name;
11661 return QualType();
11662}
11663
11664namespace {
11665 // See Sema::RebuildTypeInCurrentInstantiation
11666 class CurrentInstantiationRebuilder
11667 : public TreeTransform<CurrentInstantiationRebuilder> {
11668 SourceLocation Loc;
11669 DeclarationName Entity;
11670
11671 public:
11673
11674 CurrentInstantiationRebuilder(Sema &SemaRef,
11675 SourceLocation Loc,
11676 DeclarationName Entity)
11677 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11678 Loc(Loc), Entity(Entity) { }
11679
11680 /// Determine whether the given type \p T has already been
11681 /// transformed.
11682 ///
11683 /// For the purposes of type reconstruction, a type has already been
11684 /// transformed if it is NULL or if it is not dependent.
11685 bool AlreadyTransformed(QualType T) {
11686 return T.isNull() || !T->isInstantiationDependentType();
11687 }
11688
11689 /// Returns the location of the entity whose type is being
11690 /// rebuilt.
11691 SourceLocation getBaseLocation() { return Loc; }
11692
11693 /// Returns the name of the entity whose type is being rebuilt.
11694 DeclarationName getBaseEntity() { return Entity; }
11695
11696 /// Sets the "base" location and entity when that
11697 /// information is known based on another transformation.
11698 void setBase(SourceLocation Loc, DeclarationName Entity) {
11699 this->Loc = Loc;
11700 this->Entity = Entity;
11701 }
11702
11703 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11704 // Lambdas never need to be transformed.
11705 return E;
11706 }
11707 };
11708} // end anonymous namespace
11709
11711 SourceLocation Loc,
11712 DeclarationName Name) {
11713 if (!T || !T->getType()->isInstantiationDependentType())
11714 return T;
11715
11716 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11717 return Rebuilder.TransformType(T);
11718}
11719
11721 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11722 DeclarationName());
11723 return Rebuilder.TransformExpr(E);
11724}
11725
11727 if (SS.isInvalid())
11728 return true;
11729
11731 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11732 DeclarationName());
11734 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11735 if (!Rebuilt)
11736 return true;
11737
11738 SS.Adopt(Rebuilt);
11739 return false;
11740}
11741
11743 TemplateParameterList *Params) {
11744 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11745 Decl *Param = Params->getParam(I);
11746
11747 // There is nothing to rebuild in a type parameter.
11748 if (isa<TemplateTypeParmDecl>(Param))
11749 continue;
11750
11751 // Rebuild the template parameter list of a template template parameter.
11753 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11755 TTP->getTemplateParameters()))
11756 return true;
11757
11758 continue;
11759 }
11760
11761 // Rebuild the type of a non-type template parameter.
11763 TypeSourceInfo *NewTSI
11765 NTTP->getLocation(),
11766 NTTP->getDeclName());
11767 if (!NewTSI)
11768 return true;
11769
11770 if (NewTSI->getType()->isUndeducedType()) {
11771 // C++17 [temp.dep.expr]p3:
11772 // An id-expression is type-dependent if it contains
11773 // - an identifier associated by name lookup with a non-type
11774 // template-parameter declared with a type that contains a
11775 // placeholder type (7.1.7.4),
11776 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11777 }
11778
11779 if (NewTSI != NTTP->getTypeSourceInfo()) {
11780 NTTP->setTypeSourceInfo(NewTSI);
11781 NTTP->setType(NewTSI->getType());
11782 }
11783 }
11784
11785 return false;
11786}
11787
11788std::string
11790 const TemplateArgumentList &Args) {
11791 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11792}
11793
11794std::string
11796 const TemplateArgument *Args,
11797 unsigned NumArgs) {
11798 SmallString<128> Str;
11799 llvm::raw_svector_ostream Out(Str);
11800
11801 if (!Params || Params->size() == 0 || NumArgs == 0)
11802 return std::string();
11803
11804 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11805 if (I >= NumArgs)
11806 break;
11807
11808 if (I == 0)
11809 Out << "[with ";
11810 else
11811 Out << ", ";
11812
11813 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11814 Out << Id->getName();
11815 } else {
11816 Out << '$' << I;
11817 }
11818
11819 Out << " = ";
11820 Args[I].print(getPrintingPolicy(), Out,
11822 getPrintingPolicy(), Params, I));
11823 }
11824
11825 Out << ']';
11826 return std::string(Out.str());
11827}
11828
11830 CachedTokens &Toks) {
11831 if (!FD)
11832 return;
11833
11834 auto LPT = std::make_unique<LateParsedTemplate>();
11835
11836 // Take tokens to avoid allocations
11837 LPT->Toks.swap(Toks);
11838 LPT->D = FnD;
11839 LPT->FPO = getCurFPFeatures();
11840 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11841
11842 FD->setLateTemplateParsed(true);
11843}
11844
11846 if (!FD)
11847 return;
11848 FD->setLateTemplateParsed(false);
11849}
11850
11852 DeclContext *DC = CurContext;
11853
11854 while (DC) {
11855 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11856 const FunctionDecl *FD = RD->isLocalClass();
11857 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11858 } else if (DC->isTranslationUnit() || DC->isNamespace())
11859 return false;
11860
11861 DC = DC->getParent();
11862 }
11863 return false;
11864}
11865
11866namespace {
11867/// Walk the path from which a declaration was instantiated, and check
11868/// that every explicit specialization along that path is visible. This enforces
11869/// C++ [temp.expl.spec]/6:
11870///
11871/// If a template, a member template or a member of a class template is
11872/// explicitly specialized then that specialization shall be declared before
11873/// the first use of that specialization that would cause an implicit
11874/// instantiation to take place, in every translation unit in which such a
11875/// use occurs; no diagnostic is required.
11876///
11877/// and also C++ [temp.class.spec]/1:
11878///
11879/// A partial specialization shall be declared before the first use of a
11880/// class template specialization that would make use of the partial
11881/// specialization as the result of an implicit or explicit instantiation
11882/// in every translation unit in which such a use occurs; no diagnostic is
11883/// required.
11884class ExplicitSpecializationVisibilityChecker {
11885 Sema &S;
11886 SourceLocation Loc;
11889
11890public:
11891 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11893 : S(S), Loc(Loc), Kind(Kind) {}
11894
11895 void check(NamedDecl *ND) {
11896 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11897 return checkImpl(FD);
11898 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11899 return checkImpl(RD);
11900 if (auto *VD = dyn_cast<VarDecl>(ND))
11901 return checkImpl(VD);
11902 if (auto *ED = dyn_cast<EnumDecl>(ND))
11903 return checkImpl(ED);
11904 }
11905
11906private:
11907 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11908 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11909 : Sema::MissingImportKind::ExplicitSpecialization;
11910 const bool Recover = true;
11911
11912 // If we got a custom set of modules (because only a subset of the
11913 // declarations are interesting), use them, otherwise let
11914 // diagnoseMissingImport intelligently pick some.
11915 if (Modules.empty())
11916 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11917 else
11918 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11919 }
11920
11921 bool CheckMemberSpecialization(const NamedDecl *D) {
11922 return Kind == Sema::AcceptableKind::Visible
11925 }
11926
11927 bool CheckExplicitSpecialization(const NamedDecl *D) {
11928 return Kind == Sema::AcceptableKind::Visible
11931 }
11932
11933 bool CheckDeclaration(const NamedDecl *D) {
11934 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11936 }
11937
11938 // Check a specific declaration. There are three problematic cases:
11939 //
11940 // 1) The declaration is an explicit specialization of a template
11941 // specialization.
11942 // 2) The declaration is an explicit specialization of a member of an
11943 // templated class.
11944 // 3) The declaration is an instantiation of a template, and that template
11945 // is an explicit specialization of a member of a templated class.
11946 //
11947 // We don't need to go any deeper than that, as the instantiation of the
11948 // surrounding class / etc is not triggered by whatever triggered this
11949 // instantiation, and thus should be checked elsewhere.
11950 template<typename SpecDecl>
11951 void checkImpl(SpecDecl *Spec) {
11952 bool IsHiddenExplicitSpecialization = false;
11953 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11954 // Some invalid friend declarations are written as specializations but are
11955 // instantiated implicitly.
11956 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11957 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11958 if (SpecKind == TSK_ExplicitSpecialization) {
11959 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11960 ? !CheckMemberSpecialization(Spec)
11961 : !CheckExplicitSpecialization(Spec);
11962 } else {
11963 checkInstantiated(Spec);
11964 }
11965
11966 if (IsHiddenExplicitSpecialization)
11967 diagnose(Spec->getMostRecentDecl(), false);
11968 }
11969
11970 void checkInstantiated(FunctionDecl *FD) {
11971 if (auto *TD = FD->getPrimaryTemplate())
11972 checkTemplate(TD);
11973 }
11974
11975 void checkInstantiated(CXXRecordDecl *RD) {
11976 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11977 if (!SD)
11978 return;
11979
11980 auto From = SD->getSpecializedTemplateOrPartial();
11981 if (auto *TD = dyn_cast<ClassTemplateDecl *>(From))
11982 checkTemplate(TD);
11983 else if (auto *TD =
11984 dyn_cast<ClassTemplatePartialSpecializationDecl *>(From)) {
11985 if (!CheckDeclaration(TD))
11986 diagnose(TD, true);
11987 checkTemplate(TD);
11988 }
11989 }
11990
11991 void checkInstantiated(VarDecl *RD) {
11992 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11993 if (!SD)
11994 return;
11995
11996 auto From = SD->getSpecializedTemplateOrPartial();
11997 if (auto *TD = dyn_cast<VarTemplateDecl *>(From))
11998 checkTemplate(TD);
11999 else if (auto *TD =
12000 dyn_cast<VarTemplatePartialSpecializationDecl *>(From)) {
12001 if (!CheckDeclaration(TD))
12002 diagnose(TD, true);
12003 checkTemplate(TD);
12004 }
12005 }
12006
12007 void checkInstantiated(EnumDecl *FD) {}
12008
12009 template<typename TemplDecl>
12010 void checkTemplate(TemplDecl *TD) {
12011 if (TD->isMemberSpecialization()) {
12012 if (!CheckMemberSpecialization(TD))
12013 diagnose(TD->getMostRecentDecl(), false);
12014 }
12015 }
12016};
12017} // end anonymous namespace
12018
12020 if (!getLangOpts().Modules)
12021 return;
12022
12023 ExplicitSpecializationVisibilityChecker(*this, Loc,
12025 .check(Spec);
12026}
12027
12029 NamedDecl *Spec) {
12030 if (!getLangOpts().CPlusPlusModules)
12031 return checkSpecializationVisibility(Loc, Spec);
12032
12033 ExplicitSpecializationVisibilityChecker(*this, Loc,
12035 .check(Spec);
12036}
12037
12040 return N->getLocation();
12041 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12043 return FD->getLocation();
12046 return N->getLocation();
12047 }
12048 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12049 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12050 continue;
12051 return CSC.PointOfInstantiation;
12052 }
12053 return N->getLocation();
12054}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static void addExplicitInstantiationDecl(ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
Create an ExplicitInstantiationDecl to record source-location info for an explicit template instantia...
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static ExprResult BuildExpressionFromReflection(Sema &S, const APValue &RV, SourceLocation CaretCaretLoc)
Construct a new reflect expression that refers to the given entity with the given source-location of ...
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 QualType sortBuiltinTemplatePack(ASTContext &Context, ArrayRef< TemplateArgument > InputArgs)
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 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 void diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D)
Diagnose a missing template argument.
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, bool IsSpecified, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
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:158
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
const void * getReflectionOpaqueOperand() const
Definition APValue.h:787
APSInt & getInt()
Definition APValue.h:573
APSInt & getComplexIntImag()
Definition APValue.h:611
ValueKind getKind() const
Definition APValue.h:537
APFixedPoint & getFixedPoint()
Definition APValue.h:595
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isMemberPointer() const
Definition APValue.h:560
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:1099
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition APValue.h:167
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isNullPointer() const
Definition APValue.cpp:1162
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
TranslationUnitDecl * getTranslationUnitDecl() const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
ArrayRef< ExplicitInstantiationDecl * > getExplicitInstantiationDecls(const NamedDecl *Spec) const
Get all ExplicitInstantiationDecls for a given specialization.
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
bool isUnset() const
Definition Ownership.h:168
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3990
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition Attr.h:46
AutoTypeKeyword getAutoKeyword() const
Definition TypeLoc.h:2424
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
TemplateName getNamedConcept() const
Definition TypeLoc.h:2466
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8304
Pointer to a block type.
Definition TypeBase.h:3653
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:3245
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:2141
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:740
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition ExprCXX.h:3924
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:1581
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:133
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition DeclCXX.cpp:2032
base_class_range bases()
Definition DeclCXX.h:609
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2062
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition DeclCXX.cpp:2058
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2039
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition DeclCXX.cpp:2073
CXXRecordDecl * getPreviousDecl()
Definition DeclCXX.h:531
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, const TypeSourceInfo *TSI)
Definition ExprCXX.cpp:1983
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
char * location_data() const
Retrieve the data associated with the source-location information.
Definition DeclSpec.h:209
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1073
static CanQual< Type > CreateUnsafe(QualType Other)
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
Declaration of a C++20 concept.
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateName NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1468
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2275
bool isFileContext() const
Definition DeclBase.h:2213
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:2235
bool isTranslationUnit() const
Definition DeclBase.h:2218
bool isRecord() const
Definition DeclBase.h:2222
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
void addDecl(Decl *D)
Add the declaration D into this context.
bool isStdNamespace() const
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2177
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:1294
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1395
ValueDecl * getDecl()
Definition Expr.h:1362
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isVirtualSpecified() const
Definition DeclSpec.h:658
void ClearStorageClassSpecs()
Definition DeclSpec.h:503
bool isNoreturnSpecified() const
Definition DeclSpec.h:671
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:498
SCS getStorageClassSpec() const
Definition DeclSpec.h:489
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:563
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:562
SourceLocation getNoreturnSpecLoc() const
Definition DeclSpec.h:672
SourceLocation getExplicitSpecLoc() const
Definition DeclSpec.h:664
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:490
ParsedAttributes & getAttributes()
Definition DeclSpec.h:883
bool isInlineSpecified() const
Definition DeclSpec.h:647
SourceLocation getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:499
SourceLocation getVirtualSpecLoc() const
Definition DeclSpec.h:659
SourceLocation getConstexprSpecLoc() const
Definition DeclSpec.h:846
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:650
bool hasExplicitSpecifier() const
Definition DeclSpec.h:661
bool hasConstexprSpecifier() const
Definition DeclSpec.h:847
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:1080
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1245
T * getAttr() const
Definition DeclBase.h:583
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
@ FOK_None
Not a friend object.
Definition DeclBase.h:1236
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:856
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition DeclBase.h:826
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:1199
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition DeclBase.h:2831
bool isInvalidDecl() const
Definition DeclBase.h:598
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:512
SourceLocation getLocation() const
Definition DeclBase.h:449
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition DeclBase.cpp:256
DeclContext * getDeclContext()
Definition DeclBase.h:458
AccessSpecifier getAccess() const
Definition DeclBase.h:517
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:441
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:937
bool hasAttr() const
Definition DeclBase.h:587
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:997
Kind getKind() const
Definition DeclBase.h:452
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:437
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:815
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:838
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1955
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2102
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2391
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2781
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2138
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2121
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2117
bool hasEllipsis() const
Definition DeclSpec.h:2780
bool isInvalidType() const
Definition DeclSpec.h:2769
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2137
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2109
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2385
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4159
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2632
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:2612
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:2621
A qualified reference to a name whose declaration cannot yet be resolved.
Definition ExprCXX.h:3564
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:574
Represents an array type in C++ whose size is a value-dependent expression.
Definition TypeBase.h:4109
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4199
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4582
static DependentTemplateIdExpr * Create(const ASTContext &Context, const DeclarationNameInfo &NameInfo, TemplateName Name, const TemplateArgumentListInfo &TemplateArgs)
Definition ExprCXX.cpp:423
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3510
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4325
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4150
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4422
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5233
static ExplicitInstantiationDecl * Create(ASTContext &C, DeclContext *DC, NamedDecl *Specialization, SourceLocation ExternLoc, SourceLocation TemplateLoc, NestedNameSpecifierLoc QualifierLoc, const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc, TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK)
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:851
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:3109
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:4110
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4365
Represents a member of a struct/union/class.
Definition Decl.h:3299
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1007
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition DeclFriend.h:46
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend, SourceLocation FriendL, SourceLocation EllipsisLoc={})
Represents a function declaration or definition.
Definition Decl.h:2059
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2603
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4252
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition Decl.cpp:4581
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4360
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4219
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3792
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2667
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4191
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:4425
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition Decl.h:2489
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition Decl.cpp:4464
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition Decl.cpp:3159
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4212
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4994
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
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:4952
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:3901
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition TypeBase.h:4007
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
Describes an C or C++ initializer list.
Definition Expr.h:5356
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:985
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3715
Represents a linkage specification.
Definition DeclCXX.h:3045
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition Lookup.h:318
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
A global _GUID constant.
Definition DeclCXX.h:4451
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
QualType getPointeeType() const
Definition TypeBase.h:3769
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:241
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
NamedDecl * getMostRecentDecl()
Definition Decl.h:502
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:720
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1944
Represent a C++ namespace.
Definition Decl.h:593
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8031
Represents a pointer to an Objective C object.
Definition TypeBase.h:8087
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:1202
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1164
@ CSK_Normal
Normal lookup.
Definition Overload.h:1168
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1380
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:1431
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:4417
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2664
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2230
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:8275
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8535
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3827
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
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:8631
QualType getCanonicalType() const
Definition TypeBase.h:8498
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8540
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition Type.cpp:3820
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
Callback class to reject typo corrections that look like template parameters when doing a qualified l...
bool ValidateCandidate(const TypoCorrection &Candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
QualifiedLookupValidatorCCC(bool HasQualifier)
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3733
Represents a struct/union/class.
Definition Decl.h:4464
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4648
void setMemberSpecialization()
Note that this member template is a specialization.
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition Decl.h:5472
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
QualType getPointeeType() const
Definition TypeBase.h:3700
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:348
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition Scope.h:467
Scope * getDeclParent()
Definition Scope.h:321
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
Scope * getTemplateParamParent()
Definition Scope.h:318
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13889
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8599
A RAII object to temporarily push a declaration context.
Definition Sema.h:3627
Whether and why a template name is required in this lookup.
Definition Sema.h:11615
SourceLocation getTemplateKeywordLoc() const
Definition Sema.h:11623
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12673
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12707
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7869
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13836
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13287
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition Sema.cpp:2711
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9490
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9494
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9502
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9497
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:9806
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:1499
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition SemaAttr.cpp:54
@ Default
= default ;
Definition Sema.h:4310
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:2107
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:11586
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition Sema.h:12184
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12187
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12191
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition Sema.h:1332
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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...
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:935
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:778
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, bool DoCheckConstraintSatisfaction=true)
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1236
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition Sema.h:12363
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition Sema.h:12381
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12371
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12391
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:11636
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
Definition Sema.h:11643
@ None
This is not assumed to be a template name.
Definition Sema.h:11638
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
Definition Sema.h:11640
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:11572
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition SemaAttr.cpp:170
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition Sema.h:930
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition Sema.h:14683
@ UPPC_DefaultArgument
A default argument.
Definition Sema.h:14671
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition Sema.h:14680
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition Sema.h:14674
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14698
const LangOptions & getLangOpts() const
Definition Sema.h:928
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition Sema.h:1331
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:1330
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
ProcessDeclAttributeList - Apply all the decl attributes in the specified attribute list to the speci...
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true, bool AllowNonTemplateFunctions=false)
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
bool hasExplicitCallingConv(QualType T)
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool DiagnosePackIndexingInFriendNNS(SourceLocation Loc, NestedNameSpecifierLoc NNSLoc)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:648
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:1472
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
ExprResult CheckVarOrConceptTemplateTemplateId(const DeclarationNameInfo &NameInfo, TemplateName Template, const TemplateArgumentListInfo *TemplateArgs)
ExprResult BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index, QualType ParamType, SourceLocation loc, TemplateArgument Replacement, UnsignedOrNone PackIndex, bool Final)
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool isSFINAEContext() const
Definition Sema.h:13927
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:15733
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.
bool isRedefinitionAllowedFor(NamedDecl *D, SourceLocation NewDefinitionLoc, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ASTConsumer & Consumer
Definition Sema.h:1333
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:4823
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:6872
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6851
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, OffsetOfKind OOK, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
bool inParameterMappingSubstitution() const
Definition Sema.h:14194
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.
static QualType getTypeOfConstantTemplateParameter(const TemplateArgument &Arg)
Determine the declared type of the constant template parameter that Arg names, if any.
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:11613
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:524
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:11796
@ TPC_TemplateTemplateParameterPack
Definition Sema.h:11806
@ TPC_FriendFunctionTemplate
Definition Sema.h:11804
@ TPC_ClassTemplateMember
Definition Sema.h:11802
@ TPC_FunctionTemplate
Definition Sema.h:11801
@ TPC_FriendClassTemplate
Definition Sema.h:11803
@ TPC_FriendFunctionTemplateDefinition
Definition Sema.h:11805
friend class InitializationSequence
Definition Sema.h:1614
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool AllowTypoCorrection=true)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
bool isTagRedeclarationInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
Determine whether a tag-like declaration found by lookup can be redeclared in the given scope.
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:6475
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, bool IsMemberSpecialization, SkipBodyInfo *SkipBody=nullptr)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6559
OpaquePtr< TemplateName > TemplateTy
Definition Sema.h:1324
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition Sema.h:3620
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition Sema.h:11578
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:148
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:9815
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:13130
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition SemaAttr.cpp:365
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8812
SFINAETrap * getSFINAEContext() const
Returns a pointer to the current SFINAE context, if any.
Definition Sema.h:13924
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4718
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3856
StringRef getKindName() const
Definition Decl.h:4052
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4985
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition Decl.cpp:5121
TagKind getTagKind() const
Definition Decl.h:4056
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...
TemplateTemplateParmDecl * getAsTemplateTemplateParmDecl() const
Retrieve the template template parameter that this template name refers to, if any.
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:653
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition Decl.h:3827
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Represents a declaration of a type.
Definition Decl.h:3652
const Type * getTypeForDecl() const
Definition Decl.h:3677
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3686
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:893
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:6326
A container of type source information.
Definition TypeBase.h:8417
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8428
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBooleanType() const
Definition TypeBase.h:9209
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2483
bool isRValueReferenceType() const
Definition TypeBase.h:8715
bool isVoidPointerType() const
Definition Type.cpp:845
bool isArrayType() const
Definition TypeBase.h:8782
bool isPointerType() const
Definition TypeBase.h:8683
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isEnumeralType() const
Definition TypeBase.h:8814
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2282
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:595
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8870
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isLValueReferenceType() const
Definition TypeBase.h:8711
bool isBitIntType() const
Definition TypeBase.h:8958
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8806
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2235
bool isMemberPointerType() const
Definition TypeBase.h:8764
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9215
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:5207
bool isPointerOrReferenceType() const
Definition TypeBase.h:8687
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isFunctionType() const
Definition TypeBase.h:8679
bool isVectorType() const
Definition TypeBase.h:8822
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isNullPtrType() const
Definition TypeBase.h:9109
bool isRecordType() const
Definition TypeBase.h:8810
QualType getUnderlyingType() const
Definition Decl.h:3756
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
QualType desugar() const
Definition Type.cpp:4377
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:2292
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1042
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition DeclSpec.h:1074
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1254
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1251
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1070
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1124
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1094
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3373
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:464
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition TypeLoc.h:782
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition TypeBase.h:6131
Represents a dependent using declaration which was not marked with typename.
Definition DeclCXX.h:3970
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition DeclCXX.h:3493
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
TLSKind getTLSKind() const
Definition Decl.cpp:2148
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2747
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:2880
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:2775
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:2754
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2873
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4273
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD)
Set the diagnostic which caused the SFINAE failure.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
const PartialDiagnosticAt & peekSFINAEDiagnostic() const
Peek at the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition SPIR.cpp:35
Definition SPIR.cpp:47
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
TypeSpecifierType
Specifies the kind of type.
Definition Specifiers.h:56
ImplicitTypenameContext
Definition DeclSpec.h:1938
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
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
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1843
@ 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:924
@ 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:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition Sema.h:598
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1034
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1026
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1020
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1022
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition Specifiers.h:127
@ AS_public
Definition Specifiers.h:128
@ AS_none
Definition Specifiers.h:131
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:252
@ SC_Extern
Definition Specifiers.h:255
@ TSCS_unspecified
Definition Specifiers.h:240
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)
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:909
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
TagUseKind
Definition Sema.h:445
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6039
@ Enum
The "enum" keyword.
Definition TypeBase.h:6053
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:556
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
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:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:148
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
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:374
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:192
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:210
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:198
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
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:1259
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:835
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:836
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
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:6014
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6035
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6032
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
CharacterLiteralKind
Definition Expr.h:1627
#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:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:625
Extra information about a function prototype.
Definition TypeBase.h:5501
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition Type.cpp:3520
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition Type.cpp:3537
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition Type.cpp:3502
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:937
Describes how types, statements, expressions, and declarations should be printed.
unsigned TerseOutput
Provide a 'terse' output.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12222
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12218
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12211
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12208
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12208
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13338
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13442
A stack object to be created when performing template instantiation.
Definition Sema.h:13532
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13685
NamedDecl * Previous
Definition Sema.h:361
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:1053