clang 22.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/Type.h"
30#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/Overload.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/SemaCUDA.h"
39#include "clang/Sema/Template.h"
41#include "llvm/ADT/SmallBitVector.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/SaveAndRestore.h"
45
46#include <optional>
47using namespace clang;
48using namespace sema;
49
50// Exported for use by Parser.
53 unsigned N) {
54 if (!N) return SourceRange();
55 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56}
57
58unsigned Sema::getTemplateDepth(Scope *S) const {
59 unsigned Depth = 0;
60
61 // Each template parameter scope represents one level of template parameter
62 // depth.
63 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65 ++Depth;
66 }
67
68 // Note that there are template parameters with the given depth.
69 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70
71 // Look for parameters of an enclosing generic lambda. We don't create a
72 // template parameter scope for these.
74 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75 if (!LSI->TemplateParams.empty()) {
76 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77 break;
78 }
79 if (LSI->GLTemplateParameterList) {
80 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81 break;
82 }
83 }
84 }
85
86 // Look for parameters of an enclosing terse function template. We don't
87 // create a template parameter scope for these either.
88 for (const InventedTemplateParameterInfo &Info :
90 if (!Info.TemplateParams.empty()) {
91 ParamsAtDepth(Info.AutoTemplateParameterDepth);
92 break;
93 }
94 }
95
96 return Depth;
97}
98
99/// \brief Determine whether the declaration found is acceptable as the name
100/// of a template and, if so, return that template declaration. Otherwise,
101/// returns null.
102///
103/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104/// is true. In all other cases it will return a TemplateDecl (or null).
106 bool AllowFunctionTemplates,
107 bool AllowDependent) {
108 D = D->getUnderlyingDecl();
109
110 if (isa<TemplateDecl>(D)) {
111 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112 return nullptr;
113
114 return D;
115 }
116
117 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118 // C++ [temp.local]p1:
119 // Like normal (non-template) classes, class templates have an
120 // injected-class-name (Clause 9). The injected-class-name
121 // can be used with or without a template-argument-list. When
122 // it is used without a template-argument-list, it is
123 // equivalent to the injected-class-name followed by the
124 // template-parameters of the class template enclosed in
125 // <>. When it is used with a template-argument-list, it
126 // refers to the specified class template specialization,
127 // which could be the current specialization or another
128 // specialization.
129 if (Record->isInjectedClassName()) {
130 Record = cast<CXXRecordDecl>(Record->getDeclContext());
131 if (Record->getDescribedClassTemplate())
132 return Record->getDescribedClassTemplate();
133
134 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135 return Spec->getSpecializedTemplate();
136 }
137
138 return nullptr;
139 }
140
141 // 'using Dependent::foo;' can resolve to a template name.
142 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143 // injected-class-name).
144 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145 return D;
146
147 return nullptr;
148}
149
151 bool AllowFunctionTemplates,
152 bool AllowDependent) {
153 LookupResult::Filter filter = R.makeFilter();
154 while (filter.hasNext()) {
155 NamedDecl *Orig = filter.next();
156 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157 filter.erase();
158 }
159 filter.done();
160}
161
163 bool AllowFunctionTemplates,
164 bool AllowDependent,
165 bool AllowNonTemplateFunctions) {
166 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168 return true;
169 if (AllowNonTemplateFunctions &&
170 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171 return true;
172 }
173
174 return false;
175}
176
178 CXXScopeSpec &SS,
179 bool hasTemplateKeyword,
180 const UnqualifiedId &Name,
181 ParsedType ObjectTypePtr,
182 bool EnteringContext,
183 TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool Disambiguation) {
186 assert(getLangOpts().CPlusPlus && "No template names in C!");
187
188 DeclarationName TName;
189 MemberOfUnknownSpecialization = false;
190
191 switch (Name.getKind()) {
193 TName = DeclarationName(Name.Identifier);
194 break;
195
198 Name.OperatorFunctionId.Operator);
199 break;
200
202 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203 break;
204
205 default:
206 return TNK_Non_template;
207 }
208
209 QualType ObjectType = ObjectTypePtr.get();
210
211 AssumedTemplateKind AssumedTemplate;
212 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214 /*RequiredTemplate=*/SourceLocation(),
215 &AssumedTemplate,
216 /*AllowTypoCorrection=*/!Disambiguation))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
280 } else {
281 if (!D) {
283 assert(D && "unambiguous result is not a template name");
284 }
285
286 if (isa<UnresolvedUsingValueDecl>(D)) {
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
292 TemplateDecl *TD = cast<TemplateDecl>(D);
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
302 if (isa<FunctionTemplateDecl>(TD)) {
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
307 } else {
308 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311 TemplateKind =
312 isa<TemplateTemplateParmDecl>(TD)
313 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()
314 : isa<VarTemplateDecl>(TD) ? TNK_Var_template
315 : isa<ConceptDecl>(TD) ? TNK_Concept_template
317 }
318 }
319
321 S->getTemplateParamParent() == nullptr)
322 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(Template);
327 return TemplateKind;
328}
329
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
351 if (!TD || !getAsTypeTemplateDecl(TD))
352 return false;
353
354 if (Template) {
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.
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>()
413 "Caller should have completed object type");
414
415 // Template names cannot appear inside an Objective-C class or object type
416 // or a vector type.
417 //
418 // FIXME: This is wrong. For example:
419 //
420 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
421 // Vec<int> vi;
422 // vi.Vec<int>::~Vec<int>();
423 //
424 // ... should be accepted but we will not treat 'Vec' as a template name
425 // here. The right thing to do would be to check if the name is a valid
426 // vector component name, and look up a template name if not. And similarly
427 // for lookups into Objective-C class and object types, where the same
428 // problem can arise.
429 if (ObjectType->isObjCObjectOrInterfaceType() ||
430 ObjectType->isVectorType()) {
431 Found.clear();
432 return false;
433 }
434 } else if (SS.isNotEmpty()) {
435 // This nested-name-specifier occurs after another nested-name-specifier,
436 // so long into the context associated with the prior nested-name-specifier.
437 LookupCtx = computeDeclContext(SS, EnteringContext);
438 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
439
440 // The declaration context must be complete.
441 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
442 return true;
443 }
444
445 bool ObjectTypeSearchedInScope = false;
446 bool AllowFunctionTemplatesInLookup = true;
447 if (LookupCtx) {
448 // Perform "qualified" name lookup into the declaration context we
449 // computed, which is either the type of the base of a member access
450 // expression or the declaration context associated with a prior
451 // nested-name-specifier.
452 LookupQualifiedName(Found, LookupCtx);
453
454 // FIXME: The C++ standard does not clearly specify what happens in the
455 // case where the object type is dependent, and implementations vary. In
456 // Clang, we treat a name after a . or -> as a template-name if lookup
457 // finds a non-dependent member or member of the current instantiation that
458 // is a type template, or finds no such members and lookup in the context
459 // of the postfix-expression finds a type template. In the latter case, the
460 // name is nonetheless dependent, and we may resolve it to a member of an
461 // unknown specialization when we come to instantiate the template.
462 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
463 }
464
465 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
466 // C++ [basic.lookup.classref]p1:
467 // In a class member access expression (5.2.5), if the . or -> token is
468 // immediately followed by an identifier followed by a <, the
469 // identifier must be looked up to determine whether the < is the
470 // beginning of a template argument list (14.2) or a less-than operator.
471 // The identifier is first looked up in the class of the object
472 // expression. If the identifier is not found, it is then looked up in
473 // the context of the entire postfix-expression and shall name a class
474 // template.
475 if (S)
476 LookupName(Found, S);
477
478 if (!ObjectType.isNull()) {
479 // FIXME: We should filter out all non-type templates here, particularly
480 // variable templates and concepts. But the exclusion of alias templates
481 // and template template parameters is a wording defect.
482 AllowFunctionTemplatesInLookup = false;
483 ObjectTypeSearchedInScope = true;
484 }
485
486 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
487 }
488
489 if (Found.isAmbiguous())
490 return false;
491
492 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
493 !RequiredTemplate.hasTemplateKeyword()) {
494 // C++2a [temp.names]p2:
495 // A name is also considered to refer to a template if it is an
496 // unqualified-id followed by a < and name lookup finds either one or more
497 // functions or finds nothing.
498 //
499 // To keep our behavior consistent, we apply the "finds nothing" part in
500 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
501 // successfully form a call to an undeclared template-id.
502 bool AllFunctions =
503 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
504 return isa<FunctionDecl>(ND->getUnderlyingDecl());
505 });
506 if (AllFunctions || (Found.empty() && !IsDependent)) {
507 // If lookup found any functions, or if this is a name that can only be
508 // used for a function, then strongly assume this is a function
509 // template-id.
510 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
513 Found.clear();
514 return false;
515 }
516 }
517
518 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
519 // If we did not find any names, and this is not a disambiguation, attempt
520 // to correct any typos.
521 DeclarationName Name = Found.getLookupName();
522 Found.clear();
523 // Simple filter callback that, for keywords, only accepts the C++ *_cast
524 DefaultFilterCCC FilterCCC{};
525 FilterCCC.WantTypeSpecifiers = false;
526 FilterCCC.WantExpressionKeywords = false;
527 FilterCCC.WantRemainingKeywords = false;
528 FilterCCC.WantCXXNamedCasts = true;
529 if (TypoCorrection Corrected = CorrectTypo(
530 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,
531 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
532 if (auto *ND = Corrected.getFoundDecl())
533 Found.addDecl(ND);
535 if (Found.isAmbiguous()) {
536 Found.clear();
537 } else if (!Found.empty()) {
538 // Do not erase the typo-corrected result to avoid duplicated
539 // diagnostics.
540 AllowFunctionTemplatesInLookup = true;
541 Found.setLookupName(Corrected.getCorrection());
542 if (LookupCtx) {
543 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
544 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
545 Name.getAsString() == CorrectedStr;
546 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
547 << Name << LookupCtx << DroppedSpecifier
548 << SS.getRange());
549 } else {
550 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
551 }
552 }
553 }
554 }
555
556 NamedDecl *ExampleLookupResult =
557 Found.empty() ? nullptr : Found.getRepresentativeDecl();
558 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
559 if (Found.empty()) {
560 if (IsDependent) {
561 Found.setNotFoundInCurrentInstantiation();
562 return false;
563 }
564
565 // If a 'template' keyword was used, a lookup that finds only non-template
566 // names is an error.
567 if (ExampleLookupResult && RequiredTemplate) {
568 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
569 << Found.getLookupName() << SS.getRange()
570 << RequiredTemplate.hasTemplateKeyword()
571 << RequiredTemplate.getTemplateKeywordLoc();
572 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
573 diag::note_template_kw_refers_to_non_template)
574 << Found.getLookupName();
575 return true;
576 }
577
578 return false;
579 }
580
581 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
583 // C++03 [basic.lookup.classref]p1:
584 // [...] If the lookup in the class of the object expression finds a
585 // template, the name is also looked up in the context of the entire
586 // postfix-expression and [...]
587 //
588 // Note: C++11 does not perform this second lookup.
589 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
591 FoundOuter.setTemplateNameLookup(true);
592 LookupName(FoundOuter, S);
593 // FIXME: We silently accept an ambiguous lookup here, in violation of
594 // [basic.lookup]/1.
595 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
596
597 NamedDecl *OuterTemplate;
598 if (FoundOuter.empty()) {
599 // - if the name is not found, the name found in the class of the
600 // object expression is used, otherwise
601 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
602 !(OuterTemplate =
603 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
604 // - if the name is found in the context of the entire
605 // postfix-expression and does not name a class template, the name
606 // found in the class of the object expression is used, otherwise
607 FoundOuter.clear();
608 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
609 // - if the name found is a class template, it must refer to the same
610 // entity as the one found in the class of the object expression,
611 // otherwise the program is ill-formed.
612 if (!Found.isSingleResult() ||
613 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
614 OuterTemplate->getCanonicalDecl()) {
615 Diag(Found.getNameLoc(),
616 diag::ext_nested_name_member_ref_lookup_ambiguous)
617 << Found.getLookupName()
618 << ObjectType;
619 Diag(Found.getRepresentativeDecl()->getLocation(),
620 diag::note_ambig_member_ref_object_type)
621 << ObjectType;
622 Diag(FoundOuter.getFoundDecl()->getLocation(),
623 diag::note_ambig_member_ref_scope);
624
625 // Recover by taking the template that we found in the object
626 // expression's type.
627 }
628 }
629 }
630
631 return false;
632}
633
637 if (TemplateName.isInvalid())
638 return;
639
640 DeclarationNameInfo NameInfo;
641 CXXScopeSpec SS;
642 LookupNameKind LookupKind;
643
644 DeclContext *LookupCtx = nullptr;
645 NamedDecl *Found = nullptr;
646 bool MissingTemplateKeyword = false;
647
648 // Figure out what name we looked up.
649 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
650 NameInfo = DRE->getNameInfo();
651 SS.Adopt(DRE->getQualifierLoc());
652 LookupKind = LookupOrdinaryName;
653 Found = DRE->getFoundDecl();
654 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
655 NameInfo = ME->getMemberNameInfo();
656 SS.Adopt(ME->getQualifierLoc());
657 LookupKind = LookupMemberName;
658 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
659 Found = ME->getMemberDecl();
660 } else if (auto *DSDRE =
661 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
662 NameInfo = DSDRE->getNameInfo();
663 SS.Adopt(DSDRE->getQualifierLoc());
664 MissingTemplateKeyword = true;
665 } else if (auto *DSME =
666 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
667 NameInfo = DSME->getMemberNameInfo();
668 SS.Adopt(DSME->getQualifierLoc());
669 MissingTemplateKeyword = true;
670 } else {
671 llvm_unreachable("unexpected kind of potential template name");
672 }
673
674 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
675 // was missing.
676 if (MissingTemplateKeyword) {
677 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
678 << NameInfo.getName() << SourceRange(Less, Greater);
679 return;
680 }
681
682 // Try to correct the name by looking for templates and C++ named casts.
683 struct TemplateCandidateFilter : CorrectionCandidateCallback {
684 Sema &S;
685 TemplateCandidateFilter(Sema &S) : S(S) {
686 WantTypeSpecifiers = false;
687 WantExpressionKeywords = false;
688 WantRemainingKeywords = false;
689 WantCXXNamedCasts = true;
690 };
691 bool ValidateCandidate(const TypoCorrection &Candidate) override {
692 if (auto *ND = Candidate.getCorrectionDecl())
693 return S.getAsTemplateNameDecl(ND);
694 return Candidate.isKeyword();
695 }
696
697 std::unique_ptr<CorrectionCandidateCallback> clone() override {
698 return std::make_unique<TemplateCandidateFilter>(*this);
699 }
700 };
701
702 DeclarationName Name = NameInfo.getName();
703 TemplateCandidateFilter CCC(*this);
704 if (TypoCorrection Corrected =
705 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
706 CorrectTypoKind::ErrorRecovery, LookupCtx)) {
707 auto *ND = Corrected.getFoundDecl();
708 if (ND)
709 ND = getAsTemplateNameDecl(ND);
710 if (ND || Corrected.isKeyword()) {
711 if (LookupCtx) {
712 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
713 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
714 Name.getAsString() == CorrectedStr;
715 diagnoseTypo(Corrected,
716 PDiag(diag::err_non_template_in_member_template_id_suggest)
717 << Name << LookupCtx << DroppedSpecifier
718 << SS.getRange(), false);
719 } else {
720 diagnoseTypo(Corrected,
721 PDiag(diag::err_non_template_in_template_id_suggest)
722 << Name, false);
723 }
724 if (Found)
725 Diag(Found->getLocation(),
726 diag::note_non_template_in_template_id_found);
727 return;
728 }
729 }
730
731 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
732 << Name << SourceRange(Less, Greater);
733 if (Found)
734 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
735}
736
739 SourceLocation TemplateKWLoc,
740 const DeclarationNameInfo &NameInfo,
741 bool isAddressOfOperand,
742 const TemplateArgumentListInfo *TemplateArgs) {
743 if (SS.isEmpty()) {
744 // FIXME: This codepath is only used by dependent unqualified names
745 // (e.g. a dependent conversion-function-id, or operator= once we support
746 // it). It doesn't quite do the right thing, and it will silently fail if
747 // getCurrentThisType() returns null.
748 QualType ThisType = getCurrentThisType();
749 if (ThisType.isNull())
750 return ExprError();
751
753 Context, /*Base=*/nullptr, ThisType,
754 /*IsArrow=*/!Context.getLangOpts().HLSL,
755 /*OperatorLoc=*/SourceLocation(),
756 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
757 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
758 }
759 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
760}
761
764 SourceLocation TemplateKWLoc,
765 const DeclarationNameInfo &NameInfo,
766 const TemplateArgumentListInfo *TemplateArgs) {
767 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
768 if (!SS.isValid())
769 return CreateRecoveryExpr(
770 SS.getBeginLoc(),
771 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
772
774 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
775 TemplateArgs);
776}
777
779 NamedDecl *Instantiation,
780 bool InstantiatedFromMember,
781 const NamedDecl *Pattern,
782 const NamedDecl *PatternDef,
784 bool Complain, bool *Unreachable) {
785 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
786 isa<VarDecl>(Instantiation));
787
788 bool IsEntityBeingDefined = false;
789 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
790 IsEntityBeingDefined = TD->isBeingDefined();
791
792 if (PatternDef && !IsEntityBeingDefined) {
793 NamedDecl *SuggestedDef = nullptr;
794 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
795 &SuggestedDef,
796 /*OnlyNeedComplete*/ false)) {
797 if (Unreachable)
798 *Unreachable = true;
799 // If we're allowed to diagnose this and recover, do so.
800 bool Recover = Complain && !isSFINAEContext();
801 if (Complain)
802 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
804 return !Recover;
805 }
806 return false;
807 }
808
809 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
810 return true;
811
812 CanQualType InstantiationTy;
813 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
814 InstantiationTy = Context.getCanonicalTagType(TD);
815 if (PatternDef) {
816 Diag(PointOfInstantiation,
817 diag::err_template_instantiate_within_definition)
818 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
819 << InstantiationTy;
820 // Not much point in noting the template declaration here, since
821 // we're lexically inside it.
822 Instantiation->setInvalidDecl();
823 } else if (InstantiatedFromMember) {
824 if (isa<FunctionDecl>(Instantiation)) {
825 Diag(PointOfInstantiation,
826 diag::err_explicit_instantiation_undefined_member)
827 << /*member function*/ 1 << Instantiation->getDeclName()
828 << Instantiation->getDeclContext();
829 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
830 } else {
831 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
832 Diag(PointOfInstantiation,
833 diag::err_implicit_instantiate_member_undefined)
834 << InstantiationTy;
835 Diag(Pattern->getLocation(), diag::note_member_declared_at);
836 }
837 } else {
838 if (isa<FunctionDecl>(Instantiation)) {
839 Diag(PointOfInstantiation,
840 diag::err_explicit_instantiation_undefined_func_template)
841 << Pattern;
842 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
843 } else if (isa<TagDecl>(Instantiation)) {
844 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
845 << (TSK != TSK_ImplicitInstantiation)
846 << InstantiationTy;
847 NoteTemplateLocation(*Pattern);
848 } else {
849 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
850 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_var_template)
853 << Instantiation;
854 Instantiation->setInvalidDecl();
855 } else
856 Diag(PointOfInstantiation,
857 diag::err_explicit_instantiation_undefined_member)
858 << /*static data member*/ 2 << Instantiation->getDeclName()
859 << Instantiation->getDeclContext();
860 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
861 }
862 }
863
864 // In general, Instantiation isn't marked invalid to get more than one
865 // error for multiple undefined instantiations. But the code that does
866 // explicit declaration -> explicit definition conversion can't handle
867 // invalid declarations, so mark as invalid in that case.
869 Instantiation->setInvalidDecl();
870 return true;
871}
872
874 bool SupportedForCompatibility) {
875 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
876
877 // C++23 [temp.local]p6:
878 // The name of a template-parameter shall not be bound to any following.
879 // declaration whose locus is contained by the scope to which the
880 // template-parameter belongs.
881 //
882 // When MSVC compatibility is enabled, the diagnostic is always a warning
883 // by default. Otherwise, it an error unless SupportedForCompatibility is
884 // true, in which case it is a default-to-error warning.
885 unsigned DiagId =
886 getLangOpts().MSVCCompat
887 ? diag::ext_template_param_shadow
888 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
889 : diag::err_template_param_shadow);
890 const auto *ND = cast<NamedDecl>(PrevDecl);
891 Diag(Loc, DiagId) << ND->getDeclName();
893}
894
896 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
897 D = Temp->getTemplatedDecl();
898 return Temp;
899 }
900 return nullptr;
901}
902
904 SourceLocation EllipsisLoc) const {
905 assert(Kind == Template &&
906 "Only template template arguments can be pack expansions here");
907 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
908 "Template template argument pack expansion without packs");
910 Result.EllipsisLoc = EllipsisLoc;
911 return Result;
912}
913
915 const ParsedTemplateArgument &Arg) {
916
917 switch (Arg.getKind()) {
919 TypeSourceInfo *DI;
920 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
921 if (!DI)
922 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());
924 }
925
927 Expr *E = Arg.getAsExpr();
928 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
929 }
930
933 TemplateArgument TArg;
934 if (Arg.getEllipsisLoc().isValid())
935 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
936 else
937 TArg = Template;
938 return TemplateArgumentLoc(
939 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
941 Arg.getNameLoc(), Arg.getEllipsisLoc());
942 }
943 }
944
945 llvm_unreachable("Unhandled parsed template argument");
946}
947
949 TemplateArgumentListInfo &TemplateArgs) {
950 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
951 TemplateArgs.addArgument(translateTemplateArgument(*this,
952 TemplateArgsIn[I]));
953}
954
957 const IdentifierInfo *Name) {
958 NamedDecl *PrevDecl =
960 RedeclarationKind::ForVisibleRedeclaration);
961 if (PrevDecl && PrevDecl->isTemplateParameter())
962 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
963}
964
966 TypeSourceInfo *TInfo;
968 if (T.isNull())
969 return ParsedTemplateArgument();
970 assert(TInfo && "template argument with no location");
971
972 // If we might have formed a deduced template specialization type, convert
973 // it to a template template argument.
974 if (getLangOpts().CPlusPlus17) {
975 TypeLoc TL = TInfo->getTypeLoc();
976 SourceLocation EllipsisLoc;
977 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
978 EllipsisLoc = PET.getEllipsisLoc();
979 TL = PET.getPatternLoc();
980 }
981
982 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
983 TemplateName Name = DTST.getTypePtr()->getTemplateName();
984 CXXScopeSpec SS;
985 SS.Adopt(DTST.getQualifierLoc());
986 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
987 TemplateTy::make(Name),
988 DTST.getTemplateNameLoc());
989 if (EllipsisLoc.isValid())
990 Result = Result.getTemplatePackExpansion(EllipsisLoc);
991 return Result;
992 }
993 }
994
995 // This is a normal type template argument. Note, if the type template
996 // argument is an injected-class-name for a template, it has a dual nature
997 // and can be used as either a type or a template. We handle that in
998 // convertTypeTemplateArgumentToTemplate.
1001 TInfo->getTypeLoc().getBeginLoc());
1002}
1003
1005 SourceLocation EllipsisLoc,
1006 SourceLocation KeyLoc,
1007 IdentifierInfo *ParamName,
1008 SourceLocation ParamNameLoc,
1009 unsigned Depth, unsigned Position,
1010 SourceLocation EqualLoc,
1011 ParsedType DefaultArg,
1012 bool HasTypeConstraint) {
1013 assert(S->isTemplateParamScope() &&
1014 "Template type parameter not in template parameter scope!");
1015
1016 bool IsParameterPack = EllipsisLoc.isValid();
1019 KeyLoc, ParamNameLoc, Depth, Position,
1020 ParamName, Typename, IsParameterPack,
1021 HasTypeConstraint);
1022 Param->setAccess(AS_public);
1023
1024 if (Param->isParameterPack())
1025 if (auto *CSI = getEnclosingLambdaOrBlock())
1026 CSI->LocalPacks.push_back(Param);
1027
1028 if (ParamName) {
1029 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1030
1031 // Add the template parameter into the current scope.
1032 S->AddDecl(Param);
1033 IdResolver.AddDecl(Param);
1034 }
1035
1036 // C++0x [temp.param]p9:
1037 // A default template-argument may be specified for any kind of
1038 // template-parameter that is not a template parameter pack.
1039 if (DefaultArg && IsParameterPack) {
1040 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1041 DefaultArg = nullptr;
1042 }
1043
1044 // Handle the default argument, if provided.
1045 if (DefaultArg) {
1046 TypeSourceInfo *DefaultTInfo;
1047 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1048
1049 assert(DefaultTInfo && "expected source information for type");
1050
1051 // Check for unexpanded parameter packs.
1052 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1054 return Param;
1055
1056 // Check the template argument itself.
1057 if (CheckTemplateArgument(DefaultTInfo)) {
1058 Param->setInvalidDecl();
1059 return Param;
1060 }
1061
1062 Param->setDefaultArgument(
1063 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1064 }
1065
1066 return Param;
1067}
1068
1069/// Convert the parser's template argument list representation into our form.
1072 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1073 TemplateId.RAngleLoc);
1074 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1075 TemplateId.NumArgs);
1076 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1077 return TemplateArgs;
1078}
1079
1081
1082 TemplateName TN = TypeConstr->Template.get();
1083 NamedDecl *CD = nullptr;
1084 bool IsTypeConcept = false;
1085 bool RequiresArguments = false;
1086 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {
1087 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1088 RequiresArguments =
1089 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1090 CD = TTP;
1091 } else {
1092 CD = TN.getAsTemplateDecl();
1093 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();
1094 RequiresArguments = cast<ConceptDecl>(CD)
1097 }
1098
1099 // C++2a [temp.param]p4:
1100 // [...] The concept designated by a type-constraint shall be a type
1101 // concept ([temp.concept]).
1102 if (!IsTypeConcept) {
1103 Diag(TypeConstr->TemplateNameLoc,
1104 diag::err_type_constraint_non_type_concept);
1105 return true;
1106 }
1107
1108 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1109 return true;
1110
1111 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1112
1113 if (!WereArgsSpecified && RequiresArguments) {
1114 Diag(TypeConstr->TemplateNameLoc,
1115 diag::err_type_constraint_missing_arguments)
1116 << CD;
1117 return true;
1118 }
1119 return false;
1120}
1121
1123 TemplateIdAnnotation *TypeConstr,
1124 TemplateTypeParmDecl *ConstrainedParameter,
1125 SourceLocation EllipsisLoc) {
1126 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1127 false);
1128}
1129
1131 TemplateIdAnnotation *TypeConstr,
1132 TemplateTypeParmDecl *ConstrainedParameter,
1133 SourceLocation EllipsisLoc,
1134 bool AllowUnexpandedPack) {
1135
1136 if (CheckTypeConstraint(TypeConstr))
1137 return true;
1138
1139 TemplateName TN = TypeConstr->Template.get();
1140 TemplateDecl *CD = cast<TemplateDecl>(TN.getAsTemplateDecl());
1142
1143 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1144 TypeConstr->TemplateNameLoc);
1145
1146 TemplateArgumentListInfo TemplateArgs;
1147 if (TypeConstr->LAngleLoc.isValid()) {
1148 TemplateArgs =
1149 makeTemplateArgumentListInfo(*this, *TypeConstr);
1150
1151 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1152 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1154 return true;
1155 }
1156 }
1157 }
1158 return AttachTypeConstraint(
1160 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1161 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1162 ConstrainedParameter, EllipsisLoc);
1163}
1164
1165template <typename ArgumentLocAppender>
1168 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1169 SourceLocation RAngleLoc, QualType ConstrainedType,
1170 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1171 SourceLocation EllipsisLoc) {
1172
1173 TemplateArgumentListInfo ConstraintArgs;
1174 ConstraintArgs.addArgument(
1176 /*NTTPType=*/QualType(), ParamNameLoc));
1177
1178 ConstraintArgs.setRAngleLoc(RAngleLoc);
1179 ConstraintArgs.setLAngleLoc(LAngleLoc);
1180 Appender(ConstraintArgs);
1181
1182 // C++2a [temp.param]p4:
1183 // [...] This constraint-expression E is called the immediately-declared
1184 // constraint of T. [...]
1185 CXXScopeSpec SS;
1186 SS.Adopt(NS);
1187 ExprResult ImmediatelyDeclaredConstraint;
1188 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {
1189 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1190 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1191 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, CD,
1192 &ConstraintArgs);
1193 }
1194 // We have a template template parameter
1195 else {
1196 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);
1197 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1198 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);
1199 }
1200 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1201 return ImmediatelyDeclaredConstraint;
1202
1203 // C++2a [temp.param]p4:
1204 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1205 //
1206 // We have the following case:
1207 //
1208 // template<typename T> concept C1 = true;
1209 // template<C1... T> struct s1;
1210 //
1211 // The constraint: (C1<T> && ...)
1212 //
1213 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1214 // any unqualified lookups for 'operator&&' here.
1215 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1216 /*LParenLoc=*/SourceLocation(),
1217 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1218 EllipsisLoc, /*RHS=*/nullptr,
1219 /*RParenLoc=*/SourceLocation(),
1220 /*NumExpansions=*/std::nullopt);
1221}
1222
1224 DeclarationNameInfo NameInfo,
1225 TemplateDecl *NamedConcept,
1226 NamedDecl *FoundDecl,
1227 const TemplateArgumentListInfo *TemplateArgs,
1228 TemplateTypeParmDecl *ConstrainedParameter,
1229 SourceLocation EllipsisLoc) {
1230 // C++2a [temp.param]p4:
1231 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1232 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1233 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1235 *TemplateArgs) : nullptr;
1236
1237 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1238
1239 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1240 *this, NS, NameInfo, NamedConcept, FoundDecl,
1241 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1242 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1243 ParamAsArgument, ConstrainedParameter->getLocation(),
1244 [&](TemplateArgumentListInfo &ConstraintArgs) {
1245 if (TemplateArgs)
1246 for (const auto &ArgLoc : TemplateArgs->arguments())
1247 ConstraintArgs.addArgument(ArgLoc);
1248 },
1249 EllipsisLoc);
1250 if (ImmediatelyDeclaredConstraint.isInvalid())
1251 return true;
1252
1253 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1254 /*TemplateKWLoc=*/SourceLocation{},
1255 /*ConceptNameInfo=*/NameInfo,
1256 /*FoundDecl=*/FoundDecl,
1257 /*NamedConcept=*/NamedConcept,
1258 /*ArgsWritten=*/ArgsAsWritten);
1259 ConstrainedParameter->setTypeConstraint(
1260 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);
1261 return false;
1262}
1263
1265 NonTypeTemplateParmDecl *NewConstrainedParm,
1266 NonTypeTemplateParmDecl *OrigConstrainedParm,
1267 SourceLocation EllipsisLoc) {
1268 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1270 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1271 diag::err_unsupported_placeholder_constraint)
1272 << NewConstrainedParm->getTypeSourceInfo()
1273 ->getTypeLoc()
1274 .getSourceRange();
1275 return true;
1276 }
1277 // FIXME: Concepts: This should be the type of the placeholder, but this is
1278 // unclear in the wording right now.
1279 DeclRefExpr *Ref =
1280 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1281 VK_PRValue, OrigConstrainedParm->getLocation());
1282 if (!Ref)
1283 return true;
1284 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1286 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1288 OrigConstrainedParm->getLocation(),
1289 [&](TemplateArgumentListInfo &ConstraintArgs) {
1290 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1291 ConstraintArgs.addArgument(TL.getArgLoc(I));
1292 },
1293 EllipsisLoc);
1294 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1295 !ImmediatelyDeclaredConstraint.isUsable())
1296 return true;
1297
1298 NewConstrainedParm->setPlaceholderTypeConstraint(
1299 ImmediatelyDeclaredConstraint.get());
1300 return false;
1301}
1302
1305 if (TSI->getType()->isUndeducedType()) {
1306 // C++17 [temp.dep.expr]p3:
1307 // An id-expression is type-dependent if it contains
1308 // - an identifier associated by name lookup with a non-type
1309 // template-parameter declared with a type that contains a
1310 // placeholder type (7.1.7.4),
1312 }
1313
1315}
1316
1318 if (T->isDependentType())
1319 return false;
1320
1321 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1322 return true;
1323
1324 if (T->isStructuralType())
1325 return false;
1326
1327 // Structural types are required to be object types or lvalue references.
1328 if (T->isRValueReferenceType()) {
1329 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1330 return true;
1331 }
1332
1333 // Don't mention structural types in our diagnostic prior to C++20. Also,
1334 // there's not much more we can say about non-scalar non-class types --
1335 // because we can't see functions or arrays here, those can only be language
1336 // extensions.
1337 if (!getLangOpts().CPlusPlus20 ||
1338 (!T->isScalarType() && !T->isRecordType())) {
1339 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1340 return true;
1341 }
1342
1343 // Structural types are required to be literal types.
1344 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1345 return true;
1346
1347 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1348
1349 // Drill down into the reason why the class is non-structural.
1350 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1351 // All members are required to be public and non-mutable, and can't be of
1352 // rvalue reference type. Check these conditions first to prefer a "local"
1353 // reason over a more distant one.
1354 for (const FieldDecl *FD : RD->fields()) {
1355 if (FD->getAccess() != AS_public) {
1356 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1357 return true;
1358 }
1359 if (FD->isMutable()) {
1360 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1361 return true;
1362 }
1363 if (FD->getType()->isRValueReferenceType()) {
1364 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1365 << T;
1366 return true;
1367 }
1368 }
1369
1370 // All bases are required to be public.
1371 for (const auto &BaseSpec : RD->bases()) {
1372 if (BaseSpec.getAccessSpecifier() != AS_public) {
1373 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1374 << T << 1;
1375 return true;
1376 }
1377 }
1378
1379 // All subobjects are required to be of structural types.
1380 SourceLocation SubLoc;
1381 QualType SubType;
1382 int Kind = -1;
1383
1384 for (const FieldDecl *FD : RD->fields()) {
1385 QualType T = Context.getBaseElementType(FD->getType());
1386 if (!T->isStructuralType()) {
1387 SubLoc = FD->getLocation();
1388 SubType = T;
1389 Kind = 0;
1390 break;
1391 }
1392 }
1393
1394 if (Kind == -1) {
1395 for (const auto &BaseSpec : RD->bases()) {
1396 QualType T = BaseSpec.getType();
1397 if (!T->isStructuralType()) {
1398 SubLoc = BaseSpec.getBaseTypeLoc();
1399 SubType = T;
1400 Kind = 1;
1401 break;
1402 }
1403 }
1404 }
1405
1406 assert(Kind != -1 && "couldn't find reason why type is not structural");
1407 Diag(SubLoc, diag::note_not_structural_subobject)
1408 << T << Kind << SubType;
1409 T = SubType;
1410 RD = T->getAsCXXRecordDecl();
1411 }
1412
1413 return true;
1414}
1415
1418 // We don't allow variably-modified types as the type of non-type template
1419 // parameters.
1420 if (T->isVariablyModifiedType()) {
1421 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1422 << T;
1423 return QualType();
1424 }
1425
1426 // C++ [temp.param]p4:
1427 //
1428 // A non-type template-parameter shall have one of the following
1429 // (optionally cv-qualified) types:
1430 //
1431 // -- integral or enumeration type,
1433 // -- pointer to object or pointer to function,
1434 T->isPointerType() ||
1435 // -- lvalue reference to object or lvalue reference to function,
1437 // -- pointer to member,
1439 // -- std::nullptr_t, or
1440 T->isNullPtrType() ||
1441 // -- a type that contains a placeholder type.
1442 T->isUndeducedType()) {
1443 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1444 // are ignored when determining its type.
1445 return T.getUnqualifiedType();
1446 }
1447
1448 // C++ [temp.param]p8:
1449 //
1450 // A non-type template-parameter of type "array of T" or
1451 // "function returning T" is adjusted to be of type "pointer to
1452 // T" or "pointer to function returning T", respectively.
1453 if (T->isArrayType() || T->isFunctionType())
1454 return Context.getDecayedType(T);
1455
1456 // If T is a dependent type, we can't do the check now, so we
1457 // assume that it is well-formed. Note that stripping off the
1458 // qualifiers here is not really correct if T turns out to be
1459 // an array type, but we'll recompute the type everywhere it's
1460 // used during instantiation, so that should be OK. (Using the
1461 // qualified type is equally wrong.)
1462 if (T->isDependentType())
1463 return T.getUnqualifiedType();
1464
1465 // C++20 [temp.param]p6:
1466 // -- a structural type
1468 return QualType();
1469
1470 if (!getLangOpts().CPlusPlus20) {
1471 // FIXME: Consider allowing structural types as an extension in C++17. (In
1472 // earlier language modes, the template argument evaluation rules are too
1473 // inflexible.)
1474 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1475 return QualType();
1476 }
1477
1478 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1479 return T.getUnqualifiedType();
1480}
1481
1483 unsigned Depth,
1484 unsigned Position,
1485 SourceLocation EqualLoc,
1486 Expr *Default) {
1488
1489 // Check that we have valid decl-specifiers specified.
1490 auto CheckValidDeclSpecifiers = [this, &D] {
1491 // C++ [temp.param]
1492 // p1
1493 // template-parameter:
1494 // ...
1495 // parameter-declaration
1496 // p2
1497 // ... A storage class shall not be specified in a template-parameter
1498 // declaration.
1499 // [dcl.typedef]p1:
1500 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1501 // of a parameter-declaration
1502 const DeclSpec &DS = D.getDeclSpec();
1503 auto EmitDiag = [this](SourceLocation Loc) {
1504 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1506 };
1508 EmitDiag(DS.getStorageClassSpecLoc());
1509
1511 EmitDiag(DS.getThreadStorageClassSpecLoc());
1512
1513 // [dcl.inline]p1:
1514 // The inline specifier can be applied only to the declaration or
1515 // definition of a variable or function.
1516
1517 if (DS.isInlineSpecified())
1518 EmitDiag(DS.getInlineSpecLoc());
1519
1520 // [dcl.constexpr]p1:
1521 // The constexpr specifier shall be applied only to the definition of a
1522 // variable or variable template or the declaration of a function or
1523 // function template.
1524
1525 if (DS.hasConstexprSpecifier())
1526 EmitDiag(DS.getConstexprSpecLoc());
1527
1528 // [dcl.fct.spec]p1:
1529 // Function-specifiers can be used only in function declarations.
1530
1531 if (DS.isVirtualSpecified())
1532 EmitDiag(DS.getVirtualSpecLoc());
1533
1534 if (DS.hasExplicitSpecifier())
1535 EmitDiag(DS.getExplicitSpecLoc());
1536
1537 if (DS.isNoreturnSpecified())
1538 EmitDiag(DS.getNoreturnSpecLoc());
1539 };
1540
1541 CheckValidDeclSpecifiers();
1542
1543 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1544 if (isa<AutoType>(T))
1545 Diag(D.getIdentifierLoc(),
1546 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1547 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1548
1549 assert(S->isTemplateParamScope() &&
1550 "Non-type template parameter not in template parameter scope!");
1551 bool Invalid = false;
1552
1553 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1554 if (T.isNull()) {
1555 T = Context.IntTy; // Recover with an 'int' type.
1556 Invalid = true;
1557 }
1558
1560
1561 const IdentifierInfo *ParamName = D.getIdentifier();
1562 bool IsParameterPack = D.hasEllipsis();
1565 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1566 TInfo);
1567 Param->setAccess(AS_public);
1568
1570 if (TL.isConstrained()) {
1571 if (D.getEllipsisLoc().isInvalid() &&
1573 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1574 for (auto &Loc :
1575 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1578 }
1579 if (!Invalid &&
1580 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1581 Invalid = true;
1582 }
1583
1584 if (Invalid)
1585 Param->setInvalidDecl();
1586
1587 if (Param->isParameterPack())
1588 if (auto *CSI = getEnclosingLambdaOrBlock())
1589 CSI->LocalPacks.push_back(Param);
1590
1591 if (ParamName) {
1592 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1593 ParamName);
1594
1595 // Add the template parameter into the current scope.
1596 S->AddDecl(Param);
1597 IdResolver.AddDecl(Param);
1598 }
1599
1600 // C++0x [temp.param]p9:
1601 // A default template-argument may be specified for any kind of
1602 // template-parameter that is not a template parameter pack.
1603 if (Default && IsParameterPack) {
1604 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1605 Default = nullptr;
1606 }
1607
1608 // Check the well-formedness of the default template argument, if provided.
1609 if (Default) {
1610 // Check for unexpanded parameter packs.
1612 return Param;
1613
1614 Param->setDefaultArgument(
1616 TemplateArgument(Default, /*IsCanonical=*/false),
1617 QualType(), SourceLocation()));
1618 }
1619
1620 return Param;
1621}
1622
1623/// ActOnTemplateTemplateParameter - Called when a C++ template template
1624/// parameter (e.g. T in template <template <typename> class T> class array)
1625/// has been parsed. S is the current scope.
1627 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1628 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1629 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1630 unsigned Position, SourceLocation EqualLoc,
1632 assert(S->isTemplateParamScope() &&
1633 "Template template parameter not in template parameter scope!");
1634
1635 bool IsParameterPack = EllipsisLoc.isValid();
1636
1637 bool Invalid = false;
1639 Params,
1640 /*OldParams=*/nullptr,
1641 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1642 Invalid = true;
1643
1644 // Construct the parameter object.
1647 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1648 Name, Kind, Typename, Params);
1649 Param->setAccess(AS_public);
1650
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambdaOrBlock())
1653 LSI->LocalPacks.push_back(Param);
1654
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1657 if (Name) {
1658 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1659
1660 S->AddDecl(Param);
1661 IdResolver.AddDecl(Param);
1662 }
1663
1664 if (Params->size() == 0) {
1665 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1666 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1667 Invalid = true;
1668 }
1669
1670 if (Invalid)
1671 Param->setInvalidDecl();
1672
1673 // C++0x [temp.param]p9:
1674 // A default template-argument may be specified for any kind of
1675 // template-parameter that is not a template parameter pack.
1676 if (IsParameterPack && !Default.isInvalid()) {
1677 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1679 }
1680
1681 if (!Default.isInvalid()) {
1682 // Check only that we have a template template argument. We don't want to
1683 // try to check well-formedness now, because our template template parameter
1684 // might have dependent types in its template parameters, which we wouldn't
1685 // be able to match now.
1686 //
1687 // If none of the template template parameter's template arguments mention
1688 // other template parameters, we could actually perform more checking here.
1689 // However, it isn't worth doing.
1691 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1692 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1693 << DefaultArg.getSourceRange();
1694 return Param;
1695 }
1696
1697 TemplateName Name =
1699 TemplateDecl *Template = Name.getAsTemplateDecl();
1700 if (Template &&
1702 return Param;
1703 }
1704
1705 // Check for unexpanded parameter packs.
1707 DefaultArg.getArgument().getAsTemplate(),
1709 return Param;
1710
1711 Param->setDefaultArgument(Context, DefaultArg);
1712 }
1713
1714 return Param;
1715}
1716
1717namespace {
1718class ConstraintRefersToContainingTemplateChecker
1719 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1720 bool Result = false;
1721 const FunctionDecl *Friend = nullptr;
1722 unsigned TemplateDepth = 0;
1723
1724 // Check a record-decl that we've seen to see if it is a lexical parent of the
1725 // Friend, likely because it was referred to without its template arguments.
1726 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1727 CheckingRD = CheckingRD->getMostRecentDecl();
1728 if (!CheckingRD->isTemplated())
1729 return;
1730
1731 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1732 DC && !DC->isFileContext(); DC = DC->getParent())
1733 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1734 if (CheckingRD == RD->getMostRecentDecl())
1735 Result = true;
1736 }
1737
1738 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1739 if (D->getDepth() < TemplateDepth)
1740 Result = true;
1741
1742 // Necessary because the type of the NTTP might be what refers to the parent
1743 // constriant.
1744 TransformType(D->getType());
1745 }
1746
1747public:
1749
1750 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1751 const FunctionDecl *Friend,
1752 unsigned TemplateDepth)
1753 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1754 bool getResult() const { return Result; }
1755
1756 // This should be the only template parm type that we have to deal with.
1757 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1758 // FunctionParmPackExpr are all partially substituted, which cannot happen
1759 // with concepts at this point in translation.
1760 using inherited::TransformTemplateTypeParmType;
1761 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1762 TemplateTypeParmTypeLoc TL, bool) {
1763 if (TL.getDecl()->getDepth() < TemplateDepth)
1764 Result = true;
1765 return inherited::TransformTemplateTypeParmType(
1766 TLB, TL,
1767 /*SuppressObjCLifetime=*/false);
1768 }
1769
1770 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1771 if (!D)
1772 return D;
1773 // FIXME : This is possibly an incomplete list, but it is unclear what other
1774 // Decl kinds could be used to refer to the template parameters. This is a
1775 // best guess so far based on examples currently available, but the
1776 // unreachable should catch future instances/cases.
1777 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1778 TransformType(TD->getUnderlyingType());
1779 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1780 CheckNonTypeTemplateParmDecl(NTTPD);
1781 else if (auto *VD = dyn_cast<ValueDecl>(D))
1782 TransformType(VD->getType());
1783 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1784 TransformTemplateParameterList(TD->getTemplateParameters());
1785 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1786 CheckIfContainingRecord(RD);
1787 else if (isa<NamedDecl>(D)) {
1788 // No direct types to visit here I believe.
1789 } else
1790 llvm_unreachable("Don't know how to handle this declaration type yet");
1791 return D;
1792 }
1793};
1794} // namespace
1795
1797 const FunctionDecl *Friend, unsigned TemplateDepth,
1798 const Expr *Constraint) {
1799 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1800 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1801 TemplateDepth);
1802 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1803 return Checker.getResult();
1804}
1805
1808 SourceLocation ExportLoc,
1809 SourceLocation TemplateLoc,
1810 SourceLocation LAngleLoc,
1811 ArrayRef<NamedDecl *> Params,
1812 SourceLocation RAngleLoc,
1813 Expr *RequiresClause) {
1814 if (ExportLoc.isValid())
1815 Diag(ExportLoc, diag::warn_template_export_unsupported);
1816
1817 for (NamedDecl *P : Params)
1819
1820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
1821 llvm::ArrayRef(Params), RAngleLoc,
1822 RequiresClause);
1823}
1824
1826 const CXXScopeSpec &SS) {
1827 if (SS.isSet())
1828 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1829}
1830
1831// Returns the template parameter list with all default template argument
1832// information.
1834 // Make sure we get the template parameter list from the most
1835 // recent declaration, since that is the only one that is guaranteed to
1836 // have all the default template argument information.
1837 Decl *D = TD->getMostRecentDecl();
1838 // C++11 N3337 [temp.param]p12:
1839 // A default template argument shall not be specified in a friend class
1840 // template declaration.
1841 //
1842 // Skip past friend *declarations* because they are not supposed to contain
1843 // default template arguments. Moreover, these declarations may introduce
1844 // template parameters living in different template depths than the
1845 // corresponding template parameters in TD, causing unmatched constraint
1846 // substitution.
1847 //
1848 // FIXME: Diagnose such cases within a class template:
1849 // template <class T>
1850 // struct S {
1851 // template <class = void> friend struct C;
1852 // };
1853 // template struct S<int>;
1855 D->getPreviousDecl())
1856 D = D->getPreviousDecl();
1857 return cast<TemplateDecl>(D)->getTemplateParameters();
1858}
1859
1861 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1862 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1863 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1864 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1865 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1866 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1867 assert(TemplateParams && TemplateParams->size() > 0 &&
1868 "No template parameters");
1869 assert(TUK != TagUseKind::Reference &&
1870 "Can only declare or define class templates");
1871 bool Invalid = false;
1872
1873 // Check that we can declare a template here.
1874 if (CheckTemplateDeclScope(S, TemplateParams))
1875 return true;
1876
1878 assert(Kind != TagTypeKind::Enum &&
1879 "can't build template of enumerated type");
1880
1881 // There is no such thing as an unnamed class template.
1882 if (!Name) {
1883 Diag(KWLoc, diag::err_template_unnamed_class);
1884 return true;
1885 }
1886
1887 // Find any previous declaration with this name. For a friend with no
1888 // scope explicitly specified, we only look for tag declarations (per
1889 // C++11 [basic.lookup.elab]p2).
1890 DeclContext *SemanticContext;
1891 LookupResult Previous(*this, Name, NameLoc,
1892 (SS.isEmpty() && TUK == TagUseKind::Friend)
1896 if (SS.isNotEmpty() && !SS.isInvalid()) {
1897 SemanticContext = computeDeclContext(SS, true);
1898 if (!SemanticContext) {
1899 // FIXME: Horrible, horrible hack! We can't currently represent this
1900 // in the AST, and historically we have just ignored such friend
1901 // class templates, so don't complain here.
1902 Diag(NameLoc, TUK == TagUseKind::Friend
1903 ? diag::warn_template_qualified_friend_ignored
1904 : diag::err_template_qualified_declarator_no_match)
1905 << SS.getScopeRep() << SS.getRange();
1906 return TUK != TagUseKind::Friend;
1907 }
1908
1909 if (RequireCompleteDeclContext(SS, SemanticContext))
1910 return true;
1911
1912 // If we're adding a template to a dependent context, we may need to
1913 // rebuilding some of the types used within the template parameter list,
1914 // now that we know what the current instantiation is.
1915 if (SemanticContext->isDependentContext()) {
1916 ContextRAII SavedContext(*this, SemanticContext);
1918 Invalid = true;
1919 }
1920
1921 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1922 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1923 /*TemplateId-*/ nullptr,
1924 /*IsMemberSpecialization*/ false);
1925
1926 LookupQualifiedName(Previous, SemanticContext);
1927 } else {
1928 SemanticContext = CurContext;
1929
1930 // C++14 [class.mem]p14:
1931 // If T is the name of a class, then each of the following shall have a
1932 // name different from T:
1933 // -- every member template of class T
1934 if (TUK != TagUseKind::Friend &&
1935 DiagnoseClassNameShadow(SemanticContext,
1936 DeclarationNameInfo(Name, NameLoc)))
1937 return true;
1938
1939 LookupName(Previous, S);
1940 }
1941
1942 if (Previous.isAmbiguous())
1943 return true;
1944
1945 // Let the template parameter scope enter the lookup chain of the current
1946 // class template. For example, given
1947 //
1948 // namespace ns {
1949 // template <class> bool Param = false;
1950 // template <class T> struct N;
1951 // }
1952 //
1953 // template <class Param> struct ns::N { void foo(Param); };
1954 //
1955 // When we reference Param inside the function parameter list, our name lookup
1956 // chain for it should be like:
1957 // FunctionScope foo
1958 // -> RecordScope N
1959 // -> TemplateParamScope (where we will find Param)
1960 // -> NamespaceScope ns
1961 //
1962 // See also CppLookupName().
1963 if (S->isTemplateParamScope())
1964 EnterTemplatedContext(S, SemanticContext);
1965
1966 NamedDecl *PrevDecl = nullptr;
1967 if (Previous.begin() != Previous.end())
1968 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1969
1970 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1971 // Maybe we will complain about the shadowed template parameter.
1972 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1973 // Just pretend that we didn't see the previous declaration.
1974 PrevDecl = nullptr;
1975 }
1976
1977 // If there is a previous declaration with the same name, check
1978 // whether this is a valid redeclaration.
1979 ClassTemplateDecl *PrevClassTemplate =
1980 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1981
1982 // We may have found the injected-class-name of a class template,
1983 // class template partial specialization, or class template specialization.
1984 // In these cases, grab the template that is being defined or specialized.
1985 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1986 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1987 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1988 PrevClassTemplate
1989 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1990 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1991 PrevClassTemplate
1992 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1993 ->getSpecializedTemplate();
1994 }
1995 }
1996
1997 if (TUK == TagUseKind::Friend) {
1998 // C++ [namespace.memdef]p3:
1999 // [...] When looking for a prior declaration of a class or a function
2000 // declared as a friend, and when the name of the friend class or
2001 // function is neither a qualified name nor a template-id, scopes outside
2002 // the innermost enclosing namespace scope are not considered.
2003 if (!SS.isSet()) {
2004 DeclContext *OutermostContext = CurContext;
2005 while (!OutermostContext->isFileContext())
2006 OutermostContext = OutermostContext->getLookupParent();
2007
2008 if (PrevDecl &&
2009 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
2010 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
2011 SemanticContext = PrevDecl->getDeclContext();
2012 } else {
2013 // Declarations in outer scopes don't matter. However, the outermost
2014 // context we computed is the semantic context for our new
2015 // declaration.
2016 PrevDecl = PrevClassTemplate = nullptr;
2017 SemanticContext = OutermostContext;
2018
2019 // Check that the chosen semantic context doesn't already contain a
2020 // declaration of this name as a non-tag type.
2022 DeclContext *LookupContext = SemanticContext;
2023 while (LookupContext->isTransparentContext())
2024 LookupContext = LookupContext->getLookupParent();
2025 LookupQualifiedName(Previous, LookupContext);
2026
2027 if (Previous.isAmbiguous())
2028 return true;
2029
2030 if (Previous.begin() != Previous.end())
2031 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2032 }
2033 }
2034 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
2035 SemanticContext, S, SS.isValid()))
2036 PrevDecl = PrevClassTemplate = nullptr;
2037
2038 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2039 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2040 if (SS.isEmpty() &&
2041 !(PrevClassTemplate &&
2042 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2043 SemanticContext->getRedeclContext()))) {
2044 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2045 Diag(Shadow->getTargetDecl()->getLocation(),
2046 diag::note_using_decl_target);
2047 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2048 // Recover by ignoring the old declaration.
2049 PrevDecl = PrevClassTemplate = nullptr;
2050 }
2051 }
2052
2053 if (PrevClassTemplate) {
2054 // Ensure that the template parameter lists are compatible. Skip this check
2055 // for a friend in a dependent context: the template parameter list itself
2056 // could be dependent.
2057 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2059 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2060 : CurContext,
2061 CurContext, KWLoc),
2062 TemplateParams, PrevClassTemplate,
2063 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2065 return true;
2066
2067 // C++ [temp.class]p4:
2068 // In a redeclaration, partial specialization, explicit
2069 // specialization or explicit instantiation of a class template,
2070 // the class-key shall agree in kind with the original class
2071 // template declaration (7.1.5.3).
2072 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2074 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2075 Diag(KWLoc, diag::err_use_with_wrong_tag)
2076 << Name
2077 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2078 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2079 Kind = PrevRecordDecl->getTagKind();
2080 }
2081
2082 // Check for redefinition of this class template.
2083 if (TUK == TagUseKind::Definition) {
2084 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2085 // If we have a prior definition that is not visible, treat this as
2086 // simply making that previous definition visible.
2087 NamedDecl *Hidden = nullptr;
2088 bool HiddenDefVisible = false;
2089 if (SkipBody &&
2090 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
2091 SkipBody->ShouldSkip = true;
2092 SkipBody->Previous = Def;
2093 if (!HiddenDefVisible && Hidden) {
2094 auto *Tmpl =
2095 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2096 assert(Tmpl && "original definition of a class template is not a "
2097 "class template?");
2100 }
2101 } else {
2102 Diag(NameLoc, diag::err_redefinition) << Name;
2103 Diag(Def->getLocation(), diag::note_previous_definition);
2104 // FIXME: Would it make sense to try to "forget" the previous
2105 // definition, as part of error recovery?
2106 return true;
2107 }
2108 }
2109 }
2110 } else if (PrevDecl) {
2111 // C++ [temp]p5:
2112 // A class template shall not have the same name as any other
2113 // template, class, function, object, enumeration, enumerator,
2114 // namespace, or type in the same scope (3.3), except as specified
2115 // in (14.5.4).
2116 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2117 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2118 return true;
2119 }
2120
2121 // Check the template parameter list of this declaration, possibly
2122 // merging in the template parameter list from the previous class
2123 // template declaration. Skip this check for a friend in a dependent
2124 // context, because the template parameter list might be dependent.
2125 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2127 TemplateParams,
2128 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2129 : nullptr,
2130 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2131 SemanticContext->isDependentContext())
2134 : TPC_Other,
2135 SkipBody))
2136 Invalid = true;
2137
2138 if (SS.isSet()) {
2139 // If the name of the template was qualified, we must be defining the
2140 // template out-of-line.
2141 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2142 Diag(NameLoc, TUK == TagUseKind::Friend
2143 ? diag::err_friend_decl_does_not_match
2144 : diag::err_member_decl_does_not_match)
2145 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2146 Invalid = true;
2147 }
2148 }
2149
2150 // If this is a templated friend in a dependent context we should not put it
2151 // on the redecl chain. In some cases, the templated friend can be the most
2152 // recent declaration tricking the template instantiator to make substitutions
2153 // there.
2154 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2155 bool ShouldAddRedecl =
2157
2159 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2160 PrevClassTemplate && ShouldAddRedecl
2161 ? PrevClassTemplate->getTemplatedDecl()
2162 : nullptr);
2163 SetNestedNameSpecifier(*this, NewClass, SS);
2164 if (NumOuterTemplateParamLists > 0)
2166 Context,
2167 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2168
2169 // Add alignment attributes if necessary; these attributes are checked when
2170 // the ASTContext lays out the structure.
2171 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2172 if (LangOpts.HLSL)
2173 NewClass->addAttr(PackedAttr::CreateImplicit(Context));
2176 }
2177
2178 ClassTemplateDecl *NewTemplate
2179 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2180 DeclarationName(Name), TemplateParams,
2181 NewClass);
2182
2183 if (ShouldAddRedecl)
2184 NewTemplate->setPreviousDecl(PrevClassTemplate);
2185
2186 NewClass->setDescribedClassTemplate(NewTemplate);
2187
2188 if (ModulePrivateLoc.isValid())
2189 NewTemplate->setModulePrivate();
2190
2191 // If we are providing an explicit specialization of a member that is a
2192 // class template, make a note of that.
2193 if (PrevClassTemplate &&
2194 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2195 PrevClassTemplate->setMemberSpecialization();
2196
2197 // Set the access specifier.
2198 if (!Invalid && TUK != TagUseKind::Friend &&
2199 NewTemplate->getDeclContext()->isRecord())
2200 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2201
2202 // Set the lexical context of these templates
2204 NewTemplate->setLexicalDeclContext(CurContext);
2205
2206 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2207 NewClass->startDefinition();
2208
2209 ProcessDeclAttributeList(S, NewClass, Attr);
2210
2211 if (PrevClassTemplate)
2212 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2213
2217
2218 if (TUK != TagUseKind::Friend) {
2219 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2220 Scope *Outer = S;
2221 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2222 Outer = Outer->getParent();
2223 PushOnScopeChains(NewTemplate, Outer);
2224 } else {
2225 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2226 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2227 NewClass->setAccess(PrevClassTemplate->getAccess());
2228 }
2229
2230 NewTemplate->setObjectOfFriendDecl();
2231
2232 // Friend templates are visible in fairly strange ways.
2234 DeclContext *DC = SemanticContext->getRedeclContext();
2235 DC->makeDeclVisibleInContext(NewTemplate);
2236 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2237 PushOnScopeChains(NewTemplate, EnclosingScope,
2238 /* AddToContext = */ false);
2239 }
2240
2242 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2243 Friend->setAccess(AS_public);
2245 }
2246
2247 if (PrevClassTemplate)
2248 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2249
2250 if (Invalid) {
2251 NewTemplate->setInvalidDecl();
2252 NewClass->setInvalidDecl();
2253 }
2254
2255 ActOnDocumentableDecl(NewTemplate);
2256
2257 if (SkipBody && SkipBody->ShouldSkip)
2258 return SkipBody->Previous;
2259
2260 return NewTemplate;
2261}
2262
2263/// Diagnose the presence of a default template argument on a
2264/// template parameter, which is ill-formed in certain contexts.
2265///
2266/// \returns true if the default template argument should be dropped.
2269 SourceLocation ParamLoc,
2270 SourceRange DefArgRange) {
2271 switch (TPC) {
2272 case Sema::TPC_Other:
2274 return false;
2275
2278 // C++ [temp.param]p9:
2279 // A default template-argument shall not be specified in a
2280 // function template declaration or a function template
2281 // definition [...]
2282 // If a friend function template declaration specifies a default
2283 // template-argument, that declaration shall be a definition and shall be
2284 // the only declaration of the function template in the translation unit.
2285 // (C++98/03 doesn't have this wording; see DR226).
2286 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)
2287 << DefArgRange;
2288 return false;
2289
2291 // C++0x [temp.param]p9:
2292 // A default template-argument shall not be specified in the
2293 // template-parameter-lists of the definition of a member of a
2294 // class template that appears outside of the member's class.
2295 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2296 << DefArgRange;
2297 return true;
2298
2301 // C++ [temp.param]p9:
2302 // A default template-argument shall not be specified in a
2303 // friend template declaration.
2304 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2305 << DefArgRange;
2306 return true;
2307
2308 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2309 // for friend function templates if there is only a single
2310 // declaration (and it is a definition). Strange!
2311 }
2312
2313 llvm_unreachable("Invalid TemplateParamListContext!");
2314}
2315
2316/// Check for unexpanded parameter packs within the template parameters
2317/// of a template template parameter, recursively.
2320 // A template template parameter which is a parameter pack is also a pack
2321 // expansion.
2322 if (TTP->isParameterPack())
2323 return false;
2324
2326 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2327 NamedDecl *P = Params->getParam(I);
2328 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2329 if (!TTP->isParameterPack())
2330 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2331 if (TC->hasExplicitTemplateArgs())
2332 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2335 return true;
2336 continue;
2337 }
2338
2339 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2340 if (!NTTP->isParameterPack() &&
2341 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2342 NTTP->getTypeSourceInfo(),
2344 return true;
2345
2346 continue;
2347 }
2348
2349 if (TemplateTemplateParmDecl *InnerTTP
2350 = dyn_cast<TemplateTemplateParmDecl>(P))
2351 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2352 return true;
2353 }
2354
2355 return false;
2356}
2357
2359 TemplateParameterList *OldParams,
2361 SkipBodyInfo *SkipBody) {
2362 bool Invalid = false;
2363
2364 // C++ [temp.param]p10:
2365 // The set of default template-arguments available for use with a
2366 // template declaration or definition is obtained by merging the
2367 // default arguments from the definition (if in scope) and all
2368 // declarations in scope in the same way default function
2369 // arguments are (8.3.6).
2370 bool SawDefaultArgument = false;
2371 SourceLocation PreviousDefaultArgLoc;
2372
2373 // Dummy initialization to avoid warnings.
2374 TemplateParameterList::iterator OldParam = NewParams->end();
2375 if (OldParams)
2376 OldParam = OldParams->begin();
2377
2378 bool RemoveDefaultArguments = false;
2379 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2380 NewParamEnd = NewParams->end();
2381 NewParam != NewParamEnd; ++NewParam) {
2382 // Whether we've seen a duplicate default argument in the same translation
2383 // unit.
2384 bool RedundantDefaultArg = false;
2385 // Whether we've found inconsis inconsitent default arguments in different
2386 // translation unit.
2387 bool InconsistentDefaultArg = false;
2388 // The name of the module which contains the inconsistent default argument.
2389 std::string PrevModuleName;
2390
2391 SourceLocation OldDefaultLoc;
2392 SourceLocation NewDefaultLoc;
2393
2394 // Variable used to diagnose missing default arguments
2395 bool MissingDefaultArg = false;
2396
2397 // Variable used to diagnose non-final parameter packs
2398 bool SawParameterPack = false;
2399
2400 if (TemplateTypeParmDecl *NewTypeParm
2401 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2402 // Check the presence of a default argument here.
2403 if (NewTypeParm->hasDefaultArgument() &&
2405 *this, TPC, NewTypeParm->getLocation(),
2406 NewTypeParm->getDefaultArgument().getSourceRange()))
2407 NewTypeParm->removeDefaultArgument();
2408
2409 // Merge default arguments for template type parameters.
2410 TemplateTypeParmDecl *OldTypeParm
2411 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2412 if (NewTypeParm->isParameterPack()) {
2413 assert(!NewTypeParm->hasDefaultArgument() &&
2414 "Parameter packs can't have a default argument!");
2415 SawParameterPack = true;
2416 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2417 NewTypeParm->hasDefaultArgument() &&
2418 (!SkipBody || !SkipBody->ShouldSkip)) {
2419 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2420 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2421 SawDefaultArgument = true;
2422
2423 if (!OldTypeParm->getOwningModule())
2424 RedundantDefaultArg = true;
2425 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2426 NewTypeParm)) {
2427 InconsistentDefaultArg = true;
2428 PrevModuleName =
2430 }
2431 PreviousDefaultArgLoc = NewDefaultLoc;
2432 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2433 // Merge the default argument from the old declaration to the
2434 // new declaration.
2435 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2436 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2437 } else if (NewTypeParm->hasDefaultArgument()) {
2438 SawDefaultArgument = true;
2439 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2440 } else if (SawDefaultArgument)
2441 MissingDefaultArg = true;
2442 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2443 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2444 // Check for unexpanded parameter packs, except in a template template
2445 // parameter pack, as in those any unexpanded packs should be expanded
2446 // along with the parameter itself.
2448 !NewNonTypeParm->isParameterPack() &&
2449 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2450 NewNonTypeParm->getTypeSourceInfo(),
2452 Invalid = true;
2453 continue;
2454 }
2455
2456 // Check the presence of a default argument here.
2457 if (NewNonTypeParm->hasDefaultArgument() &&
2459 *this, TPC, NewNonTypeParm->getLocation(),
2460 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2461 NewNonTypeParm->removeDefaultArgument();
2462 }
2463
2464 // Merge default arguments for non-type template parameters
2465 NonTypeTemplateParmDecl *OldNonTypeParm
2466 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2467 if (NewNonTypeParm->isParameterPack()) {
2468 assert(!NewNonTypeParm->hasDefaultArgument() &&
2469 "Parameter packs can't have a default argument!");
2470 if (!NewNonTypeParm->isPackExpansion())
2471 SawParameterPack = true;
2472 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2473 NewNonTypeParm->hasDefaultArgument() &&
2474 (!SkipBody || !SkipBody->ShouldSkip)) {
2475 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2476 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2477 SawDefaultArgument = true;
2478 if (!OldNonTypeParm->getOwningModule())
2479 RedundantDefaultArg = true;
2480 else if (!getASTContext().isSameDefaultTemplateArgument(
2481 OldNonTypeParm, NewNonTypeParm)) {
2482 InconsistentDefaultArg = true;
2483 PrevModuleName =
2484 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2485 }
2486 PreviousDefaultArgLoc = NewDefaultLoc;
2487 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2488 // Merge the default argument from the old declaration to the
2489 // new declaration.
2490 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2491 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2492 } else if (NewNonTypeParm->hasDefaultArgument()) {
2493 SawDefaultArgument = true;
2494 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2495 } else if (SawDefaultArgument)
2496 MissingDefaultArg = true;
2497 } else {
2498 TemplateTemplateParmDecl *NewTemplateParm
2499 = cast<TemplateTemplateParmDecl>(*NewParam);
2500
2501 // Check for unexpanded parameter packs, recursively.
2502 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2503 Invalid = true;
2504 continue;
2505 }
2506
2507 // Check the presence of a default argument here.
2508 if (NewTemplateParm->hasDefaultArgument() &&
2510 NewTemplateParm->getLocation(),
2511 NewTemplateParm->getDefaultArgument().getSourceRange()))
2512 NewTemplateParm->removeDefaultArgument();
2513
2514 // Merge default arguments for template template parameters
2515 TemplateTemplateParmDecl *OldTemplateParm
2516 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2517 if (NewTemplateParm->isParameterPack()) {
2518 assert(!NewTemplateParm->hasDefaultArgument() &&
2519 "Parameter packs can't have a default argument!");
2520 if (!NewTemplateParm->isPackExpansion())
2521 SawParameterPack = true;
2522 } else if (OldTemplateParm &&
2523 hasVisibleDefaultArgument(OldTemplateParm) &&
2524 NewTemplateParm->hasDefaultArgument() &&
2525 (!SkipBody || !SkipBody->ShouldSkip)) {
2526 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2527 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2528 SawDefaultArgument = true;
2529 if (!OldTemplateParm->getOwningModule())
2530 RedundantDefaultArg = true;
2531 else if (!getASTContext().isSameDefaultTemplateArgument(
2532 OldTemplateParm, NewTemplateParm)) {
2533 InconsistentDefaultArg = true;
2534 PrevModuleName =
2535 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2536 }
2537 PreviousDefaultArgLoc = NewDefaultLoc;
2538 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2539 // Merge the default argument from the old declaration to the
2540 // new declaration.
2541 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2542 PreviousDefaultArgLoc
2543 = OldTemplateParm->getDefaultArgument().getLocation();
2544 } else if (NewTemplateParm->hasDefaultArgument()) {
2545 SawDefaultArgument = true;
2546 PreviousDefaultArgLoc
2547 = NewTemplateParm->getDefaultArgument().getLocation();
2548 } else if (SawDefaultArgument)
2549 MissingDefaultArg = true;
2550 }
2551
2552 // C++11 [temp.param]p11:
2553 // If a template parameter of a primary class template or alias template
2554 // is a template parameter pack, it shall be the last template parameter.
2555 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2556 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2557 Diag((*NewParam)->getLocation(),
2558 diag::err_template_param_pack_must_be_last_template_parameter);
2559 Invalid = true;
2560 }
2561
2562 // [basic.def.odr]/13:
2563 // There can be more than one definition of a
2564 // ...
2565 // default template argument
2566 // ...
2567 // in a program provided that each definition appears in a different
2568 // translation unit and the definitions satisfy the [same-meaning
2569 // criteria of the ODR].
2570 //
2571 // Simply, the design of modules allows the definition of template default
2572 // argument to be repeated across translation unit. Note that the ODR is
2573 // checked elsewhere. But it is still not allowed to repeat template default
2574 // argument in the same translation unit.
2575 if (RedundantDefaultArg) {
2576 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2577 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2578 Invalid = true;
2579 } else if (InconsistentDefaultArg) {
2580 // We could only diagnose about the case that the OldParam is imported.
2581 // The case NewParam is imported should be handled in ASTReader.
2582 Diag(NewDefaultLoc,
2583 diag::err_template_param_default_arg_inconsistent_redefinition);
2584 Diag(OldDefaultLoc,
2585 diag::note_template_param_prev_default_arg_in_other_module)
2586 << PrevModuleName;
2587 Invalid = true;
2588 } else if (MissingDefaultArg &&
2589 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2590 TPC == TPC_FriendClassTemplate)) {
2591 // C++ 23[temp.param]p14:
2592 // If a template-parameter of a class template, variable template, or
2593 // alias template has a default template argument, each subsequent
2594 // template-parameter shall either have a default template argument
2595 // supplied or be a template parameter pack.
2596 Diag((*NewParam)->getLocation(),
2597 diag::err_template_param_default_arg_missing);
2598 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2599 Invalid = true;
2600 RemoveDefaultArguments = true;
2601 }
2602
2603 // If we have an old template parameter list that we're merging
2604 // in, move on to the next parameter.
2605 if (OldParams)
2606 ++OldParam;
2607 }
2608
2609 // We were missing some default arguments at the end of the list, so remove
2610 // all of the default arguments.
2611 if (RemoveDefaultArguments) {
2612 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2613 NewParamEnd = NewParams->end();
2614 NewParam != NewParamEnd; ++NewParam) {
2615 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2616 TTP->removeDefaultArgument();
2617 else if (NonTypeTemplateParmDecl *NTTP
2618 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2619 NTTP->removeDefaultArgument();
2620 else
2621 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2622 }
2623 }
2624
2625 return Invalid;
2626}
2627
2628namespace {
2629
2630/// A class which looks for a use of a certain level of template
2631/// parameter.
2632struct DependencyChecker : DynamicRecursiveASTVisitor {
2633 unsigned Depth;
2634
2635 // Whether we're looking for a use of a template parameter that makes the
2636 // overall construct type-dependent / a dependent type. This is strictly
2637 // best-effort for now; we may fail to match at all for a dependent type
2638 // in some cases if this is set.
2639 bool IgnoreNonTypeDependent;
2640
2641 bool Match;
2642 SourceLocation MatchLoc;
2643
2644 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2645 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2646 Match(false) {}
2647
2648 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2649 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2650 NamedDecl *ND = Params->getParam(0);
2651 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2652 Depth = PD->getDepth();
2653 } else if (NonTypeTemplateParmDecl *PD =
2654 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2655 Depth = PD->getDepth();
2656 } else {
2657 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2658 }
2659 }
2660
2661 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2662 if (ParmDepth >= Depth) {
2663 Match = true;
2664 MatchLoc = Loc;
2665 return true;
2666 }
2667 return false;
2668 }
2669
2670 bool TraverseStmt(Stmt *S) override {
2671 // Prune out non-type-dependent expressions if requested. This can
2672 // sometimes result in us failing to find a template parameter reference
2673 // (if a value-dependent expression creates a dependent type), but this
2674 // mode is best-effort only.
2675 if (auto *E = dyn_cast_or_null<Expr>(S))
2676 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2677 return true;
2679 }
2680
2681 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2682 if (IgnoreNonTypeDependent && !TL.isNull() &&
2683 !TL.getType()->isDependentType())
2684 return true;
2685 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2686 }
2687
2688 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2689 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2690 }
2691
2692 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2693 // For a best-effort search, keep looking until we find a location.
2694 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2695 }
2696
2697 bool TraverseTemplateName(TemplateName N) override {
2698 if (TemplateTemplateParmDecl *PD =
2699 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2700 if (Matches(PD->getDepth()))
2701 return false;
2703 }
2704
2705 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2706 if (NonTypeTemplateParmDecl *PD =
2707 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2708 if (Matches(PD->getDepth(), E->getExprLoc()))
2709 return false;
2710 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2711 }
2712
2713 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2714 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2715 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2716 if (Matches(TTP->getDepth(), ULE->getExprLoc()))
2717 return false;
2718 }
2719 for (auto &TLoc : ULE->template_arguments())
2721 }
2722 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);
2723 }
2724
2725 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2726 return TraverseType(T->getReplacementType());
2727 }
2728
2729 bool VisitSubstTemplateTypeParmPackType(
2730 SubstTemplateTypeParmPackType *T) override {
2731 return TraverseTemplateArgument(T->getArgumentPack());
2732 }
2733
2734 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2735 bool TraverseQualifier) override {
2736 // An InjectedClassNameType will never have a dependent template name,
2737 // so no need to traverse it.
2738 return TraverseTemplateArguments(
2739 T->getTemplateArgs(T->getOriginalDecl()->getASTContext()));
2740 }
2741};
2742} // end anonymous namespace
2743
2744/// Determines whether a given type depends on the given parameter
2745/// list.
2746static bool
2748 if (!Params->size())
2749 return false;
2750
2751 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2752 Checker.TraverseType(T);
2753 return Checker.Match;
2754}
2755
2756// Find the source range corresponding to the named type in the given
2757// nested-name-specifier, if any.
2759 QualType T,
2760 const CXXScopeSpec &SS) {
2762 for (;;) {
2765 break;
2766 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))
2767 return NNSLoc.castAsTypeLoc().getSourceRange();
2768 // FIXME: This will always be empty.
2769 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2770 }
2771
2772 return SourceRange();
2773}
2774
2776 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2777 TemplateIdAnnotation *TemplateId,
2778 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2779 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2780 IsMemberSpecialization = false;
2781 Invalid = false;
2782
2783 // The sequence of nested types to which we will match up the template
2784 // parameter lists. We first build this list by starting with the type named
2785 // by the nested-name-specifier and walking out until we run out of types.
2786 SmallVector<QualType, 4> NestedTypes;
2787 QualType T;
2788 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2789 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2790 if (CXXRecordDecl *Record =
2791 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2793 else
2794 T = QualType(Qualifier.getAsType(), 0);
2795 }
2796
2797 // If we found an explicit specialization that prevents us from needing
2798 // 'template<>' headers, this will be set to the location of that
2799 // explicit specialization.
2800 SourceLocation ExplicitSpecLoc;
2801
2802 while (!T.isNull()) {
2803 NestedTypes.push_back(T);
2804
2805 // Retrieve the parent of a record type.
2807 // If this type is an explicit specialization, we're done.
2809 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2810 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2811 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2812 ExplicitSpecLoc = Spec->getLocation();
2813 break;
2814 }
2815 } else if (Record->getTemplateSpecializationKind()
2817 ExplicitSpecLoc = Record->getLocation();
2818 break;
2819 }
2820
2821 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2823 else
2824 T = QualType();
2825 continue;
2826 }
2827
2828 if (const TemplateSpecializationType *TST
2830 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2831 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2833 else
2834 T = QualType();
2835 continue;
2836 }
2837 }
2838
2839 // Look one step prior in a dependent template specialization type.
2840 if (const DependentTemplateSpecializationType *DependentTST
2842 if (NestedNameSpecifier NNS =
2843 DependentTST->getDependentTemplateName().getQualifier();
2845 T = QualType(NNS.getAsType(), 0);
2846 else
2847 T = QualType();
2848 continue;
2849 }
2850
2851 // Look one step prior in a dependent name type.
2852 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2853 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2855 T = QualType(NNS.getAsType(), 0);
2856 else
2857 T = QualType();
2858 continue;
2859 }
2860
2861 // Retrieve the parent of an enumeration type.
2862 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2863 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2864 // check here.
2865 EnumDecl *Enum = EnumT->getOriginalDecl();
2866
2867 // Get to the parent type.
2868 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2870 else
2871 T = QualType();
2872 continue;
2873 }
2874
2875 T = QualType();
2876 }
2877 // Reverse the nested types list, since we want to traverse from the outermost
2878 // to the innermost while checking template-parameter-lists.
2879 std::reverse(NestedTypes.begin(), NestedTypes.end());
2880
2881 // C++0x [temp.expl.spec]p17:
2882 // A member or a member template may be nested within many
2883 // enclosing class templates. In an explicit specialization for
2884 // such a member, the member declaration shall be preceded by a
2885 // template<> for each enclosing class template that is
2886 // explicitly specialized.
2887 bool SawNonEmptyTemplateParameterList = false;
2888
2889 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2890 if (SawNonEmptyTemplateParameterList) {
2891 if (!SuppressDiagnostic)
2892 Diag(DeclLoc, diag::err_specialize_member_of_template)
2893 << !Recovery << Range;
2894 Invalid = true;
2895 IsMemberSpecialization = false;
2896 return true;
2897 }
2898
2899 return false;
2900 };
2901
2902 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2903 // Check that we can have an explicit specialization here.
2904 if (CheckExplicitSpecialization(Range, true))
2905 return true;
2906
2907 // We don't have a template header, but we should.
2908 SourceLocation ExpectedTemplateLoc;
2909 if (!ParamLists.empty())
2910 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2911 else
2912 ExpectedTemplateLoc = DeclStartLoc;
2913
2914 if (!SuppressDiagnostic)
2915 Diag(DeclLoc, diag::err_template_spec_needs_header)
2916 << Range
2917 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2918 return false;
2919 };
2920
2921 unsigned ParamIdx = 0;
2922 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2923 ++TypeIdx) {
2924 T = NestedTypes[TypeIdx];
2925
2926 // Whether we expect a 'template<>' header.
2927 bool NeedEmptyTemplateHeader = false;
2928
2929 // Whether we expect a template header with parameters.
2930 bool NeedNonemptyTemplateHeader = false;
2931
2932 // For a dependent type, the set of template parameters that we
2933 // expect to see.
2934 TemplateParameterList *ExpectedTemplateParams = nullptr;
2935
2936 // C++0x [temp.expl.spec]p15:
2937 // A member or a member template may be nested within many enclosing
2938 // class templates. In an explicit specialization for such a member, the
2939 // member declaration shall be preceded by a template<> for each
2940 // enclosing class template that is explicitly specialized.
2943 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2944 ExpectedTemplateParams = Partial->getTemplateParameters();
2945 NeedNonemptyTemplateHeader = true;
2946 } else if (Record->isDependentType()) {
2947 if (Record->getDescribedClassTemplate()) {
2948 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2949 ->getTemplateParameters();
2950 NeedNonemptyTemplateHeader = true;
2951 }
2952 } else if (ClassTemplateSpecializationDecl *Spec
2953 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2954 // C++0x [temp.expl.spec]p4:
2955 // Members of an explicitly specialized class template are defined
2956 // in the same manner as members of normal classes, and not using
2957 // the template<> syntax.
2958 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2959 NeedEmptyTemplateHeader = true;
2960 else
2961 continue;
2962 } else if (Record->getTemplateSpecializationKind()) {
2963 if (Record->getTemplateSpecializationKind()
2965 TypeIdx == NumTypes - 1)
2966 IsMemberSpecialization = true;
2967
2968 continue;
2969 }
2970 } else if (const TemplateSpecializationType *TST
2972 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2973 ExpectedTemplateParams = Template->getTemplateParameters();
2974 NeedNonemptyTemplateHeader = true;
2975 }
2977 // FIXME: We actually could/should check the template arguments here
2978 // against the corresponding template parameter list.
2979 NeedNonemptyTemplateHeader = false;
2980 }
2981
2982 // C++ [temp.expl.spec]p16:
2983 // In an explicit specialization declaration for a member of a class
2984 // template or a member template that appears in namespace scope, the
2985 // member template and some of its enclosing class templates may remain
2986 // unspecialized, except that the declaration shall not explicitly
2987 // specialize a class member template if its enclosing class templates
2988 // are not explicitly specialized as well.
2989 if (ParamIdx < ParamLists.size()) {
2990 if (ParamLists[ParamIdx]->size() == 0) {
2991 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2992 false))
2993 return nullptr;
2994 } else
2995 SawNonEmptyTemplateParameterList = true;
2996 }
2997
2998 if (NeedEmptyTemplateHeader) {
2999 // If we're on the last of the types, and we need a 'template<>' header
3000 // here, then it's a member specialization.
3001 if (TypeIdx == NumTypes - 1)
3002 IsMemberSpecialization = true;
3003
3004 if (ParamIdx < ParamLists.size()) {
3005 if (ParamLists[ParamIdx]->size() > 0) {
3006 // The header has template parameters when it shouldn't. Complain.
3007 if (!SuppressDiagnostic)
3008 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3009 diag::err_template_param_list_matches_nontemplate)
3010 << T
3011 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3012 ParamLists[ParamIdx]->getRAngleLoc())
3014 Invalid = true;
3015 return nullptr;
3016 }
3017
3018 // Consume this template header.
3019 ++ParamIdx;
3020 continue;
3021 }
3022
3023 if (!IsFriend)
3024 if (DiagnoseMissingExplicitSpecialization(
3026 return nullptr;
3027
3028 continue;
3029 }
3030
3031 if (NeedNonemptyTemplateHeader) {
3032 // In friend declarations we can have template-ids which don't
3033 // depend on the corresponding template parameter lists. But
3034 // assume that empty parameter lists are supposed to match this
3035 // template-id.
3036 if (IsFriend && T->isDependentType()) {
3037 if (ParamIdx < ParamLists.size() &&
3039 ExpectedTemplateParams = nullptr;
3040 else
3041 continue;
3042 }
3043
3044 if (ParamIdx < ParamLists.size()) {
3045 // Check the template parameter list, if we can.
3046 if (ExpectedTemplateParams &&
3048 ExpectedTemplateParams,
3049 !SuppressDiagnostic, TPL_TemplateMatch))
3050 Invalid = true;
3051
3052 if (!Invalid &&
3053 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3055 Invalid = true;
3056
3057 ++ParamIdx;
3058 continue;
3059 }
3060
3061 if (!SuppressDiagnostic)
3062 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3063 << T
3065 Invalid = true;
3066 continue;
3067 }
3068 }
3069
3070 // If there were at least as many template-ids as there were template
3071 // parameter lists, then there are no template parameter lists remaining for
3072 // the declaration itself.
3073 if (ParamIdx >= ParamLists.size()) {
3074 if (TemplateId && !IsFriend) {
3075 // We don't have a template header for the declaration itself, but we
3076 // should.
3077 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3078 TemplateId->RAngleLoc));
3079
3080 // Fabricate an empty template parameter list for the invented header.
3082 SourceLocation(), {},
3083 SourceLocation(), nullptr);
3084 }
3085
3086 return nullptr;
3087 }
3088
3089 // If there were too many template parameter lists, complain about that now.
3090 if (ParamIdx < ParamLists.size() - 1) {
3091 bool HasAnyExplicitSpecHeader = false;
3092 bool AllExplicitSpecHeaders = true;
3093 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3094 if (ParamLists[I]->size() == 0)
3095 HasAnyExplicitSpecHeader = true;
3096 else
3097 AllExplicitSpecHeaders = false;
3098 }
3099
3100 if (!SuppressDiagnostic)
3101 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3102 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3103 : diag::err_template_spec_extra_headers)
3104 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3105 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3106
3107 // If there was a specialization somewhere, such that 'template<>' is
3108 // not required, and there were any 'template<>' headers, note where the
3109 // specialization occurred.
3110 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3111 !SuppressDiagnostic)
3112 Diag(ExplicitSpecLoc,
3113 diag::note_explicit_template_spec_does_not_need_header)
3114 << NestedTypes.back();
3115
3116 // We have a template parameter list with no corresponding scope, which
3117 // means that the resulting template declaration can't be instantiated
3118 // properly (we'll end up with dependent nodes when we shouldn't).
3119 if (!AllExplicitSpecHeaders)
3120 Invalid = true;
3121 }
3122
3123 // C++ [temp.expl.spec]p16:
3124 // In an explicit specialization declaration for a member of a class
3125 // template or a member template that ap- pears in namespace scope, the
3126 // member template and some of its enclosing class templates may remain
3127 // unspecialized, except that the declaration shall not explicitly
3128 // specialize a class member template if its en- closing class templates
3129 // are not explicitly specialized as well.
3130 if (ParamLists.back()->size() == 0 &&
3131 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3132 false))
3133 return nullptr;
3134
3135 // Return the last template parameter list, which corresponds to the
3136 // entity being declared.
3137 return ParamLists.back();
3138}
3139
3141 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3142 Diag(Template->getLocation(), diag::note_template_declared_here)
3143 << (isa<FunctionTemplateDecl>(Template)
3144 ? 0
3145 : isa<ClassTemplateDecl>(Template)
3146 ? 1
3147 : isa<VarTemplateDecl>(Template)
3148 ? 2
3149 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3150 << Template->getDeclName();
3151 return;
3152 }
3153
3154 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3155 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3156 IEnd = OST->end();
3157 I != IEnd; ++I)
3158 Diag((*I)->getLocation(), diag::note_template_declared_here)
3159 << 0 << (*I)->getDeclName();
3160
3161 return;
3162 }
3163}
3164
3166 TemplateName BaseTemplate,
3167 SourceLocation TemplateLoc,
3169 auto lookUpCommonType = [&](TemplateArgument T1,
3170 TemplateArgument T2) -> QualType {
3171 // Don't bother looking for other specializations if both types are
3172 // builtins - users aren't allowed to specialize for them
3173 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3174 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3175 {T1, T2});
3176
3181 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3182
3183 EnterExpressionEvaluationContext UnevaluatedContext(
3185 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3187
3188 QualType BaseTemplateInst =
3189 S.CheckTemplateIdType(Keyword, BaseTemplate, TemplateLoc, Args);
3190
3191 if (SFINAE.hasErrorOccurred())
3192 return QualType();
3193
3194 return BaseTemplateInst;
3195 };
3196
3197 // Note A: For the common_type trait applied to a template parameter pack T of
3198 // types, the member type shall be either defined or not present as follows:
3199 switch (Ts.size()) {
3200
3201 // If sizeof...(T) is zero, there shall be no member type.
3202 case 0:
3203 return QualType();
3204
3205 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3206 // pack T. The member typedef-name type shall denote the same type, if any, as
3207 // common_type_t<T0, T0>; otherwise there shall be no member type.
3208 case 1:
3209 return lookUpCommonType(Ts[0], Ts[0]);
3210
3211 // If sizeof...(T) is two, let the first and second types constituting T be
3212 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3213 // as decay_t<T1> and decay_t<T2>, respectively.
3214 case 2: {
3215 QualType T1 = Ts[0].getAsType();
3216 QualType T2 = Ts[1].getAsType();
3217 QualType D1 = S.BuiltinDecay(T1, {});
3218 QualType D2 = S.BuiltinDecay(T2, {});
3219
3220 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3221 // the same type, if any, as common_type_t<D1, D2>.
3222 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3223 return lookUpCommonType(D1, D2);
3224
3225 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3226 // denotes a valid type, let C denote that type.
3227 {
3228 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3229 EnterExpressionEvaluationContext UnevaluatedContext(
3231 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3233
3234 // false
3236 VK_PRValue);
3237 ExprResult Cond = &CondExpr;
3238
3239 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3240 if (ConstRefQual) {
3241 D1.addConst();
3242 D2.addConst();
3243 }
3244
3245 // declval<D1>()
3246 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3247 ExprResult LHS = &LHSExpr;
3248
3249 // declval<D2>()
3250 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3251 ExprResult RHS = &RHSExpr;
3252
3255
3256 // decltype(false ? declval<D1>() : declval<D2>())
3258 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3259
3260 if (Result.isNull() || SFINAE.hasErrorOccurred())
3261 return QualType();
3262
3263 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3264 return S.BuiltinDecay(Result, TemplateLoc);
3265 };
3266
3267 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3268 return Res;
3269
3270 // Let:
3271 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3272 // COND-RES(X, Y) be
3273 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3274
3275 // C++20 only
3276 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3277 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3278 if (!S.Context.getLangOpts().CPlusPlus20)
3279 return QualType();
3280 return CheckConditionalOperands(true);
3281 }
3282 }
3283
3284 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3285 // denote the first, second, and (pack of) remaining types constituting T. Let
3286 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3287 // a type C, the member typedef-name type shall denote the same type, if any,
3288 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3289 default: {
3290 QualType Result = Ts.front().getAsType();
3291 for (auto T : llvm::drop_begin(Ts)) {
3292 Result = lookUpCommonType(Result, T.getAsType());
3293 if (Result.isNull())
3294 return QualType();
3295 }
3296 return Result;
3297 }
3298 }
3299}
3300
3301static bool isInVkNamespace(const RecordType *RT) {
3303 if (!DC)
3304 return false;
3305
3306 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
3307 if (!ND)
3308 return false;
3309
3310 return ND->getQualifiedNameAsString() == "hlsl::vk";
3311}
3312
3314 QualType OperandArg,
3316 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3317 bool Literal = false;
3318 SourceLocation LiteralLoc;
3319 if (isInVkNamespace(RT) && RT->getOriginalDecl()->getName() == "Literal") {
3320 auto SpecDecl =
3321 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3322 assert(SpecDecl);
3323
3324 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3325 QualType ConstantType = LiteralArgs[0].getAsType();
3326 RT = ConstantType->getAsCanonical<RecordType>();
3327 Literal = true;
3328 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3329 }
3330
3331 if (RT && isInVkNamespace(RT) &&
3332 RT->getOriginalDecl()->getName() == "integral_constant") {
3333 auto SpecDecl =
3334 dyn_cast<ClassTemplateSpecializationDecl>(RT->getOriginalDecl());
3335 assert(SpecDecl);
3336
3337 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3338
3339 QualType ConstantType = ConstantArgs[0].getAsType();
3340 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3341
3342 if (Literal)
3344 return SpirvOperand::createConstant(ConstantType, Value);
3345 } else if (Literal) {
3346 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);
3347 return SpirvOperand();
3348 }
3349 }
3350 if (SemaRef.RequireCompleteType(Loc, OperandArg,
3351 diag::err_call_incomplete_argument))
3352 return SpirvOperand();
3353 return SpirvOperand::createType(OperandArg);
3354}
3355
3358 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3359 TemplateArgumentListInfo &TemplateArgs) {
3360 ASTContext &Context = SemaRef.getASTContext();
3361
3362 switch (BTD->getBuiltinTemplateKind()) {
3363 case BTK__make_integer_seq: {
3364 // Specializations of __make_integer_seq<S, T, N> are treated like
3365 // S<T, 0, ..., N-1>.
3366
3367 QualType OrigType = Converted[1].getAsType();
3368 // C++14 [inteseq.intseq]p1:
3369 // T shall be an integer type.
3370 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3371 SemaRef.Diag(TemplateArgs[1].getLocation(),
3372 diag::err_integer_sequence_integral_element_type);
3373 return QualType();
3374 }
3375
3376 TemplateArgument NumArgsArg = Converted[2];
3377 if (NumArgsArg.isDependent())
3378 return QualType();
3379
3380 TemplateArgumentListInfo SyntheticTemplateArgs;
3381 // The type argument, wrapped in substitution sugar, gets reused as the
3382 // first template argument in the synthetic template argument list.
3383 SyntheticTemplateArgs.addArgument(
3386 OrigType, TemplateArgs[1].getLocation())));
3387
3388 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3389 // Expand N into 0 ... N-1.
3390 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3391 I < NumArgs; ++I) {
3392 TemplateArgument TA(Context, I, OrigType);
3393 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3394 TA, OrigType, TemplateArgs[2].getLocation()));
3395 }
3396 } else {
3397 // C++14 [inteseq.make]p1:
3398 // If N is negative the program is ill-formed.
3399 SemaRef.Diag(TemplateArgs[2].getLocation(),
3400 diag::err_integer_sequence_negative_length);
3401 return QualType();
3402 }
3403
3404 // The first template argument will be reused as the template decl that
3405 // our synthetic template arguments will be applied to.
3406 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),
3407 TemplateLoc, SyntheticTemplateArgs);
3408 }
3409
3410 case BTK__type_pack_element: {
3411 // Specializations of
3412 // __type_pack_element<Index, T_1, ..., T_N>
3413 // are treated like T_Index.
3414 assert(Converted.size() == 2 &&
3415 "__type_pack_element should be given an index and a parameter pack");
3416
3417 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3418 if (IndexArg.isDependent() || Ts.isDependent())
3419 return QualType();
3420
3421 llvm::APSInt Index = IndexArg.getAsIntegral();
3422 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3423 "type std::size_t, and hence be non-negative");
3424 // If the Index is out of bounds, the program is ill-formed.
3425 if (Index >= Ts.pack_size()) {
3426 SemaRef.Diag(TemplateArgs[0].getLocation(),
3427 diag::err_type_pack_element_out_of_bounds);
3428 return QualType();
3429 }
3430
3431 // We simply return the type at index `Index`.
3432 int64_t N = Index.getExtValue();
3433 return Ts.getPackAsArray()[N].getAsType();
3434 }
3435
3436 case BTK__builtin_common_type: {
3437 assert(Converted.size() == 4);
3438 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3439 return QualType();
3440
3441 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3442 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3443 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,
3444 TemplateLoc, Ts);
3445 !CT.isNull()) {
3449 CT, TemplateArgs[1].getLocation())));
3450 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3451 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,
3452 TAs);
3453 }
3454 QualType HasNoTypeMember = Converted[2].getAsType();
3455 return HasNoTypeMember;
3456 }
3457
3458 case BTK__hlsl_spirv_type: {
3459 assert(Converted.size() == 4);
3460
3461 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3462 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;
3463 }
3464
3465 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3466 return QualType();
3467
3468 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3469 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3470 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3471
3472 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3473
3475
3476 for (auto &OperandTA : OperandArgs) {
3477 QualType OperandArg = OperandTA.getAsType();
3478 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3479 TemplateArgs[3].getLocation());
3480 if (!Operand.isValid())
3481 return QualType();
3482 Operands.push_back(Operand);
3483 }
3484
3485 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3486 }
3487 case BTK__builtin_dedup_pack: {
3488 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3489 "a parameter pack");
3490 TemplateArgument Ts = Converted[0];
3491 // Delay the computation until we can compute the final result. We choose
3492 // not to remove the duplicates upfront before substitution to keep the code
3493 // simple.
3494 if (Ts.isDependent())
3495 return QualType();
3496 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3498 llvm::SmallDenseSet<QualType> Seen;
3499 // Synthesize a new template argument list, removing duplicates.
3500 for (auto T : Ts.getPackAsArray()) {
3501 assert(T.getKind() == clang::TemplateArgument::Type);
3502 if (!Seen.insert(T.getAsType().getCanonicalType()).second)
3503 continue;
3504 OutArgs.push_back(T);
3505 }
3506 return Context.getSubstBuiltinTemplatePack(
3507 TemplateArgument::CreatePackCopy(Context, OutArgs));
3508 }
3509 }
3510 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3511}
3512
3513/// Determine whether this alias template is "enable_if_t".
3514/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3516 return AliasTemplate->getName() == "enable_if_t" ||
3517 AliasTemplate->getName() == "__enable_if_t";
3518}
3519
3520/// Collect all of the separable terms in the given condition, which
3521/// might be a conjunction.
3522///
3523/// FIXME: The right answer is to convert the logical expression into
3524/// disjunctive normal form, so we can find the first failed term
3525/// within each possible clause.
3526static void collectConjunctionTerms(Expr *Clause,
3527 SmallVectorImpl<Expr *> &Terms) {
3528 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3529 if (BinOp->getOpcode() == BO_LAnd) {
3530 collectConjunctionTerms(BinOp->getLHS(), Terms);
3531 collectConjunctionTerms(BinOp->getRHS(), Terms);
3532 return;
3533 }
3534 }
3535
3536 Terms.push_back(Clause);
3537}
3538
3539// The ranges-v3 library uses an odd pattern of a top-level "||" with
3540// a left-hand side that is value-dependent but never true. Identify
3541// the idiom and ignore that term.
3543 // Top-level '||'.
3544 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3545 if (!BinOp) return Cond;
3546
3547 if (BinOp->getOpcode() != BO_LOr) return Cond;
3548
3549 // With an inner '==' that has a literal on the right-hand side.
3550 Expr *LHS = BinOp->getLHS();
3551 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3552 if (!InnerBinOp) return Cond;
3553
3554 if (InnerBinOp->getOpcode() != BO_EQ ||
3555 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3556 return Cond;
3557
3558 // If the inner binary operation came from a macro expansion named
3559 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3560 // of the '||', which is the real, user-provided condition.
3561 SourceLocation Loc = InnerBinOp->getExprLoc();
3562 if (!Loc.isMacroID()) return Cond;
3563
3564 StringRef MacroName = PP.getImmediateMacroName(Loc);
3565 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3566 return BinOp->getRHS();
3567
3568 return Cond;
3569}
3570
3571namespace {
3572
3573// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3574// within failing boolean expression, such as substituting template parameters
3575// for actual types.
3576class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3577public:
3578 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3579 : Policy(P) {}
3580
3581 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3582 const auto *DR = dyn_cast<DeclRefExpr>(E);
3583 if (DR && DR->getQualifier()) {
3584 // If this is a qualified name, expand the template arguments in nested
3585 // qualifiers.
3586 DR->getQualifier().print(OS, Policy, true);
3587 // Then print the decl itself.
3588 const ValueDecl *VD = DR->getDecl();
3589 OS << VD->getName();
3590 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3591 // This is a template variable, print the expanded template arguments.
3593 OS, IV->getTemplateArgs().asArray(), Policy,
3594 IV->getSpecializedTemplate()->getTemplateParameters());
3595 }
3596 return true;
3597 }
3598 return false;
3599 }
3600
3601private:
3602 const PrintingPolicy Policy;
3603};
3604
3605} // end anonymous namespace
3606
3607std::pair<Expr *, std::string>
3609 Cond = lookThroughRangesV3Condition(PP, Cond);
3610
3611 // Separate out all of the terms in a conjunction.
3613 collectConjunctionTerms(Cond, Terms);
3614
3615 // Determine which term failed.
3616 Expr *FailedCond = nullptr;
3617 for (Expr *Term : Terms) {
3618 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3619
3620 // Literals are uninteresting.
3621 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3622 isa<IntegerLiteral>(TermAsWritten))
3623 continue;
3624
3625 // The initialization of the parameter from the argument is
3626 // a constant-evaluated context.
3629
3630 bool Succeeded;
3631 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3632 !Succeeded) {
3633 FailedCond = TermAsWritten;
3634 break;
3635 }
3636 }
3637 if (!FailedCond)
3638 FailedCond = Cond->IgnoreParenImpCasts();
3639
3640 std::string Description;
3641 {
3642 llvm::raw_string_ostream Out(Description);
3644 Policy.PrintAsCanonical = true;
3645 FailedBooleanConditionPrinterHelper Helper(Policy);
3646 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3647 }
3648 return { FailedCond, Description };
3649}
3650
3652 TemplateName Name,
3653 SourceLocation TemplateLoc,
3654 TemplateArgumentListInfo &TemplateArgs) {
3655 // FIXME: 'getUnderlying' loses SubstTemplateTemplateParm nodes from alias
3656 // template substitutions.
3657 if (DependentTemplateName *DTN =
3658 Name.getUnderlying().getAsDependentTemplateName();
3659 DTN && DTN->getName().getIdentifier())
3660 // When building a template-id where the template-name is dependent,
3661 // assume the template is a type template. Either our assumption is
3662 // correct, or the code is ill-formed and will be diagnosed when the
3663 // dependent name is substituted.
3665 ElaboratedTypeKeyword::None, *DTN, TemplateArgs.arguments());
3666
3667 if (Name.getAsAssumedTemplateName() &&
3668 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3669 return QualType();
3670
3672 DefaultArguments DefaultArgs;
3674 Name.getAsSubstTemplateTemplateParmPack()) {
3675 Template = S->getParameterPack();
3676 } else {
3677 std::tie(Template, DefaultArgs) = Name.getTemplateDeclAndDefaultArgs();
3678 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3679 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3680 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name;
3682 return QualType();
3683 }
3684 }
3685
3686 // Check that the template argument list is well-formed for this
3687 // template.
3689 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3690 DefaultArgs, /*PartialTemplateArgs=*/false,
3691 CTAI,
3692 /*UpdateArgsWithConversions=*/true))
3693 return QualType();
3694
3695 QualType CanonType;
3696
3697 if (isa<TemplateTemplateParmDecl>(Template)) {
3698 // We might have a substituted template template parameter pack. If so,
3699 // build a template specialization type for it.
3701 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3702
3703 // C++0x [dcl.type.elab]p2:
3704 // If the identifier resolves to a typedef-name or the simple-template-id
3705 // resolves to an alias template specialization, the
3706 // elaborated-type-specifier is ill-formed.
3709 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3712 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);
3713 }
3714
3715 // Find the canonical type for this type alias template specialization.
3716 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3717 if (Pattern->isInvalidDecl())
3718 return QualType();
3719
3720 // Only substitute for the innermost template argument list.
3721 MultiLevelTemplateArgumentList TemplateArgLists;
3723 /*Final=*/true);
3724 TemplateArgLists.addOuterRetainedLevels(
3725 AliasTemplate->getTemplateParameters()->getDepth());
3726
3729 *this, /*PointOfInstantiation=*/TemplateLoc,
3730 /*Entity=*/AliasTemplate,
3731 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3732
3733 // Diagnose uses of this alias.
3734 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3735
3736 if (Inst.isInvalid())
3737 return QualType();
3738
3739 std::optional<ContextRAII> SavedContext;
3740 if (!AliasTemplate->getDeclContext()->isFileContext())
3741 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3742
3743 CanonType =
3744 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3745 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3746 if (CanonType.isNull()) {
3747 // If this was enable_if and we failed to find the nested type
3748 // within enable_if in a SFINAE context, dig out the specific
3749 // enable_if condition that failed and present that instead.
3751 if (auto DeductionInfo = isSFINAEContext()) {
3752 if (*DeductionInfo &&
3753 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3754 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3755 diag::err_typename_nested_not_found_enable_if &&
3756 TemplateArgs[0].getArgument().getKind()
3758 Expr *FailedCond;
3759 std::string FailedDescription;
3760 std::tie(FailedCond, FailedDescription) =
3761 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3762
3763 // Remove the old SFINAE diagnostic.
3764 PartialDiagnosticAt OldDiag =
3766 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3767
3768 // Add a new SFINAE diagnostic specifying which condition
3769 // failed.
3770 (*DeductionInfo)->addSFINAEDiagnostic(
3771 OldDiag.first,
3772 PDiag(diag::err_typename_nested_not_found_requirement)
3773 << FailedDescription
3774 << FailedCond->getSourceRange());
3775 }
3776 }
3777 }
3778
3779 return QualType();
3780 }
3781 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3782 CanonType = checkBuiltinTemplateIdType(
3783 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3784 } else if (Name.isDependent() ||
3786 TemplateArgs, CTAI.CanonicalConverted)) {
3787 // This class template specialization is a dependent
3788 // type. Therefore, its canonical type is another class template
3789 // specialization type that contains all of the converted
3790 // arguments in canonical form. This ensures that, e.g., A<T> and
3791 // A<T, T> have identical types when A is declared as:
3792 //
3793 // template<typename T, typename U = T> struct A;
3795 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3796 CTAI.CanonicalConverted);
3797 assert(CanonType->isCanonicalUnqualified());
3798
3799 // This might work out to be a current instantiation, in which
3800 // case the canonical type needs to be the InjectedClassNameType.
3801 //
3802 // TODO: in theory this could be a simple hashtable lookup; most
3803 // changes to CurContext don't change the set of current
3804 // instantiations.
3805 if (isa<ClassTemplateDecl>(Template)) {
3806 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3807 // If we get out to a namespace, we're done.
3808 if (Ctx->isFileContext()) break;
3809
3810 // If this isn't a record, keep looking.
3811 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3812 if (!Record) continue;
3813
3814 // Look for one of the two cases with InjectedClassNameTypes
3815 // and check whether it's the same template.
3816 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3817 !Record->getDescribedClassTemplate())
3818 continue;
3819
3820 // Fetch the injected class name type and check whether its
3821 // injected type is equal to the type we just built.
3823 CanQualType Injected =
3824 Record->getCanonicalTemplateSpecializationType(Context);
3825
3826 if (CanonType != Injected)
3827 continue;
3828
3829 // If so, the canonical type of this TST is the injected
3830 // class name type of the record we just found.
3831 CanonType = ICNT;
3832 break;
3833 }
3834 }
3835 } else if (ClassTemplateDecl *ClassTemplate =
3836 dyn_cast<ClassTemplateDecl>(Template)) {
3837 // Find the class template specialization declaration that
3838 // corresponds to these arguments.
3839 void *InsertPos = nullptr;
3841 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
3842 if (!Decl) {
3843 // This is the first time we have referenced this class template
3844 // specialization. Create the canonical declaration and add it to
3845 // the set of specializations.
3847 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3848 ClassTemplate->getDeclContext(),
3849 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3850 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,
3851 CTAI.StrictPackMatch, nullptr);
3852 ClassTemplate->AddSpecialization(Decl, InsertPos);
3853 if (ClassTemplate->isOutOfLine())
3854 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3855 }
3856
3857 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3858 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3859 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3860 if (!Inst.isInvalid()) {
3862 CTAI.CanonicalConverted,
3863 /*Final=*/false);
3864 InstantiateAttrsForDecl(TemplateArgLists,
3865 ClassTemplate->getTemplatedDecl(), Decl);
3866 }
3867 }
3868
3869 // Diagnose uses of this specialization.
3870 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3871
3872 CanonType = Context.getCanonicalTagType(Decl);
3873 assert(isa<RecordType>(CanonType) &&
3874 "type of non-dependent specialization is not a RecordType");
3875 } else {
3876 llvm_unreachable("Unhandled template kind");
3877 }
3878
3879 // Build the fully-sugared type for this class template
3880 // specialization, which refers back to the class template
3881 // specialization we created or found.
3883 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,
3884 CanonType);
3885}
3886
3888 TemplateNameKind &TNK,
3889 SourceLocation NameLoc,
3890 IdentifierInfo *&II) {
3891 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3892
3893 TemplateName Name = ParsedName.get();
3894 auto *ATN = Name.getAsAssumedTemplateName();
3895 assert(ATN && "not an assumed template name");
3896 II = ATN->getDeclName().getAsIdentifierInfo();
3897
3898 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3899 // Resolved to a type template name.
3900 ParsedName = TemplateTy::make(Name);
3901 TNK = TNK_Type_template;
3902 }
3903}
3904
3906 SourceLocation NameLoc,
3907 bool Diagnose) {
3908 // We assumed this undeclared identifier to be an (ADL-only) function
3909 // template name, but it was used in a context where a type was required.
3910 // Try to typo-correct it now.
3911 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3912 assert(ATN && "not an assumed template name");
3913
3914 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3915 struct CandidateCallback : CorrectionCandidateCallback {
3916 bool ValidateCandidate(const TypoCorrection &TC) override {
3917 return TC.getCorrectionDecl() &&
3919 }
3920 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3921 return std::make_unique<CandidateCallback>(*this);
3922 }
3923 } FilterCCC;
3924
3925 TypoCorrection Corrected =
3926 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3928 if (Corrected && Corrected.getFoundDecl()) {
3929 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3930 << ATN->getDeclName());
3932 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3934 return false;
3935 }
3936
3937 if (Diagnose)
3938 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3939 return true;
3940}
3941
3943 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
3944 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
3945 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
3946 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
3947 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
3948 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
3949 ImplicitTypenameContext AllowImplicitTypename) {
3950 if (SS.isInvalid())
3951 return true;
3952
3953 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3954 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3955
3956 // C++ [temp.res]p3:
3957 // A qualified-id that refers to a type and in which the
3958 // nested-name-specifier depends on a template-parameter (14.6.2)
3959 // shall be prefixed by the keyword typename to indicate that the
3960 // qualified-id denotes a type, forming an
3961 // elaborated-type-specifier (7.1.5.3).
3962 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3963 // C++2a relaxes some of those restrictions in [temp.res]p5.
3965 SS.getScopeRep(), TemplateII);
3967 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3968 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)
3969 << NNS;
3970 if (!getLangOpts().CPlusPlus20)
3971 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3972 } else
3973 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;
3974
3975 // FIXME: This is not quite correct recovery as we don't transform SS
3976 // into the corresponding dependent form (and we don't diagnose missing
3977 // 'template' keywords within SS as a result).
3978 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3979 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3980 TemplateArgsIn, RAngleLoc);
3981 }
3982
3983 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3984 // it's not actually allowed to be used as a type in most cases. Because
3985 // we annotate it before we know whether it's valid, we have to check for
3986 // this case here.
3987 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3988 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3989 Diag(TemplateIILoc,
3990 TemplateKWLoc.isInvalid()
3991 ? diag::err_out_of_line_qualified_id_type_names_constructor
3992 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3993 << TemplateII << 0 /*injected-class-name used as template name*/
3994 << 1 /*if any keyword was present, it was 'template'*/;
3995 }
3996 }
3997
3998 TemplateName Template = TemplateD.get();
3999 if (Template.getAsAssumedTemplateName() &&
4000 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4001 return true;
4002
4003 // Translate the parser's template argument list in our AST format.
4004 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4005 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4006
4007 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4008 assert(SS.getScopeRep() == DTN->getQualifier());
4010 ElaboratedKeyword, *DTN, TemplateArgs.arguments());
4011 // Build type-source information.
4012 TypeLocBuilder TLB;
4015 SpecTL.setElaboratedKeywordLoc(ElaboratedKeywordLoc);
4017 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4018 SpecTL.setTemplateNameLoc(TemplateIILoc);
4019 SpecTL.setLAngleLoc(LAngleLoc);
4020 SpecTL.setRAngleLoc(RAngleLoc);
4021 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4022 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4024 }
4025
4026 QualType SpecTy = CheckTemplateIdType(ElaboratedKeyword, Template,
4027 TemplateIILoc, TemplateArgs);
4028 if (SpecTy.isNull())
4029 return true;
4030
4031 // Build type-source information.
4032 TypeLocBuilder TLB;
4033 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(
4034 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
4035 TemplateIILoc, TemplateArgs);
4036 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));
4037}
4038
4040 TypeSpecifierType TagSpec,
4041 SourceLocation TagLoc,
4042 CXXScopeSpec &SS,
4043 SourceLocation TemplateKWLoc,
4044 TemplateTy TemplateD,
4045 SourceLocation TemplateLoc,
4046 SourceLocation LAngleLoc,
4047 ASTTemplateArgsPtr TemplateArgsIn,
4048 SourceLocation RAngleLoc) {
4049 if (SS.isInvalid())
4050 return TypeResult(true);
4051
4052 TemplateName Template = TemplateD.get();
4053
4054 // Translate the parser's template argument list in our AST format.
4055 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4056 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4057
4058 // Determine the tag kind
4062
4063 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4064 assert(SS.getScopeRep() == DTN->getQualifier());
4066 Keyword, *DTN, TemplateArgs.arguments());
4067
4068 // Build type-source information.
4069 TypeLocBuilder TLB;
4072 SpecTL.setElaboratedKeywordLoc(TagLoc);
4074 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4075 SpecTL.setTemplateNameLoc(TemplateLoc);
4076 SpecTL.setLAngleLoc(LAngleLoc);
4077 SpecTL.setRAngleLoc(RAngleLoc);
4078 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4079 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4081 }
4082
4084 CheckTemplateIdType(Keyword, Template, TemplateLoc, TemplateArgs);
4085 if (Result.isNull())
4086 return TypeResult(true);
4087
4088 // Check the tag kind
4089 if (const RecordType *RT = Result->getAs<RecordType>()) {
4090 RecordDecl *D = RT->getOriginalDecl();
4091
4092 IdentifierInfo *Id = D->getIdentifier();
4093 assert(Id && "templated class must have an identifier");
4094
4096 TagLoc, Id)) {
4097 Diag(TagLoc, diag::err_use_with_wrong_tag)
4098 << Result
4099 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4100 Diag(D->getLocation(), diag::note_previous_use);
4101 }
4102 }
4103
4104 // Provide source-location information for the template specialization.
4105 TypeLocBuilder TLB;
4107 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,
4108 TemplateArgs);
4110}
4111
4112static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4113 NamedDecl *PrevDecl,
4116
4118
4120 unsigned Depth,
4121 unsigned Index) {
4122 switch (Arg.getKind()) {
4130 return false;
4131
4133 QualType Type = Arg.getAsType();
4134 const TemplateTypeParmType *TPT =
4136 return TPT && !Type.hasQualifiers() &&
4137 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4138 }
4139
4141 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4142 if (!DRE || !DRE->getDecl())
4143 return false;
4144 const NonTypeTemplateParmDecl *NTTP =
4145 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4146 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4147 }
4148
4150 const TemplateTemplateParmDecl *TTP =
4151 dyn_cast_or_null<TemplateTemplateParmDecl>(
4153 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4154 }
4155 llvm_unreachable("unexpected kind of template argument");
4156}
4157
4159 TemplateParameterList *SpecParams,
4161 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4162 return false;
4163
4164 unsigned Depth = Params->getDepth();
4165
4166 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4167 TemplateArgument Arg = Args[I];
4168
4169 // If the parameter is a pack expansion, the argument must be a pack
4170 // whose only element is a pack expansion.
4171 if (Params->getParam(I)->isParameterPack()) {
4172 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4173 !Arg.pack_begin()->isPackExpansion())
4174 return false;
4175 Arg = Arg.pack_begin()->getPackExpansionPattern();
4176 }
4177
4178 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4179 return false;
4180
4181 // For NTTPs further specialization is allowed via deduced types, so
4182 // we need to make sure to only reject here if primary template and
4183 // specialization use the same type for the NTTP.
4184 if (auto *SpecNTTP =
4185 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {
4186 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));
4187 if (!NTTP || NTTP->getType().getCanonicalType() !=
4188 SpecNTTP->getType().getCanonicalType())
4189 return false;
4190 }
4191 }
4192
4193 return true;
4194}
4195
4196template<typename PartialSpecDecl>
4197static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4198 if (Partial->getDeclContext()->isDependentContext())
4199 return;
4200
4201 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4202 // for non-substitution-failure issues?
4203 TemplateDeductionInfo Info(Partial->getLocation());
4204 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4205 return;
4206
4207 auto *Template = Partial->getSpecializedTemplate();
4208 S.Diag(Partial->getLocation(),
4209 diag::ext_partial_spec_not_more_specialized_than_primary)
4210 << isa<VarTemplateDecl>(Template);
4211
4212 if (Info.hasSFINAEDiagnostic()) {
4216 SmallString<128> SFINAEArgString;
4217 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4218 S.Diag(Diag.first,
4219 diag::note_partial_spec_not_more_specialized_than_primary)
4220 << SFINAEArgString;
4221 }
4222
4224 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4225 Template->getAssociatedConstraints(TemplateAC);
4226 Partial->getAssociatedConstraints(PartialAC);
4228 TemplateAC);
4229}
4230
4231static void
4233 const llvm::SmallBitVector &DeducibleParams) {
4234 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4235 if (!DeducibleParams[I]) {
4236 NamedDecl *Param = TemplateParams->getParam(I);
4237 if (Param->getDeclName())
4238 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4239 << Param->getDeclName();
4240 else
4241 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4242 << "(anonymous)";
4243 }
4244 }
4245}
4246
4247
4248template<typename PartialSpecDecl>
4250 PartialSpecDecl *Partial) {
4251 // C++1z [temp.class.spec]p8: (DR1495)
4252 // - The specialization shall be more specialized than the primary
4253 // template (14.5.5.2).
4255
4256 // C++ [temp.class.spec]p8: (DR1315)
4257 // - Each template-parameter shall appear at least once in the
4258 // template-id outside a non-deduced context.
4259 // C++1z [temp.class.spec.match]p3 (P0127R2)
4260 // If the template arguments of a partial specialization cannot be
4261 // deduced because of the structure of its template-parameter-list
4262 // and the template-id, the program is ill-formed.
4263 auto *TemplateParams = Partial->getTemplateParameters();
4264 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4265 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4266 TemplateParams->getDepth(), DeducibleParams);
4267
4268 if (!DeducibleParams.all()) {
4269 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4270 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4271 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4272 << (NumNonDeducible > 1)
4273 << SourceRange(Partial->getLocation(),
4274 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4275 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4276 }
4277}
4278
4281 checkTemplatePartialSpecialization(*this, Partial);
4282}
4283
4286 checkTemplatePartialSpecialization(*this, Partial);
4287}
4288
4290 // C++1z [temp.param]p11:
4291 // A template parameter of a deduction guide template that does not have a
4292 // default-argument shall be deducible from the parameter-type-list of the
4293 // deduction guide template.
4294 auto *TemplateParams = TD->getTemplateParameters();
4295 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4296 MarkDeducedTemplateParameters(TD, DeducibleParams);
4297 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4298 // A parameter pack is deducible (to an empty pack).
4299 auto *Param = TemplateParams->getParam(I);
4300 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4301 DeducibleParams[I] = true;
4302 }
4303
4304 if (!DeducibleParams.all()) {
4305 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4306 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4307 << (NumNonDeducible > 1);
4308 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4309 }
4310}
4311
4314 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4316 // D must be variable template id.
4317 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4318 "Variable template specialization is declared with a template id.");
4319
4320 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4321 TemplateArgumentListInfo TemplateArgs =
4322 makeTemplateArgumentListInfo(*this, *TemplateId);
4323 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4324 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4325 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4326
4327 TemplateName Name = TemplateId->Template.get();
4328
4329 // The template-id must name a variable template.
4331 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4332 if (!VarTemplate) {
4333 NamedDecl *FnTemplate;
4334 if (auto *OTS = Name.getAsOverloadedTemplate())
4335 FnTemplate = *OTS->begin();
4336 else
4337 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4338 if (FnTemplate)
4339 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4340 << FnTemplate->getDeclName();
4341 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4343 }
4344
4345 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4346 auto Message = DSA->getMessage();
4347 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4348 << VarTemplate << !Message.empty() << Message;
4349 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4350 }
4351
4352 // Check for unexpanded parameter packs in any of the template arguments.
4353 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4354 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4358 return true;
4359
4360 // Check that the template argument list is well-formed for this
4361 // template.
4363 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4364 /*DefaultArgs=*/{},
4365 /*PartialTemplateArgs=*/false, CTAI,
4366 /*UpdateArgsWithConversions=*/true))
4367 return true;
4368
4369 // Find the variable template (partial) specialization declaration that
4370 // corresponds to these arguments.
4373 TemplateArgs.size(),
4374 CTAI.CanonicalConverted))
4375 return true;
4376
4377 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4378 // we also do them during instantiation.
4379 if (!Name.isDependent() &&
4381 TemplateArgs, CTAI.CanonicalConverted)) {
4382 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4383 << VarTemplate->getDeclName();
4385 }
4386
4387 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4388 TemplateParams, CTAI.CanonicalConverted) &&
4389 (!Context.getLangOpts().CPlusPlus20 ||
4390 !TemplateParams->hasAssociatedConstraints())) {
4391 // C++ [temp.class.spec]p9b3:
4392 //
4393 // -- The argument list of the specialization shall not be identical
4394 // to the implicit argument list of the primary template.
4395 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4396 << /*variable template*/ 1
4397 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4398 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4399 // FIXME: Recover from this by treating the declaration as a
4400 // redeclaration of the primary template.
4401 return true;
4402 }
4403 }
4404
4405 void *InsertPos = nullptr;
4406 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4407
4409 PrevDecl = VarTemplate->findPartialSpecialization(
4410 CTAI.CanonicalConverted, TemplateParams, InsertPos);
4411 else
4412 PrevDecl =
4413 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
4414
4416
4417 // Check whether we can declare a variable template specialization in
4418 // the current scope.
4419 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4420 TemplateNameLoc,
4422 return true;
4423
4424 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4425 // Since the only prior variable template specialization with these
4426 // arguments was referenced but not declared, reuse that
4427 // declaration node as our own, updating its source location and
4428 // the list of outer template parameters to reflect our new declaration.
4429 Specialization = PrevDecl;
4430 Specialization->setLocation(TemplateNameLoc);
4431 PrevDecl = nullptr;
4432 } else if (IsPartialSpecialization) {
4433 // Create a new class template partial specialization declaration node.
4435 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4438 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4439 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4440 CTAI.CanonicalConverted);
4441 Partial->setTemplateArgsAsWritten(TemplateArgs);
4442
4443 if (!PrevPartial)
4444 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4445 Specialization = Partial;
4446
4447 // If we are providing an explicit specialization of a member variable
4448 // template specialization, make a note of that.
4449 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4450 PrevPartial->setMemberSpecialization();
4451
4453 } else {
4454 // Create a new class template specialization declaration node for
4455 // this explicit specialization or friend declaration.
4457 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4458 VarTemplate, DI->getType(), DI, SC, CTAI.CanonicalConverted);
4459 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4460
4461 if (!PrevDecl)
4462 VarTemplate->AddSpecialization(Specialization, InsertPos);
4463 }
4464
4465 // C++ [temp.expl.spec]p6:
4466 // If a template, a member template or the member of a class template is
4467 // explicitly specialized then that specialization shall be declared
4468 // before the first use of that specialization that would cause an implicit
4469 // instantiation to take place, in every translation unit in which such a
4470 // use occurs; no diagnostic is required.
4471 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4472 bool Okay = false;
4473 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4474 // Is there any previous explicit specialization declaration?
4476 Okay = true;
4477 break;
4478 }
4479 }
4480
4481 if (!Okay) {
4482 SourceRange Range(TemplateNameLoc, RAngleLoc);
4483 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4484 << Name << Range;
4485
4486 Diag(PrevDecl->getPointOfInstantiation(),
4487 diag::note_instantiation_required_here)
4488 << (PrevDecl->getTemplateSpecializationKind() !=
4490 return true;
4491 }
4492 }
4493
4494 Specialization->setLexicalDeclContext(CurContext);
4495
4496 // Add the specialization into its lexical context, so that it can
4497 // be seen when iterating through the list of declarations in that
4498 // context. However, specializations are not found by name lookup.
4500
4501 // Note that this is an explicit specialization.
4502 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4503
4504 Previous.clear();
4505 if (PrevDecl)
4506 Previous.addDecl(PrevDecl);
4507 else if (Specialization->isStaticDataMember() &&
4508 Specialization->isOutOfLine())
4509 Specialization->setAccess(VarTemplate->getAccess());
4510
4511 return Specialization;
4512}
4513
4514namespace {
4515/// A partial specialization whose template arguments have matched
4516/// a given template-id.
4517struct PartialSpecMatchResult {
4520};
4521
4522// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4523// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4524static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4525 if (Var->getName() != "format_kind" ||
4526 !Var->getDeclContext()->isStdNamespace())
4527 return false;
4528
4529 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4530 // release in which users can access std::format_kind.
4531 // We can use 20250520 as the final date, see the following commits.
4532 // GCC releases/gcc-15 branch:
4533 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4534 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4535 // GCC master branch:
4536 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4537 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4538 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);
4539}
4540} // end anonymous namespace
4541
4544 SourceLocation TemplateNameLoc,
4545 const TemplateArgumentListInfo &TemplateArgs) {
4546 assert(Template && "A variable template id without template?");
4547
4548 // Check that the template argument list is well-formed for this template.
4551 Template, TemplateNameLoc,
4552 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4553 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4554 /*UpdateArgsWithConversions=*/true))
4555 return true;
4556
4557 // Produce a placeholder value if the specialization is dependent.
4558 if (Template->getDeclContext()->isDependentContext() ||
4560 TemplateArgs, CTAI.CanonicalConverted)) {
4561 if (ParsingInitForAutoVars.empty())
4562 return DeclResult();
4563
4564 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4565 const TemplateArgument &Arg2) {
4566 return Context.isSameTemplateArgument(Arg1, Arg2);
4567 };
4568
4569 if (VarDecl *Var = Template->getTemplatedDecl();
4570 ParsingInitForAutoVars.count(Var) &&
4571 // See comments on this function definition
4572 !IsLibstdcxxStdFormatKind(PP, Var) &&
4573 llvm::equal(
4574 CTAI.CanonicalConverted,
4575 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4576 IsSameTemplateArg)) {
4577 Diag(TemplateNameLoc,
4578 diag::err_auto_variable_cannot_appear_in_own_initializer)
4579 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4580 return true;
4581 }
4582
4584 Template->getPartialSpecializations(PartialSpecs);
4585 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4586 if (ParsingInitForAutoVars.count(Partial) &&
4587 llvm::equal(CTAI.CanonicalConverted,
4588 Partial->getTemplateArgs().asArray(),
4589 IsSameTemplateArg)) {
4590 Diag(TemplateNameLoc,
4591 diag::err_auto_variable_cannot_appear_in_own_initializer)
4592 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4593 << Partial->getType();
4594 return true;
4595 }
4596
4597 return DeclResult();
4598 }
4599
4600 // Find the variable template specialization declaration that
4601 // corresponds to these arguments.
4602 void *InsertPos = nullptr;
4604 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
4605 checkSpecializationReachability(TemplateNameLoc, Spec);
4606 if (Spec->getType()->isUndeducedType()) {
4607 if (ParsingInitForAutoVars.count(Spec))
4608 Diag(TemplateNameLoc,
4609 diag::err_auto_variable_cannot_appear_in_own_initializer)
4610 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4611 << Spec->getType();
4612 else
4613 // We are substituting the initializer of this variable template
4614 // specialization.
4615 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
4616 << Spec << Spec->getType();
4617
4618 return true;
4619 }
4620 // If we already have a variable template specialization, return it.
4621 return Spec;
4622 }
4623
4624 // This is the first time we have referenced this variable template
4625 // specialization. Create the canonical declaration and add it to
4626 // the set of specializations, based on the closest partial specialization
4627 // that it represents. That is,
4628 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4629 const TemplateArgumentList *PartialSpecArgs = nullptr;
4630 bool AmbiguousPartialSpec = false;
4631 typedef PartialSpecMatchResult MatchResult;
4633 SourceLocation PointOfInstantiation = TemplateNameLoc;
4634 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4635 /*ForTakingAddress=*/false);
4636
4637 // 1. Attempt to find the closest partial specialization that this
4638 // specializes, if any.
4639 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4640 // Perhaps better after unification of DeduceTemplateArguments() and
4641 // getMoreSpecializedPartialSpecialization().
4643 Template->getPartialSpecializations(PartialSpecs);
4644
4645 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4646 // C++ [temp.spec.partial.member]p2:
4647 // If the primary member template is explicitly specialized for a given
4648 // (implicit) specialization of the enclosing class template, the partial
4649 // specializations of the member template are ignored for this
4650 // specialization of the enclosing class template. If a partial
4651 // specialization of the member template is explicitly specialized for a
4652 // given (implicit) specialization of the enclosing class template, the
4653 // primary member template and its other partial specializations are still
4654 // considered for this specialization of the enclosing class template.
4655 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4656 !Partial->getMostRecentDecl()->isMemberSpecialization())
4657 continue;
4658
4659 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4660
4662 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);
4664 // Store the failed-deduction information for use in diagnostics, later.
4665 // TODO: Actually use the failed-deduction info?
4666 FailedCandidates.addCandidate().set(
4669 (void)Result;
4670 } else {
4671 Matched.push_back(PartialSpecMatchResult());
4672 Matched.back().Partial = Partial;
4673 Matched.back().Args = Info.takeSugared();
4674 }
4675 }
4676
4677 if (Matched.size() >= 1) {
4678 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4679 if (Matched.size() == 1) {
4680 // -- If exactly one matching specialization is found, the
4681 // instantiation is generated from that specialization.
4682 // We don't need to do anything for this.
4683 } else {
4684 // -- If more than one matching specialization is found, the
4685 // partial order rules (14.5.4.2) are used to determine
4686 // whether one of the specializations is more specialized
4687 // than the others. If none of the specializations is more
4688 // specialized than all of the other matching
4689 // specializations, then the use of the variable template is
4690 // ambiguous and the program is ill-formed.
4692 PEnd = Matched.end();
4693 P != PEnd; ++P) {
4694 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4695 PointOfInstantiation) ==
4696 P->Partial)
4697 Best = P;
4698 }
4699
4700 // Determine if the best partial specialization is more specialized than
4701 // the others.
4702 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4703 PEnd = Matched.end();
4704 P != PEnd; ++P) {
4706 P->Partial, Best->Partial,
4707 PointOfInstantiation) != Best->Partial) {
4708 AmbiguousPartialSpec = true;
4709 break;
4710 }
4711 }
4712 }
4713
4714 // Instantiate using the best variable template partial specialization.
4715 InstantiationPattern = Best->Partial;
4716 PartialSpecArgs = Best->Args;
4717 } else {
4718 // -- If no match is found, the instantiation is generated
4719 // from the primary template.
4720 // InstantiationPattern = Template->getTemplatedDecl();
4721 }
4722
4723 // 2. Create the canonical declaration.
4724 // Note that we do not instantiate a definition until we see an odr-use
4725 // in DoMarkVarDeclReferenced().
4726 // FIXME: LateAttrs et al.?
4728 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4729 CTAI.CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4730 if (!Decl)
4731 return true;
4732
4733 if (AmbiguousPartialSpec) {
4734 // Partial ordering did not produce a clear winner. Complain.
4736 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4737 << Decl;
4738
4739 // Print the matching partial specializations.
4740 for (MatchResult P : Matched)
4741 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4742 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4743 *P.Args);
4744 return true;
4745 }
4746
4748 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4749 Decl->setInstantiationOf(D, PartialSpecArgs);
4750
4751 checkSpecializationReachability(TemplateNameLoc, Decl);
4752
4753 assert(Decl && "No variable template specialization?");
4754 return Decl;
4755}
4756
4758 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4759 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4760 const TemplateArgumentListInfo *TemplateArgs) {
4761
4762 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4763 *TemplateArgs);
4764 if (Decl.isInvalid())
4765 return ExprError();
4766
4767 if (!Decl.get())
4768 return ExprResult();
4769
4770 VarDecl *Var = cast<VarDecl>(Decl.get());
4773 NameInfo.getLoc());
4774
4775 // Build an ordinary singleton decl ref.
4776 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4777}
4778
4780 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4782 const TemplateArgumentListInfo *TemplateArgs) {
4783 assert(Template && "A variable template id without template?");
4784
4785 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4786 Template->templateParameterKind() !=
4788 return ExprResult();
4789
4790 // Check that the template argument list is well-formed for this template.
4793 Template, TemplateLoc,
4794 // FIXME: TemplateArgs will not be modified because
4795 // UpdateArgsWithConversions is false, however, we should
4796 // CheckTemplateArgumentList to be const-correct.
4797 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4798 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4799 /*UpdateArgsWithConversions=*/false))
4800 return true;
4801
4803 R.addDecl(Template);
4804
4805 // FIXME: We model references to variable template and concept parameters
4806 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4807 // data, can generally be used in the same places and work the same way.
4808 // However, it might be cleaner to use a dedicated AST node in the long run.
4811 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),
4812 /*KnownDependent=*/false,
4813 /*KnownInstantiationDependent=*/false);
4814}
4815
4818 Diag(Loc, diag::err_template_missing_args)
4819 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4820 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4821 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4822 }
4823}
4824
4826 bool TemplateKeyword,
4827 TemplateDecl *TD,
4830 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4832}
4833
4836 SourceLocation TemplateKWLoc,
4837 const DeclarationNameInfo &ConceptNameInfo,
4838 NamedDecl *FoundDecl,
4839 ConceptDecl *NamedConcept,
4840 const TemplateArgumentListInfo *TemplateArgs) {
4841 assert(NamedConcept && "A concept template id without a template?");
4842
4843 if (NamedConcept->isInvalidDecl())
4844 return ExprError();
4845
4848 NamedConcept, ConceptNameInfo.getLoc(),
4849 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4850 /*DefaultArgs=*/{},
4851 /*PartialTemplateArgs=*/false, CTAI,
4852 /*UpdateArgsWithConversions=*/false))
4853 return ExprError();
4854
4855 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4856
4858 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4859 CTAI.CanonicalConverted);
4860 ConstraintSatisfaction Satisfaction;
4861 bool AreArgsDependent =
4863 *TemplateArgs, CTAI.CanonicalConverted);
4864 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.CanonicalConverted,
4865 /*Final=*/false);
4867
4870
4871 if (!AreArgsDependent &&
4873 NamedConcept, AssociatedConstraint(NamedConcept->getConstraintExpr()),
4874 MLTAL,
4875 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4876 TemplateArgs->getRAngleLoc()),
4877 Satisfaction))
4878 return ExprError();
4880 Context,
4882 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4885 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4886}
4887
4889 SourceLocation TemplateKWLoc,
4890 LookupResult &R,
4891 bool RequiresADL,
4892 const TemplateArgumentListInfo *TemplateArgs) {
4893 // FIXME: Can we do any checking at this point? I guess we could check the
4894 // template arguments that we have against the template name, if the template
4895 // name refers to a single template. That's not a terribly common case,
4896 // though.
4897 // foo<int> could identify a single function unambiguously
4898 // This approach does NOT work, since f<int>(1);
4899 // gets resolved prior to resorting to overload resolution
4900 // i.e., template<class T> void f(double);
4901 // vs template<class T, class U> void f(U);
4902
4903 // These should be filtered out by our callers.
4904 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4905
4906 // Non-function templates require a template argument list.
4907 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4908 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4910 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4911 return ExprError();
4912 }
4913 }
4914 bool KnownDependent = false;
4915 // In C++1y, check variable template ids.
4916 if (R.getAsSingle<VarTemplateDecl>()) {
4919 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4920 if (Res.isInvalid() || Res.isUsable())
4921 return Res;
4922 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4923 KnownDependent = true;
4924 }
4925
4926 // We don't want lookup warnings at this point.
4928
4929 if (R.getAsSingle<ConceptDecl>()) {
4930 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4932 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4933 }
4934
4935 // Check variable template ids (C++17) and concept template parameters
4936 // (C++26).
4941 TemplateKWLoc, TemplateArgs);
4942
4943 // Function templates
4946 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4947 R.begin(), R.end(), KnownDependent,
4948 /*KnownInstantiationDependent=*/false);
4949 // Model the templates with UnresolvedTemplateTy. The expression should then
4950 // either be transformed in an instantiation or be diagnosed in
4951 // CheckPlaceholderExpr.
4952 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4955
4956 return ULE;
4957}
4958
4960 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4961 const DeclarationNameInfo &NameInfo,
4962 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4963 assert(TemplateArgs || TemplateKWLoc.isValid());
4964
4965 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4966 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4967 /*EnteringContext=*/false, TemplateKWLoc))
4968 return ExprError();
4969
4970 if (R.isAmbiguous())
4971 return ExprError();
4972
4974 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4975
4976 if (R.empty()) {
4978 Diag(NameInfo.getLoc(), diag::err_no_member)
4979 << NameInfo.getName() << DC << SS.getRange();
4980 return ExprError();
4981 }
4982
4983 // If necessary, build an implicit class member access.
4984 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4985 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4986 /*S=*/nullptr);
4987
4988 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4989}
4990
4992 CXXScopeSpec &SS,
4993 SourceLocation TemplateKWLoc,
4994 const UnqualifiedId &Name,
4995 ParsedType ObjectType,
4996 bool EnteringContext,
4998 bool AllowInjectedClassName) {
4999 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5000 Diag(TemplateKWLoc,
5002 diag::warn_cxx98_compat_template_outside_of_template :
5003 diag::ext_template_outside_of_template)
5004 << FixItHint::CreateRemoval(TemplateKWLoc);
5005
5006 if (SS.isInvalid())
5007 return TNK_Non_template;
5008
5009 // Figure out where isTemplateName is going to look.
5010 DeclContext *LookupCtx = nullptr;
5011 if (SS.isNotEmpty())
5012 LookupCtx = computeDeclContext(SS, EnteringContext);
5013 else if (ObjectType)
5014 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5015
5016 // C++0x [temp.names]p5:
5017 // If a name prefixed by the keyword template is not the name of
5018 // a template, the program is ill-formed. [Note: the keyword
5019 // template may not be applied to non-template members of class
5020 // templates. -end note ] [ Note: as is the case with the
5021 // typename prefix, the template prefix is allowed in cases
5022 // where it is not strictly necessary; i.e., when the
5023 // nested-name-specifier or the expression on the left of the ->
5024 // or . is not dependent on a template-parameter, or the use
5025 // does not appear in the scope of a template. -end note]
5026 //
5027 // Note: C++03 was more strict here, because it banned the use of
5028 // the "template" keyword prior to a template-name that was not a
5029 // dependent name. C++ DR468 relaxed this requirement (the
5030 // "template" keyword is now permitted). We follow the C++0x
5031 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5032 bool MemberOfUnknownSpecialization;
5033 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5034 ObjectType, EnteringContext, Result,
5035 MemberOfUnknownSpecialization);
5036 if (TNK != TNK_Non_template) {
5037 // We resolved this to a (non-dependent) template name. Return it.
5038 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5039 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5040 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5041 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5042 // C++14 [class.qual]p2:
5043 // In a lookup in which function names are not ignored and the
5044 // nested-name-specifier nominates a class C, if the name specified
5045 // [...] is the injected-class-name of C, [...] the name is instead
5046 // considered to name the constructor
5047 //
5048 // We don't get here if naming the constructor would be valid, so we
5049 // just reject immediately and recover by treating the
5050 // injected-class-name as naming the template.
5051 Diag(Name.getBeginLoc(),
5052 diag::ext_out_of_line_qualified_id_type_names_constructor)
5053 << Name.Identifier
5054 << 0 /*injected-class-name used as template name*/
5055 << TemplateKWLoc.isValid();
5056 }
5057 return TNK;
5058 }
5059
5060 if (!MemberOfUnknownSpecialization) {
5061 // Didn't find a template name, and the lookup wasn't dependent.
5062 // Do the lookup again to determine if this is a "nothing found" case or
5063 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5064 // need to do this.
5066 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5068 // Tell LookupTemplateName that we require a template so that it diagnoses
5069 // cases where it finds a non-template.
5070 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5071 ? RequiredTemplateKind(TemplateKWLoc)
5073 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
5074 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5075 !R.isAmbiguous()) {
5076 if (LookupCtx)
5077 Diag(Name.getBeginLoc(), diag::err_no_member)
5078 << DNI.getName() << LookupCtx << SS.getRange();
5079 else
5080 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5081 << DNI.getName() << SS.getRange();
5082 }
5083 return TNK_Non_template;
5084 }
5085
5086 NestedNameSpecifier Qualifier = SS.getScopeRep();
5087
5088 switch (Name.getKind()) {
5091 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5093
5096 {Qualifier, Name.OperatorFunctionId.Operator,
5097 TemplateKWLoc.isValid()}));
5098 return TNK_Function_template;
5099
5101 // This is a kind of template name, but can never occur in a dependent
5102 // scope (literal operators can only be declared at namespace scope).
5103 break;
5104
5105 default:
5106 break;
5107 }
5108
5109 // This name cannot possibly name a dependent template. Diagnose this now
5110 // rather than building a dependent template name that can never be valid.
5111 Diag(Name.getBeginLoc(),
5112 diag::err_template_kw_refers_to_dependent_non_template)
5113 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5114 << TemplateKWLoc.isValid() << TemplateKWLoc;
5115 return TNK_Non_template;
5116}
5117
5120 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5121 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5122 const TemplateArgument &Arg = AL.getArgument();
5123 QualType ArgType;
5124 TypeSourceInfo *TSI = nullptr;
5125
5126 // Check template type parameter.
5127 switch(Arg.getKind()) {
5129 // C++ [temp.arg.type]p1:
5130 // A template-argument for a template-parameter which is a
5131 // type shall be a type-id.
5132 ArgType = Arg.getAsType();
5133 TSI = AL.getTypeSourceInfo();
5134 break;
5137 // We have a template type parameter but the template argument
5138 // is a template without any arguments.
5139 SourceRange SR = AL.getSourceRange();
5142 return true;
5143 }
5145 // We have a template type parameter but the template argument is an
5146 // expression; see if maybe it is missing the "typename" keyword.
5147 CXXScopeSpec SS;
5148 DeclarationNameInfo NameInfo;
5149
5150 if (DependentScopeDeclRefExpr *ArgExpr =
5151 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5152 SS.Adopt(ArgExpr->getQualifierLoc());
5153 NameInfo = ArgExpr->getNameInfo();
5154 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5155 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5156 if (ArgExpr->isImplicitAccess()) {
5157 SS.Adopt(ArgExpr->getQualifierLoc());
5158 NameInfo = ArgExpr->getMemberNameInfo();
5159 }
5160 }
5161
5162 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5163 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5164 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
5165
5166 if (Result.getAsSingle<TypeDecl>() ||
5167 Result.wasNotFoundInCurrentInstantiation()) {
5168 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5169 // Suggest that the user add 'typename' before the NNS.
5171 Diag(Loc, getLangOpts().MSVCCompat
5172 ? diag::ext_ms_template_type_arg_missing_typename
5173 : diag::err_template_arg_must_be_type_suggest)
5174 << FixItHint::CreateInsertion(Loc, "typename ");
5176
5177 // Recover by synthesizing a type using the location information that we
5178 // already have.
5180 SS.getScopeRep(), II);
5181 TypeLocBuilder TLB;
5183 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5185 TL.setNameLoc(NameInfo.getLoc());
5186 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5187
5188 // Overwrite our input TemplateArgumentLoc so that we can recover
5189 // properly.
5192
5193 break;
5194 }
5195 }
5196 // fallthrough
5197 [[fallthrough]];
5198 }
5199 default: {
5200 // We allow instantiating a template with template argument packs when
5201 // building deduction guides.
5202 if (Arg.getKind() == TemplateArgument::Pack &&
5203 CodeSynthesisContexts.back().Kind ==
5205 SugaredConverted.push_back(Arg);
5206 CanonicalConverted.push_back(Arg);
5207 return false;
5208 }
5209 // We have a template type parameter but the template argument
5210 // is not a type.
5211 SourceRange SR = AL.getSourceRange();
5212 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5214
5215 return true;
5216 }
5217 }
5218
5219 if (CheckTemplateArgument(TSI))
5220 return true;
5221
5222 // Objective-C ARC:
5223 // If an explicitly-specified template argument type is a lifetime type
5224 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5225 if (getLangOpts().ObjCAutoRefCount &&
5226 ArgType->isObjCLifetimeType() &&
5227 !ArgType.getObjCLifetime()) {
5228 Qualifiers Qs;
5230 ArgType = Context.getQualifiedType(ArgType, Qs);
5231 }
5232
5233 SugaredConverted.push_back(TemplateArgument(ArgType));
5234 CanonicalConverted.push_back(
5236 return false;
5237}
5238
5239/// Substitute template arguments into the default template argument for
5240/// the given template type parameter.
5241///
5242/// \param SemaRef the semantic analysis object for which we are performing
5243/// the substitution.
5244///
5245/// \param Template the template that we are synthesizing template arguments
5246/// for.
5247///
5248/// \param TemplateLoc the location of the template name that started the
5249/// template-id we are checking.
5250///
5251/// \param RAngleLoc the location of the right angle bracket ('>') that
5252/// terminates the template-id.
5253///
5254/// \param Param the template template parameter whose default we are
5255/// substituting into.
5256///
5257/// \param Converted the list of template arguments provided for template
5258/// parameters that precede \p Param in the template parameter list.
5259///
5260/// \param Output the resulting substituted template argument.
5261///
5262/// \returns true if an error occurred.
5264 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5265 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5266 ArrayRef<TemplateArgument> SugaredConverted,
5267 ArrayRef<TemplateArgument> CanonicalConverted,
5268 TemplateArgumentLoc &Output) {
5269 Output = Param->getDefaultArgument();
5270
5271 // If the argument type is dependent, instantiate it now based
5272 // on the previously-computed template arguments.
5273 if (Output.getArgument().isInstantiationDependent()) {
5274 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5275 SugaredConverted,
5276 SourceRange(TemplateLoc, RAngleLoc));
5277 if (Inst.isInvalid())
5278 return true;
5279
5280 // Only substitute for the innermost template argument list.
5281 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5282 /*Final=*/true);
5283 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5284 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5285
5286 bool ForLambdaCallOperator = false;
5287 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5288 ForLambdaCallOperator = Rec->isLambda();
5289 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5290 !ForLambdaCallOperator);
5291
5292 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5293 Param->getDefaultArgumentLoc(),
5294 Param->getDeclName()))
5295 return true;
5296 }
5297
5298 return false;
5299}
5300
5301/// Substitute template arguments into the default template argument for
5302/// the given non-type template parameter.
5303///
5304/// \param SemaRef the semantic analysis object for which we are performing
5305/// the substitution.
5306///
5307/// \param Template the template that we are synthesizing template arguments
5308/// for.
5309///
5310/// \param TemplateLoc the location of the template name that started the
5311/// template-id we are checking.
5312///
5313/// \param RAngleLoc the location of the right angle bracket ('>') that
5314/// terminates the template-id.
5315///
5316/// \param Param the non-type template parameter whose default we are
5317/// substituting into.
5318///
5319/// \param Converted the list of template arguments provided for template
5320/// parameters that precede \p Param in the template parameter list.
5321///
5322/// \returns the substituted template argument, or NULL if an error occurred.
5324 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5325 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5326 ArrayRef<TemplateArgument> SugaredConverted,
5327 ArrayRef<TemplateArgument> CanonicalConverted,
5328 TemplateArgumentLoc &Output) {
5329 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5330 SugaredConverted,
5331 SourceRange(TemplateLoc, RAngleLoc));
5332 if (Inst.isInvalid())
5333 return true;
5334
5335 // Only substitute for the innermost template argument list.
5336 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5337 /*Final=*/true);
5338 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5339 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5340
5341 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5342 EnterExpressionEvaluationContext ConstantEvaluated(
5344 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5345 TemplateArgLists, Output);
5346}
5347
5348/// Substitute template arguments into the default template argument for
5349/// the given template template parameter.
5350///
5351/// \param SemaRef the semantic analysis object for which we are performing
5352/// the substitution.
5353///
5354/// \param Template the template that we are synthesizing template arguments
5355/// for.
5356///
5357/// \param TemplateLoc the location of the template name that started the
5358/// template-id we are checking.
5359///
5360/// \param RAngleLoc the location of the right angle bracket ('>') that
5361/// terminates the template-id.
5362///
5363/// \param Param the template template parameter whose default we are
5364/// substituting into.
5365///
5366/// \param Converted the list of template arguments provided for template
5367/// parameters that precede \p Param in the template parameter list.
5368///
5369/// \param QualifierLoc Will be set to the nested-name-specifier (with
5370/// source-location information) that precedes the template name.
5371///
5372/// \returns the substituted template argument, or NULL if an error occurred.
5374 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5375 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5377 ArrayRef<TemplateArgument> SugaredConverted,
5378 ArrayRef<TemplateArgument> CanonicalConverted,
5379 NestedNameSpecifierLoc &QualifierLoc) {
5381 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5382 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5383 if (Inst.isInvalid())
5384 return TemplateName();
5385
5386 // Only substitute for the innermost template argument list.
5387 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5388 /*Final=*/true);
5389 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5390 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5391
5392 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5393
5394 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5395 QualifierLoc = A.getTemplateQualifierLoc();
5396 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5398 A.getTemplateNameLoc(), TemplateArgLists);
5399}
5400
5402 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5403 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5404 ArrayRef<TemplateArgument> SugaredConverted,
5405 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5406 HasDefaultArg = false;
5407
5408 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5409 if (!hasReachableDefaultArgument(TypeParm))
5410 return TemplateArgumentLoc();
5411
5412 HasDefaultArg = true;
5413 TemplateArgumentLoc Output;
5414 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5415 RAngleLoc, TypeParm, SugaredConverted,
5416 CanonicalConverted, Output))
5417 return TemplateArgumentLoc();
5418 return Output;
5419 }
5420
5421 if (NonTypeTemplateParmDecl *NonTypeParm
5422 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5423 if (!hasReachableDefaultArgument(NonTypeParm))
5424 return TemplateArgumentLoc();
5425
5426 HasDefaultArg = true;
5427 TemplateArgumentLoc Output;
5428 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,
5429 RAngleLoc, NonTypeParm, SugaredConverted,
5430 CanonicalConverted, Output))
5431 return TemplateArgumentLoc();
5432 return Output;
5433 }
5434
5435 TemplateTemplateParmDecl *TempTempParm
5436 = cast<TemplateTemplateParmDecl>(Param);
5437 if (!hasReachableDefaultArgument(TempTempParm))
5438 return TemplateArgumentLoc();
5439
5440 HasDefaultArg = true;
5441 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5442 NestedNameSpecifierLoc QualifierLoc;
5444 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,
5445 SugaredConverted, CanonicalConverted, QualifierLoc);
5446 if (TName.isNull())
5447 return TemplateArgumentLoc();
5448
5449 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5450 QualifierLoc, A.getTemplateNameLoc());
5451}
5452
5453/// Convert a template-argument that we parsed as a type into a template, if
5454/// possible. C++ permits injected-class-names to perform dual service as
5455/// template template arguments and as template type arguments.
5458 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5459 if (!TagLoc)
5460 return TemplateArgumentLoc();
5461
5462 // If this type was written as an injected-class-name, it can be used as a
5463 // template template argument.
5464 // If this type was written as an injected-class-name, it may have been
5465 // converted to a RecordType during instantiation. If the RecordType is
5466 // *not* wrapped in a TemplateSpecializationType and denotes a class
5467 // template specialization, it must have come from an injected-class-name.
5468
5469 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);
5470 if (Name.isNull())
5471 return TemplateArgumentLoc();
5472
5473 return TemplateArgumentLoc(Context, Name,
5474 /*TemplateKWLoc=*/SourceLocation(),
5475 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5476}
5477
5480 SourceLocation TemplateLoc,
5481 SourceLocation RAngleLoc,
5482 unsigned ArgumentPackIndex,
5485 // Check template type parameters.
5486 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5487 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,
5488 CTAI.CanonicalConverted);
5489
5490 const TemplateArgument &Arg = ArgLoc.getArgument();
5491 // Check non-type template parameters.
5492 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5493 // Do substitution on the type of the non-type template parameter
5494 // with the template arguments we've seen thus far. But if the
5495 // template has a dependent context then we cannot substitute yet.
5496 QualType NTTPType = NTTP->getType();
5497 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5498 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5499
5500 if (NTTPType->isInstantiationDependentType() &&
5501 !isa<TemplateTemplateParmDecl>(Template) &&
5502 !Template->getDeclContext()->isDependentContext()) {
5503 // Do substitution on the type of the non-type template parameter.
5504 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5505 CTAI.SugaredConverted,
5506 SourceRange(TemplateLoc, RAngleLoc));
5507 if (Inst.isInvalid())
5508 return true;
5509
5511 /*Final=*/true);
5512 // If the parameter is a pack expansion, expand this slice of the pack.
5513 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5514 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5515 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5516 NTTP->getDeclName());
5517 } else {
5518 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5519 NTTP->getDeclName());
5520 }
5521
5522 // If that worked, check the non-type template parameter type
5523 // for validity.
5524 if (!NTTPType.isNull())
5525 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5526 NTTP->getLocation());
5527 if (NTTPType.isNull())
5528 return true;
5529 }
5530
5531 auto checkExpr = [&](Expr *E) -> Expr * {
5532 TemplateArgument SugaredResult, CanonicalResult;
5533 unsigned CurSFINAEErrors = NumSFINAEErrors;
5535 NTTP, NTTPType, E, SugaredResult, CanonicalResult,
5536 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5537 // If the current template argument causes an error, give up now.
5538 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5539 return nullptr;
5540 CTAI.SugaredConverted.push_back(SugaredResult);
5541 CTAI.CanonicalConverted.push_back(CanonicalResult);
5542 return Res.get();
5543 };
5544
5545 switch (Arg.getKind()) {
5547 llvm_unreachable("Should never see a NULL template argument here");
5548
5550 Expr *E = Arg.getAsExpr();
5551 Expr *R = checkExpr(E);
5552 if (!R)
5553 return true;
5554 // If the resulting expression is new, then use it in place of the
5555 // old expression in the template argument.
5556 if (R != E) {
5557 TemplateArgument TA(R, /*IsCanonical=*/false);
5558 ArgLoc = TemplateArgumentLoc(TA, R);
5559 }
5560 break;
5561 }
5562
5563 // As for the converted NTTP kinds, they still might need another
5564 // conversion, as the new corresponding parameter might be different.
5565 // Ideally, we would always perform substitution starting with sugared types
5566 // and never need these, as we would still have expressions. Since these are
5567 // needed so rarely, it's probably a better tradeoff to just convert them
5568 // back to expressions.
5573 // FIXME: StructuralValue is untested here.
5574 ExprResult R =
5576 assert(R.isUsable());
5577 if (!checkExpr(R.get()))
5578 return true;
5579 break;
5580 }
5581
5584 // We were given a template template argument. It may not be ill-formed;
5585 // see below.
5588 // We have a template argument such as \c T::template X, which we
5589 // parsed as a template template argument. However, since we now
5590 // know that we need a non-type template argument, convert this
5591 // template name into an expression.
5592
5593 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5594 ArgLoc.getTemplateNameLoc());
5595
5596 CXXScopeSpec SS;
5597 SS.Adopt(ArgLoc.getTemplateQualifierLoc());
5598 // FIXME: the template-template arg was a DependentTemplateName,
5599 // so it was provided with a template keyword. However, its source
5600 // location is not stored in the template argument structure.
5601 SourceLocation TemplateKWLoc;
5603 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5604 nullptr);
5605
5606 // If we parsed the template argument as a pack expansion, create a
5607 // pack expansion expression.
5609 E = ActOnPackExpansion(E.get(), ArgLoc.getTemplateEllipsisLoc());
5610 if (E.isInvalid())
5611 return true;
5612 }
5613
5614 TemplateArgument SugaredResult, CanonicalResult;
5616 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,
5617 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);
5618 if (E.isInvalid())
5619 return true;
5620
5621 CTAI.SugaredConverted.push_back(SugaredResult);
5622 CTAI.CanonicalConverted.push_back(CanonicalResult);
5623 break;
5624 }
5625
5626 // We have a template argument that actually does refer to a class
5627 // template, alias template, or template template parameter, and
5628 // therefore cannot be a non-type template argument.
5629 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)
5630 << ArgLoc.getSourceRange();
5632
5633 return true;
5634
5636 // We have a non-type template parameter but the template
5637 // argument is a type.
5638
5639 // C++ [temp.arg]p2:
5640 // In a template-argument, an ambiguity between a type-id and
5641 // an expression is resolved to a type-id, regardless of the
5642 // form of the corresponding template-parameter.
5643 //
5644 // We warn specifically about this case, since it can be rather
5645 // confusing for users.
5646 QualType T = Arg.getAsType();
5647 SourceRange SR = ArgLoc.getSourceRange();
5648 if (T->isFunctionType())
5649 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5650 else
5651 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5653 return true;
5654 }
5655
5657 llvm_unreachable("Caller must expand template argument packs");
5658 }
5659
5660 return false;
5661 }
5662
5663
5664 // Check template template parameters.
5665 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5666
5667 TemplateParameterList *Params = TempParm->getTemplateParameters();
5668 if (TempParm->isExpandedParameterPack())
5669 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5670
5671 // Substitute into the template parameter list of the template
5672 // template parameter, since previously-supplied template arguments
5673 // may appear within the template template parameter.
5674 //
5675 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5676 {
5677 // Set up a template instantiation context.
5679 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5680 CTAI.SugaredConverted,
5681 SourceRange(TemplateLoc, RAngleLoc));
5682 if (Inst.isInvalid())
5683 return true;
5684
5685 Params = SubstTemplateParams(
5686 Params, CurContext,
5688 /*Final=*/true),
5689 /*EvaluateConstraints=*/false);
5690 if (!Params)
5691 return true;
5692 }
5693
5694 // C++1z [temp.local]p1: (DR1004)
5695 // When [the injected-class-name] is used [...] as a template-argument for
5696 // a template template-parameter [...] it refers to the class template
5697 // itself.
5698 if (Arg.getKind() == TemplateArgument::Type) {
5700 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());
5701 if (!ConvertedArg.getArgument().isNull())
5702 ArgLoc = ConvertedArg;
5703 }
5704
5705 switch (Arg.getKind()) {
5707 llvm_unreachable("Should never see a NULL template argument here");
5708
5711 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,
5712 CTAI.PartialOrdering,
5713 &CTAI.StrictPackMatch))
5714 return true;
5715
5716 CTAI.SugaredConverted.push_back(Arg);
5717 CTAI.CanonicalConverted.push_back(
5719 break;
5720
5723 auto Kind = 0;
5724 switch (TempParm->templateParameterKind()) {
5726 Kind = 1;
5727 break;
5729 Kind = 2;
5730 break;
5731 default:
5732 break;
5733 }
5734
5735 // We have a template template parameter but the template
5736 // argument does not refer to a template.
5737 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)
5738 << Kind << getLangOpts().CPlusPlus11;
5739 return true;
5740 }
5741
5746 llvm_unreachable("non-type argument with template template parameter");
5747
5749 llvm_unreachable("Caller must expand template argument packs");
5750 }
5751
5752 return false;
5753}
5754
5755/// Diagnose a missing template argument.
5756template<typename TemplateParmDecl>
5758 TemplateDecl *TD,
5759 const TemplateParmDecl *D,
5761 // Dig out the most recent declaration of the template parameter; there may be
5762 // declarations of the template that are more recent than TD.
5763 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5764 ->getTemplateParameters()
5765 ->getParam(D->getIndex()));
5766
5767 // If there's a default argument that's not reachable, diagnose that we're
5768 // missing a module import.
5770 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5771 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5772 D->getDefaultArgumentLoc(), Modules,
5774 /*Recover*/true);
5775 return true;
5776 }
5777
5778 // FIXME: If there's a more recent default argument that *is* visible,
5779 // diagnose that it was declared too late.
5780
5782
5783 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5784 << /*not enough args*/0
5786 << TD;
5787 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5788 return true;
5789}
5790
5791/// Check that the given template argument list is well-formed
5792/// for specializing the given template.
5794 TemplateDecl *Template, SourceLocation TemplateLoc,
5795 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5796 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5797 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5798
5800 *ConstraintsNotSatisfied = false;
5801
5802 // Make a copy of the template arguments for processing. Only make the
5803 // changes at the end when successful in matching the arguments to the
5804 // template.
5805 TemplateArgumentListInfo NewArgs = TemplateArgs;
5806
5808
5809 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5810
5811 // C++23 [temp.arg.general]p1:
5812 // [...] The type and form of each template-argument specified in
5813 // a template-id shall match the type and form specified for the
5814 // corresponding parameter declared by the template in its
5815 // template-parameter-list.
5816 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5817 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5818 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5819 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5820 LocalInstantiationScope InstScope(*this, true);
5821 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5822 ParamEnd = Params->end(),
5823 Param = ParamBegin;
5824 Param != ParamEnd;
5825 /* increment in loop */) {
5826 if (size_t ParamIdx = Param - ParamBegin;
5827 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5828 // All written arguments should have been consumed by this point.
5829 assert(ArgIdx == NumArgs && "bad default argument deduction");
5830 if (ParamIdx == DefaultArgs.StartPos) {
5831 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5832 // Default arguments from a DeducedTemplateName are already converted.
5833 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5834 CTAI.SugaredConverted.push_back(DefArg);
5835 CTAI.CanonicalConverted.push_back(
5837 ++Param;
5838 }
5839 continue;
5840 }
5841 }
5842
5843 // If we have an expanded parameter pack, make sure we don't have too
5844 // many arguments.
5845 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {
5846 if (*Expansions == SugaredArgumentPack.size()) {
5847 // We're done with this parameter pack. Pack up its arguments and add
5848 // them to the list.
5849 CTAI.SugaredConverted.push_back(
5850 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5851 SugaredArgumentPack.clear();
5852
5853 CTAI.CanonicalConverted.push_back(
5854 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5855 CanonicalArgumentPack.clear();
5856
5857 // This argument is assigned to the next parameter.
5858 ++Param;
5859 continue;
5860 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5861 // Not enough arguments for this parameter pack.
5862 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5863 << /*not enough args*/0
5865 << Template;
5867 return true;
5868 }
5869 }
5870
5871 // Check for builtins producing template packs in this context, we do not
5872 // support them yet.
5873 if (const NonTypeTemplateParmDecl *NTTP =
5874 dyn_cast<NonTypeTemplateParmDecl>(*Param);
5875 NTTP && NTTP->isPackExpansion()) {
5876 auto TL = NTTP->getTypeSourceInfo()
5877 ->getTypeLoc()
5880 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);
5881 for (const auto &UPP : Unexpanded) {
5882 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5883 if (!TST)
5884 continue;
5885 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5886 // Expanding a built-in pack in this context is not yet supported.
5887 Diag(TL.getEllipsisLoc(),
5888 diag::err_unsupported_builtin_template_pack_expansion)
5889 << TST->getTemplateName();
5890 return true;
5891 }
5892 }
5893
5894 if (ArgIdx < NumArgs) {
5895 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5896 bool NonPackParameter =
5897 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5898 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5899
5900 if (ArgIsExpansion && CTAI.MatchingTTP) {
5901 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5902 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5903 ++Param) {
5904 TemplateArgument &Arg = Args[Param - First];
5905 Arg = ArgLoc.getArgument();
5906 if (!(*Param)->isTemplateParameterPack() ||
5907 getExpandedPackSize(*Param))
5908 Arg = Arg.getPackExpansionPattern();
5909 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5910 SaveAndRestore _1(CTAI.PartialOrdering, false);
5911 SaveAndRestore _2(CTAI.MatchingTTP, true);
5912 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5913 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5915 return true;
5916 Arg = NewArgLoc.getArgument();
5917 CTAI.CanonicalConverted.back().setIsDefaulted(
5919 CTAI.CanonicalConverted,
5920 Params->getDepth()));
5921 }
5922 ArgLoc =
5924 ArgLoc.getLocInfo());
5925 } else {
5926 SaveAndRestore _1(CTAI.PartialOrdering, false);
5927 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5928 RAngleLoc, SugaredArgumentPack.size(), CTAI,
5930 return true;
5931 CTAI.CanonicalConverted.back().setIsDefaulted(
5933 *Param, CTAI.CanonicalConverted,
5934 Params->getDepth()));
5935 if (ArgIsExpansion && NonPackParameter) {
5936 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5937 // alias template or concept, and it's not part of a parameter pack.
5938 // This can't be canonicalized, so reject it now.
5939 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Template)) {
5940 Diag(ArgLoc.getLocation(),
5941 diag::err_template_expansion_into_fixed_list)
5942 << (isa<ConceptDecl>(Template) ? 1 : 0)
5943 << ArgLoc.getSourceRange();
5945 return true;
5946 }
5947 }
5948 }
5949
5950 // We're now done with this argument.
5951 ++ArgIdx;
5952
5953 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
5954 // Directly convert the remaining arguments, because we don't know what
5955 // parameters they'll match up with.
5956
5957 if (!SugaredArgumentPack.empty()) {
5958 // If we were part way through filling in an expanded parameter pack,
5959 // fall back to just producing individual arguments.
5960 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),
5961 SugaredArgumentPack.begin(),
5962 SugaredArgumentPack.end());
5963 SugaredArgumentPack.clear();
5964
5965 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),
5966 CanonicalArgumentPack.begin(),
5967 CanonicalArgumentPack.end());
5968 CanonicalArgumentPack.clear();
5969 }
5970
5971 while (ArgIdx < NumArgs) {
5972 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5973 CTAI.SugaredConverted.push_back(Arg);
5974 CTAI.CanonicalConverted.push_back(
5976 ++ArgIdx;
5977 }
5978
5979 return false;
5980 }
5981
5982 if ((*Param)->isTemplateParameterPack()) {
5983 // The template parameter was a template parameter pack, so take the
5984 // deduced argument and place it on the argument pack. Note that we
5985 // stay on the same template parameter so that we can deduce more
5986 // arguments.
5987 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());
5988 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());
5989 } else {
5990 // Move to the next template parameter.
5991 ++Param;
5992 }
5993 continue;
5994 }
5995
5996 // If we're checking a partial template argument list, we're done.
5997 if (PartialTemplateArgs) {
5998 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5999 CTAI.SugaredConverted.push_back(
6000 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6001 CTAI.CanonicalConverted.push_back(
6002 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6003 }
6004 return false;
6005 }
6006
6007 // If we have a template parameter pack with no more corresponding
6008 // arguments, just break out now and we'll fill in the argument pack below.
6009 if ((*Param)->isTemplateParameterPack()) {
6010 assert(!getExpandedPackSize(*Param) &&
6011 "Should have dealt with this already");
6012
6013 // A non-expanded parameter pack before the end of the parameter list
6014 // only occurs for an ill-formed template parameter list, unless we've
6015 // got a partial argument list for a function template, so just bail out.
6016 if (Param + 1 != ParamEnd) {
6017 assert(
6018 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6019 "Concept templates must have parameter packs at the end.");
6020 return true;
6021 }
6022
6023 CTAI.SugaredConverted.push_back(
6024 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6025 SugaredArgumentPack.clear();
6026
6027 CTAI.CanonicalConverted.push_back(
6028 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6029 CanonicalArgumentPack.clear();
6030
6031 ++Param;
6032 continue;
6033 }
6034
6035 // Check whether we have a default argument.
6036 bool HasDefaultArg;
6037
6038 // Retrieve the default template argument from the template
6039 // parameter. For each kind of template parameter, we substitute the
6040 // template arguments provided thus far and any "outer" template arguments
6041 // (when the template parameter was part of a nested template) into
6042 // the default argument.
6044 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,
6045 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);
6046
6047 if (Arg.getArgument().isNull()) {
6048 if (!HasDefaultArg) {
6049 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
6050 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6051 NewArgs);
6052 if (NonTypeTemplateParmDecl *NTTP =
6053 dyn_cast<NonTypeTemplateParmDecl>(*Param))
6054 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6055 NewArgs);
6056 return diagnoseMissingArgument(*this, TemplateLoc, Template,
6057 cast<TemplateTemplateParmDecl>(*Param),
6058 NewArgs);
6059 }
6060 return true;
6061 }
6062
6063 // Introduce an instantiation record that describes where we are using
6064 // the default template argument. We're not actually instantiating a
6065 // template here, we just create this object to put a note into the
6066 // context stack.
6067 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6068 CTAI.SugaredConverted,
6069 SourceRange(TemplateLoc, RAngleLoc));
6070 if (Inst.isInvalid())
6071 return true;
6072
6073 SaveAndRestore _1(CTAI.PartialOrdering, false);
6074 SaveAndRestore _2(CTAI.MatchingTTP, false);
6075 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6076 // Check the default template argument.
6077 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6078 CTAI, CTAK_Specified))
6079 return true;
6080
6081 CTAI.SugaredConverted.back().setIsDefaulted(true);
6082 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6083
6084 // Core issue 150 (assumed resolution): if this is a template template
6085 // parameter, keep track of the default template arguments from the
6086 // template definition.
6087 if (isTemplateTemplateParameter)
6088 NewArgs.addArgument(Arg);
6089
6090 // Move to the next template parameter and argument.
6091 ++Param;
6092 ++ArgIdx;
6093 }
6094
6095 // If we're performing a partial argument substitution, allow any trailing
6096 // pack expansions; they might be empty. This can happen even if
6097 // PartialTemplateArgs is false (the list of arguments is complete but
6098 // still dependent).
6099 if (CTAI.MatchingTTP ||
6102 while (ArgIdx < NumArgs &&
6103 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6104 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6105 CTAI.SugaredConverted.push_back(Arg);
6106 CTAI.CanonicalConverted.push_back(
6108 }
6109 }
6110
6111 // If we have any leftover arguments, then there were too many arguments.
6112 // Complain and fail.
6113 if (ArgIdx < NumArgs) {
6114 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6115 << /*too many args*/1
6117 << Template
6118 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6120 return true;
6121 }
6122
6123 // No problems found with the new argument list, propagate changes back
6124 // to caller.
6125 if (UpdateArgsWithConversions)
6126 TemplateArgs = std::move(NewArgs);
6127
6128 if (!PartialTemplateArgs) {
6129 // Setup the context/ThisScope for the case where we are needing to
6130 // re-instantiate constraints outside of normal instantiation.
6131 DeclContext *NewContext = Template->getDeclContext();
6132
6133 // If this template is in a template, make sure we extract the templated
6134 // decl.
6135 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6136 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6137 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6138
6139 Qualifiers ThisQuals;
6140 if (const auto *Method =
6141 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6142 ThisQuals = Method->getMethodQualifiers();
6143
6144 ContextRAII Context(*this, NewContext);
6145 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6146
6148 Template, NewContext, /*Final=*/false, CTAI.CanonicalConverted,
6149 /*RelativeToPrimary=*/true,
6150 /*Pattern=*/nullptr,
6151 /*ForConceptInstantiation=*/true);
6153 Template, MLTAL,
6154 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6157 return true;
6158 }
6159 }
6160
6161 return false;
6162}
6163
6164namespace {
6165 class UnnamedLocalNoLinkageFinder
6166 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6167 {
6168 Sema &S;
6169 SourceRange SR;
6170
6172
6173 public:
6174 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6175
6176 bool Visit(QualType T) {
6177 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6178 }
6179
6180#define TYPE(Class, Parent) \
6181 bool Visit##Class##Type(const Class##Type *);
6182#define ABSTRACT_TYPE(Class, Parent) \
6183 bool Visit##Class##Type(const Class##Type *) { return false; }
6184#define NON_CANONICAL_TYPE(Class, Parent) \
6185 bool Visit##Class##Type(const Class##Type *) { return false; }
6186#include "clang/AST/TypeNodes.inc"
6187
6188 bool VisitTagDecl(const TagDecl *Tag);
6189 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6190 };
6191} // end anonymous namespace
6192
6193bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6194 return false;
6195}
6196
6197bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6198 return Visit(T->getElementType());
6199}
6200
6201bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6202 return Visit(T->getPointeeType());
6203}
6204
6205bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6206 const BlockPointerType* T) {
6207 return Visit(T->getPointeeType());
6208}
6209
6210bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6211 const LValueReferenceType* T) {
6212 return Visit(T->getPointeeType());
6213}
6214
6215bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6216 const RValueReferenceType* T) {
6217 return Visit(T->getPointeeType());
6218}
6219
6220bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6221 const MemberPointerType *T) {
6222 if (Visit(T->getPointeeType()))
6223 return true;
6224 if (auto *RD = T->getMostRecentCXXRecordDecl())
6225 return VisitTagDecl(RD);
6226 return VisitNestedNameSpecifier(T->getQualifier());
6227}
6228
6229bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6230 const ConstantArrayType* T) {
6231 return Visit(T->getElementType());
6232}
6233
6234bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6235 const IncompleteArrayType* T) {
6236 return Visit(T->getElementType());
6237}
6238
6239bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6240 const VariableArrayType* T) {
6241 return Visit(T->getElementType());
6242}
6243
6244bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6245 const DependentSizedArrayType* T) {
6246 return Visit(T->getElementType());
6247}
6248
6249bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6251 return Visit(T->getElementType());
6252}
6253
6254bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6255 const DependentSizedMatrixType *T) {
6256 return Visit(T->getElementType());
6257}
6258
6259bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6261 return Visit(T->getPointeeType());
6262}
6263
6264bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6265 return Visit(T->getElementType());
6266}
6267
6268bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6269 const DependentVectorType *T) {
6270 return Visit(T->getElementType());
6271}
6272
6273bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6274 return Visit(T->getElementType());
6275}
6276
6277bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6278 const ConstantMatrixType *T) {
6279 return Visit(T->getElementType());
6280}
6281
6282bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6283 const FunctionProtoType* T) {
6284 for (const auto &A : T->param_types()) {
6285 if (Visit(A))
6286 return true;
6287 }
6288
6289 return Visit(T->getReturnType());
6290}
6291
6292bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6293 const FunctionNoProtoType* T) {
6294 return Visit(T->getReturnType());
6295}
6296
6297bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6298 const UnresolvedUsingType*) {
6299 return false;
6300}
6301
6302bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6303 return false;
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6307 return Visit(T->getUnmodifiedType());
6308}
6309
6310bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6311 return false;
6312}
6313
6314bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6315 const PackIndexingType *) {
6316 return false;
6317}
6318
6319bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6320 const UnaryTransformType*) {
6321 return false;
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6325 return Visit(T->getDeducedType());
6326}
6327
6328bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6330 return Visit(T->getDeducedType());
6331}
6332
6333bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6334 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6335}
6336
6337bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6338 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6339}
6340
6341bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6342 const TemplateTypeParmType*) {
6343 return false;
6344}
6345
6346bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6348 return false;
6349}
6350
6351bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6353 return false;
6354}
6355
6356bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6358 return false;
6359}
6360
6361bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6362 const InjectedClassNameType* T) {
6363 return VisitTagDecl(T->getOriginalDecl()->getDefinitionOrSelf());
6364}
6365
6366bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6367 const DependentNameType* T) {
6368 return VisitNestedNameSpecifier(T->getQualifier());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6373 return VisitNestedNameSpecifier(T->getDependentTemplateName().getQualifier());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6377 const PackExpansionType* T) {
6378 return Visit(T->getPattern());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6382 return false;
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6386 const ObjCInterfaceType *) {
6387 return false;
6388}
6389
6390bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6391 const ObjCObjectPointerType *) {
6392 return false;
6393}
6394
6395bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6396 return Visit(T->getValueType());
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6404 return false;
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6408 const ArrayParameterType *T) {
6409 return VisitConstantArrayType(T);
6410}
6411
6412bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6413 const DependentBitIntType *T) {
6414 return false;
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6418 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6419 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus11
6420 ? diag::warn_cxx98_compat_template_arg_local_type
6421 : diag::ext_template_arg_local_type)
6422 << S.Context.getCanonicalTagType(Tag) << SR;
6423 return true;
6424 }
6425
6426 if (!Tag->hasNameForLinkage()) {
6427 S.Diag(SR.getBegin(),
6428 S.getLangOpts().CPlusPlus11 ?
6429 diag::warn_cxx98_compat_template_arg_unnamed_type :
6430 diag::ext_template_arg_unnamed_type) << SR;
6431 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6432 return true;
6433 }
6434
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6439 NestedNameSpecifier NNS) {
6440 switch (NNS.getKind()) {
6445 return false;
6447 return Visit(QualType(NNS.getAsType(), 0));
6448 }
6449 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6450}
6451
6452bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6454 if (T->hasContainedType() && Visit(T->getContainedType()))
6455 return true;
6456 return Visit(T->getWrappedType());
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6460 const HLSLInlineSpirvType *T) {
6461 for (auto &Operand : T->getOperands())
6462 if (Operand.isConstant() && Operand.isLiteral())
6463 if (Visit(Operand.getResultType()))
6464 return true;
6465 return false;
6466}
6467
6469 assert(ArgInfo && "invalid TypeSourceInfo");
6470 QualType Arg = ArgInfo->getType();
6471 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6472 QualType CanonArg = Context.getCanonicalType(Arg);
6473
6474 if (CanonArg->isVariablyModifiedType()) {
6475 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6477 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6478 }
6479
6480 // C++03 [temp.arg.type]p2:
6481 // A local type, a type with no linkage, an unnamed type or a type
6482 // compounded from any of these types shall not be used as a
6483 // template-argument for a template type-parameter.
6484 //
6485 // C++11 allows these, and even in C++03 we allow them as an extension with
6486 // a warning.
6487 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6488 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6489 (void)Finder.Visit(CanonArg);
6490 }
6491
6492 return false;
6493}
6494
6498 NPV_Error
6500
6501/// Determine whether the given template argument is a null pointer
6502/// value of the appropriate type.
6505 QualType ParamType, Expr *Arg,
6506 Decl *Entity = nullptr) {
6507 if (Arg->isValueDependent() || Arg->isTypeDependent())
6508 return NPV_NotNullPointer;
6509
6510 // dllimport'd entities aren't constant but are available inside of template
6511 // arguments.
6512 if (Entity && Entity->hasAttr<DLLImportAttr>())
6513 return NPV_NotNullPointer;
6514
6515 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6516 llvm_unreachable(
6517 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6518
6519 if (!S.getLangOpts().CPlusPlus11)
6520 return NPV_NotNullPointer;
6521
6522 // Determine whether we have a constant expression.
6524 if (ArgRV.isInvalid())
6525 return NPV_Error;
6526 Arg = ArgRV.get();
6527
6528 Expr::EvalResult EvalResult;
6530 EvalResult.Diag = &Notes;
6531 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6532 EvalResult.HasSideEffects) {
6533 SourceLocation DiagLoc = Arg->getExprLoc();
6534
6535 // If our only note is the usual "invalid subexpression" note, just point
6536 // the caret at its location rather than producing an essentially
6537 // redundant note.
6538 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6539 diag::note_invalid_subexpr_in_const_expr) {
6540 DiagLoc = Notes[0].first;
6541 Notes.clear();
6542 }
6543
6544 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6545 << Arg->getType() << Arg->getSourceRange();
6546 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6547 S.Diag(Notes[I].first, Notes[I].second);
6548
6550 return NPV_Error;
6551 }
6552
6553 // C++11 [temp.arg.nontype]p1:
6554 // - an address constant expression of type std::nullptr_t
6555 if (Arg->getType()->isNullPtrType())
6556 return NPV_NullPointer;
6557
6558 // - a constant expression that evaluates to a null pointer value (4.10); or
6559 // - a constant expression that evaluates to a null member pointer value
6560 // (4.11); or
6561 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6562 (EvalResult.Val.isMemberPointer() &&
6563 !EvalResult.Val.getMemberPointerDecl())) {
6564 // If our expression has an appropriate type, we've succeeded.
6565 bool ObjCLifetimeConversion;
6566 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6567 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6568 ObjCLifetimeConversion))
6569 return NPV_NullPointer;
6570
6571 // The types didn't match, but we know we got a null pointer; complain,
6572 // then recover as if the types were correct.
6573 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6574 << Arg->getType() << ParamType << Arg->getSourceRange();
6576 return NPV_NullPointer;
6577 }
6578
6579 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6580 // We found a pointer that isn't null, but doesn't refer to an object.
6581 // We could just return NPV_NotNullPointer, but we can print a better
6582 // message with the information we have here.
6583 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6584 << EvalResult.Val.getAsString(S.Context, ParamType);
6586 return NPV_Error;
6587 }
6588
6589 // If we don't have a null pointer value, but we do have a NULL pointer
6590 // constant, suggest a cast to the appropriate type.
6592 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6593 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6594 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6596 ")");
6598 return NPV_NullPointer;
6599 }
6600
6601 // FIXME: If we ever want to support general, address-constant expressions
6602 // as non-type template arguments, we should return the ExprResult here to
6603 // be interpreted by the caller.
6604 return NPV_NotNullPointer;
6605}
6606
6607/// Checks whether the given template argument is compatible with its
6608/// template parameter.
6609static bool
6611 QualType ParamType, Expr *ArgIn,
6612 Expr *Arg, QualType ArgType) {
6613 bool ObjCLifetimeConversion;
6614 if (ParamType->isPointerType() &&
6615 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6616 S.IsQualificationConversion(ArgType, ParamType, false,
6617 ObjCLifetimeConversion)) {
6618 // For pointer-to-object types, qualification conversions are
6619 // permitted.
6620 } else {
6621 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6622 if (!ParamRef->getPointeeType()->isFunctionType()) {
6623 // C++ [temp.arg.nontype]p5b3:
6624 // For a non-type template-parameter of type reference to
6625 // object, no conversions apply. The type referred to by the
6626 // reference may be more cv-qualified than the (otherwise
6627 // identical) type of the template- argument. The
6628 // template-parameter is bound directly to the
6629 // template-argument, which shall be an lvalue.
6630
6631 // FIXME: Other qualifiers?
6632 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6633 unsigned ArgQuals = ArgType.getCVRQualifiers();
6634
6635 if ((ParamQuals | ArgQuals) != ParamQuals) {
6636 S.Diag(Arg->getBeginLoc(),
6637 diag::err_template_arg_ref_bind_ignores_quals)
6638 << ParamType << Arg->getType() << Arg->getSourceRange();
6640 return true;
6641 }
6642 }
6643 }
6644
6645 // At this point, the template argument refers to an object or
6646 // function with external linkage. We now need to check whether the
6647 // argument and parameter types are compatible.
6648 if (!S.Context.hasSameUnqualifiedType(ArgType,
6649 ParamType.getNonReferenceType())) {
6650 // We can't perform this conversion or binding.
6651 if (ParamType->isReferenceType())
6652 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6653 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6654 else
6655 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6656 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6658 return true;
6659 }
6660 }
6661
6662 return false;
6663}
6664
6665/// Checks whether the given template argument is the address
6666/// of an object or function according to C++ [temp.arg.nontype]p1.
6668 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6669 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6670 bool Invalid = false;
6671 Expr *Arg = ArgIn;
6672 QualType ArgType = Arg->getType();
6673
6674 bool AddressTaken = false;
6675 SourceLocation AddrOpLoc;
6676 if (S.getLangOpts().MicrosoftExt) {
6677 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6678 // dereference and address-of operators.
6679 Arg = Arg->IgnoreParenCasts();
6680
6681 bool ExtWarnMSTemplateArg = false;
6682 UnaryOperatorKind FirstOpKind;
6683 SourceLocation FirstOpLoc;
6684 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6685 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6686 if (UnOpKind == UO_Deref)
6687 ExtWarnMSTemplateArg = true;
6688 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6689 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6690 if (!AddrOpLoc.isValid()) {
6691 FirstOpKind = UnOpKind;
6692 FirstOpLoc = UnOp->getOperatorLoc();
6693 }
6694 } else
6695 break;
6696 }
6697 if (FirstOpLoc.isValid()) {
6698 if (ExtWarnMSTemplateArg)
6699 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6700 << ArgIn->getSourceRange();
6701
6702 if (FirstOpKind == UO_AddrOf)
6703 AddressTaken = true;
6704 else if (Arg->getType()->isPointerType()) {
6705 // We cannot let pointers get dereferenced here, that is obviously not a
6706 // constant expression.
6707 assert(FirstOpKind == UO_Deref);
6708 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6709 << Arg->getSourceRange();
6710 }
6711 }
6712 } else {
6713 // See through any implicit casts we added to fix the type.
6714 Arg = Arg->IgnoreImpCasts();
6715
6716 // C++ [temp.arg.nontype]p1:
6717 //
6718 // A template-argument for a non-type, non-template
6719 // template-parameter shall be one of: [...]
6720 //
6721 // -- the address of an object or function with external
6722 // linkage, including function templates and function
6723 // template-ids but excluding non-static class members,
6724 // expressed as & id-expression where the & is optional if
6725 // the name refers to a function or array, or if the
6726 // corresponding template-parameter is a reference; or
6727
6728 // In C++98/03 mode, give an extension warning on any extra parentheses.
6729 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6730 bool ExtraParens = false;
6731 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6732 if (!Invalid && !ExtraParens) {
6733 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6734 << Arg->getSourceRange();
6735 ExtraParens = true;
6736 }
6737
6738 Arg = Parens->getSubExpr();
6739 }
6740
6741 while (SubstNonTypeTemplateParmExpr *subst =
6742 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6743 Arg = subst->getReplacement()->IgnoreImpCasts();
6744
6745 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6746 if (UnOp->getOpcode() == UO_AddrOf) {
6747 Arg = UnOp->getSubExpr();
6748 AddressTaken = true;
6749 AddrOpLoc = UnOp->getOperatorLoc();
6750 }
6751 }
6752
6753 while (SubstNonTypeTemplateParmExpr *subst =
6754 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6755 Arg = subst->getReplacement()->IgnoreImpCasts();
6756 }
6757
6758 ValueDecl *Entity = nullptr;
6759 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6760 Entity = DRE->getDecl();
6761 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6762 Entity = CUE->getGuidDecl();
6763
6764 // If our parameter has pointer type, check for a null template value.
6765 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6766 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6767 Entity)) {
6768 case NPV_NullPointer:
6769 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6770 SugaredConverted = TemplateArgument(ParamType,
6771 /*isNullPtr=*/true);
6772 CanonicalConverted =
6774 /*isNullPtr=*/true);
6775 return false;
6776
6777 case NPV_Error:
6778 return true;
6779
6780 case NPV_NotNullPointer:
6781 break;
6782 }
6783 }
6784
6785 // Stop checking the precise nature of the argument if it is value dependent,
6786 // it should be checked when instantiated.
6787 if (Arg->isValueDependent()) {
6788 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6789 CanonicalConverted =
6790 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6791 return false;
6792 }
6793
6794 if (!Entity) {
6795 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6796 << Arg->getSourceRange();
6798 return true;
6799 }
6800
6801 // Cannot refer to non-static data members
6802 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6803 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6804 << Entity << Arg->getSourceRange();
6806 return true;
6807 }
6808
6809 // Cannot refer to non-static member functions
6810 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6811 if (!Method->isStatic()) {
6812 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6813 << Method << Arg->getSourceRange();
6815 return true;
6816 }
6817 }
6818
6819 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6820 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6821 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6822
6823 // A non-type template argument must refer to an object or function.
6824 if (!Func && !Var && !Guid) {
6825 // We found something, but we don't know specifically what it is.
6826 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6827 << Arg->getSourceRange();
6828 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6829 return true;
6830 }
6831
6832 // Address / reference template args must have external linkage in C++98.
6833 if (Entity->getFormalLinkage() == Linkage::Internal) {
6834 S.Diag(Arg->getBeginLoc(),
6835 S.getLangOpts().CPlusPlus11
6836 ? diag::warn_cxx98_compat_template_arg_object_internal
6837 : diag::ext_template_arg_object_internal)
6838 << !Func << Entity << Arg->getSourceRange();
6839 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6840 << !Func;
6841 } else if (!Entity->hasLinkage()) {
6842 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6843 << !Func << Entity << Arg->getSourceRange();
6844 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6845 << !Func;
6846 return true;
6847 }
6848
6849 if (Var) {
6850 // A value of reference type is not an object.
6851 if (Var->getType()->isReferenceType()) {
6852 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6853 << Var->getType() << Arg->getSourceRange();
6855 return true;
6856 }
6857
6858 // A template argument must have static storage duration.
6859 if (Var->getTLSKind()) {
6860 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6861 << Arg->getSourceRange();
6862 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6863 return true;
6864 }
6865 }
6866
6867 if (AddressTaken && ParamType->isReferenceType()) {
6868 // If we originally had an address-of operator, but the
6869 // parameter has reference type, complain and (if things look
6870 // like they will work) drop the address-of operator.
6871 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6872 ParamType.getNonReferenceType())) {
6873 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6874 << ParamType;
6876 return true;
6877 }
6878
6879 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6880 << ParamType
6881 << FixItHint::CreateRemoval(AddrOpLoc);
6883
6884 ArgType = Entity->getType();
6885 }
6886
6887 // If the template parameter has pointer type, either we must have taken the
6888 // address or the argument must decay to a pointer.
6889 if (!AddressTaken && ParamType->isPointerType()) {
6890 if (Func) {
6891 // Function-to-pointer decay.
6892 ArgType = S.Context.getPointerType(Func->getType());
6893 } else if (Entity->getType()->isArrayType()) {
6894 // Array-to-pointer decay.
6895 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6896 } else {
6897 // If the template parameter has pointer type but the address of
6898 // this object was not taken, complain and (possibly) recover by
6899 // taking the address of the entity.
6900 ArgType = S.Context.getPointerType(Entity->getType());
6901 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6902 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6903 << ParamType;
6905 return true;
6906 }
6907
6908 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6909 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6910
6912 }
6913 }
6914
6915 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6916 Arg, ArgType))
6917 return true;
6918
6919 // Create the template argument.
6920 SugaredConverted = TemplateArgument(Entity, ParamType);
6921 CanonicalConverted =
6922 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6923 S.Context.getCanonicalType(ParamType));
6924 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6925 return false;
6926}
6927
6928/// Checks whether the given template argument is a pointer to
6929/// member constant according to C++ [temp.arg.nontype]p1.
6931 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6932 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6933 bool Invalid = false;
6934
6935 Expr *Arg = ResultArg;
6936 bool ObjCLifetimeConversion;
6937
6938 // C++ [temp.arg.nontype]p1:
6939 //
6940 // A template-argument for a non-type, non-template
6941 // template-parameter shall be one of: [...]
6942 //
6943 // -- a pointer to member expressed as described in 5.3.1.
6944 DeclRefExpr *DRE = nullptr;
6945
6946 // In C++98/03 mode, give an extension warning on any extra parentheses.
6947 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6948 bool ExtraParens = false;
6949 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6950 if (!Invalid && !ExtraParens) {
6951 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)
6952 << Arg->getSourceRange();
6953 ExtraParens = true;
6954 }
6955
6956 Arg = Parens->getSubExpr();
6957 }
6958
6959 while (SubstNonTypeTemplateParmExpr *subst =
6960 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6961 Arg = subst->getReplacement()->IgnoreImpCasts();
6962
6963 // A pointer-to-member constant written &Class::member.
6964 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6965 if (UnOp->getOpcode() == UO_AddrOf) {
6966 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6967 if (DRE && !DRE->getQualifier())
6968 DRE = nullptr;
6969 }
6970 }
6971 // A constant of pointer-to-member type.
6972 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6973 ValueDecl *VD = DRE->getDecl();
6974 if (VD->getType()->isMemberPointerType()) {
6975 if (isa<NonTypeTemplateParmDecl>(VD)) {
6976 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6977 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6978 CanonicalConverted =
6979 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6980 } else {
6981 SugaredConverted = TemplateArgument(VD, ParamType);
6982 CanonicalConverted =
6983 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6984 S.Context.getCanonicalType(ParamType));
6985 }
6986 return Invalid;
6987 }
6988 }
6989
6990 DRE = nullptr;
6991 }
6992
6993 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6994
6995 // Check for a null pointer value.
6996 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6997 Entity)) {
6998 case NPV_Error:
6999 return true;
7000 case NPV_NullPointer:
7001 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7002 SugaredConverted = TemplateArgument(ParamType,
7003 /*isNullPtr*/ true);
7004 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7005 /*isNullPtr*/ true);
7006 return false;
7007 case NPV_NotNullPointer:
7008 break;
7009 }
7010
7011 if (S.IsQualificationConversion(ResultArg->getType(),
7012 ParamType.getNonReferenceType(), false,
7013 ObjCLifetimeConversion)) {
7014 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7015 ResultArg->getValueKind())
7016 .get();
7017 } else if (!S.Context.hasSameUnqualifiedType(
7018 ResultArg->getType(), ParamType.getNonReferenceType())) {
7019 // We can't perform this conversion.
7020 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7021 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7023 return true;
7024 }
7025
7026 if (!DRE)
7027 return S.Diag(Arg->getBeginLoc(),
7028 diag::err_template_arg_not_pointer_to_member_form)
7029 << Arg->getSourceRange();
7030
7031 if (isa<FieldDecl>(DRE->getDecl()) ||
7032 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7033 isa<CXXMethodDecl>(DRE->getDecl())) {
7034 assert((isa<FieldDecl>(DRE->getDecl()) ||
7035 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7036 cast<CXXMethodDecl>(DRE->getDecl())
7037 ->isImplicitObjectMemberFunction()) &&
7038 "Only non-static member pointers can make it here");
7039
7040 // Okay: this is the address of a non-static member, and therefore
7041 // a member pointer constant.
7042 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7043 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7044 CanonicalConverted =
7045 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7046 } else {
7047 ValueDecl *D = DRE->getDecl();
7048 SugaredConverted = TemplateArgument(D, ParamType);
7049 CanonicalConverted =
7050 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7051 S.Context.getCanonicalType(ParamType));
7052 }
7053 return Invalid;
7054 }
7055
7056 // We found something else, but we don't know specifically what it is.
7057 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7058 << Arg->getSourceRange();
7059 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7060 return true;
7061}
7062
7063/// Check a template argument against its corresponding
7064/// non-type template parameter.
7065///
7066/// This routine implements the semantics of C++ [temp.arg.nontype].
7067/// If an error occurred, it returns ExprError(); otherwise, it
7068/// returns the converted template argument. \p ParamType is the
7069/// type of the non-type template parameter after it has been instantiated.
7071 Expr *Arg,
7072 TemplateArgument &SugaredConverted,
7073 TemplateArgument &CanonicalConverted,
7074 bool StrictCheck,
7076 SourceLocation StartLoc = Arg->getBeginLoc();
7077 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);
7078 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7079 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7080 DeductionArg = NewDeductionArg;
7081 if (ArgPE) {
7082 // Recreate a pack expansion if we unwrapped one.
7083 Arg = new (Context) PackExpansionExpr(
7084 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7085 } else {
7086 Arg = DeductionArg;
7087 }
7088 };
7089
7090 // If the parameter type somehow involves auto, deduce the type now.
7091 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7092 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7093 // During template argument deduction, we allow 'decltype(auto)' to
7094 // match an arbitrary dependent argument.
7095 // FIXME: The language rules don't say what happens in this case.
7096 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7097 // expression is merely instantiation-dependent; is this enough?
7098 if (DeductionArg->isTypeDependent()) {
7099 auto *AT = dyn_cast<AutoType>(DeducedT);
7100 if (AT && AT->isDecltypeAuto()) {
7101 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7102 CanonicalConverted = TemplateArgument(
7103 Context.getCanonicalTemplateArgument(SugaredConverted));
7104 return Arg;
7105 }
7106 }
7107
7108 // When checking a deduced template argument, deduce from its type even if
7109 // the type is dependent, in order to check the types of non-type template
7110 // arguments line up properly in partial ordering.
7111 TypeSourceInfo *TSI =
7112 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7113 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7114 InitializedEntity Entity =
7117 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7118 Expr *Inits[1] = {DeductionArg};
7119 ParamType =
7120 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7121 if (ParamType.isNull())
7122 return ExprError();
7123 } else {
7124 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7125 Param->getTemplateDepth() + 1);
7126 ParamType = QualType();
7128 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7129 /*DependentDeduction=*/true,
7130 // We do not check constraints right now because the
7131 // immediately-declared constraint of the auto type is
7132 // also an associated constraint, and will be checked
7133 // along with the other associated constraints after
7134 // checking the template argument list.
7135 /*IgnoreConstraints=*/true);
7137 return ExprError();
7139 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7140 Diag(Arg->getExprLoc(),
7141 diag::err_non_type_template_parm_type_deduction_failure)
7142 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7143 << Arg->getSourceRange();
7144 }
7146 return ExprError();
7147 }
7148 }
7149 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7150 // an error. The error message normally references the parameter
7151 // declaration, but here we'll pass the argument location because that's
7152 // where the parameter type is deduced.
7153 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7154 if (ParamType.isNull()) {
7156 return ExprError();
7157 }
7158 }
7159
7160 // We should have already dropped all cv-qualifiers by now.
7161 assert(!ParamType.hasQualifiers() &&
7162 "non-type template parameter type cannot be qualified");
7163
7164 // If either the parameter has a dependent type or the argument is
7165 // type-dependent, there's nothing we can check now.
7166 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7167 // Force the argument to the type of the parameter to maintain invariants.
7169 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7170 ParamType->isLValueReferenceType() ? VK_LValue
7171 : ParamType->isRValueReferenceType() ? VK_XValue
7172 : VK_PRValue);
7173 if (E.isInvalid())
7174 return ExprError();
7175 setDeductionArg(E.get());
7176 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7177 CanonicalConverted = TemplateArgument(
7178 Context.getCanonicalTemplateArgument(SugaredConverted));
7179 return Arg;
7180 }
7181
7182 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7183 if (CTAK == CTAK_Deduced && !StrictCheck &&
7184 (ParamType->isReferenceType()
7186 DeductionArg->getType())
7187 : !Context.hasSameUnqualifiedType(ParamType,
7188 DeductionArg->getType()))) {
7189 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7190 // we should actually be checking the type of the template argument in P,
7191 // not the type of the template argument deduced from A, against the
7192 // template parameter type.
7193 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7194 << Arg->getType() << ParamType.getUnqualifiedType();
7196 return ExprError();
7197 }
7198
7199 // If the argument is a pack expansion, we don't know how many times it would
7200 // expand. If we continue checking the argument, this will make the template
7201 // definition ill-formed if it would be ill-formed for any number of
7202 // expansions during instantiation time. When partial ordering or matching
7203 // template template parameters, this is exactly what we want. Otherwise, the
7204 // normal template rules apply: we accept the template if it would be valid
7205 // for any number of expansions (i.e. none).
7206 if (ArgPE && !StrictCheck) {
7207 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7208 CanonicalConverted = TemplateArgument(
7209 Context.getCanonicalTemplateArgument(SugaredConverted));
7210 return Arg;
7211 }
7212
7213 // Avoid making a copy when initializing a template parameter of class type
7214 // from a template parameter object of the same type. This is going beyond
7215 // the standard, but is required for soundness: in
7216 // template<A a> struct X { X *p; X<a> *q; };
7217 // ... we need p and q to have the same type.
7218 //
7219 // Similarly, don't inject a call to a copy constructor when initializing
7220 // from a template parameter of the same type.
7221 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7222 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7223 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7224 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7225 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7226
7227 SugaredConverted = TemplateArgument(TPO, ParamType);
7228 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7229 ParamType.getCanonicalType());
7230 return Arg;
7231 }
7232 if (isa<NonTypeTemplateParmDecl>(ND)) {
7233 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7234 CanonicalConverted =
7235 Context.getCanonicalTemplateArgument(SugaredConverted);
7236 return Arg;
7237 }
7238 }
7239
7240 // The initialization of the parameter from the argument is
7241 // a constant-evaluated context.
7244
7245 bool IsConvertedConstantExpression = true;
7246 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {
7248 StartLoc, /*DirectInit=*/false, DeductionArg);
7249 Expr *Inits[1] = {DeductionArg};
7250 InitializedEntity Entity =
7252 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7253 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7254 if (Result.isInvalid() || !Result.get())
7255 return ExprError();
7257 if (Result.isInvalid() || !Result.get())
7258 return ExprError();
7259 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7260 /*DiscardedValue=*/false,
7261 /*IsConstexpr=*/true,
7262 /*IsTemplateArgument=*/true)
7263 .get());
7264 IsConvertedConstantExpression = false;
7265 }
7266
7267 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7268 // C++17 [temp.arg.nontype]p1:
7269 // A template-argument for a non-type template parameter shall be
7270 // a converted constant expression of the type of the template-parameter.
7271 APValue Value;
7272 ExprResult ArgResult;
7273 if (IsConvertedConstantExpression) {
7275 DeductionArg, ParamType,
7276 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);
7277 assert(!ArgResult.isUnset());
7278 if (ArgResult.isInvalid()) {
7280 return ExprError();
7281 }
7282 } else {
7283 ArgResult = DeductionArg;
7284 }
7285
7286 // For a value-dependent argument, CheckConvertedConstantExpression is
7287 // permitted (and expected) to be unable to determine a value.
7288 if (ArgResult.get()->isValueDependent()) {
7289 setDeductionArg(ArgResult.get());
7290 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7291 CanonicalConverted =
7292 Context.getCanonicalTemplateArgument(SugaredConverted);
7293 return Arg;
7294 }
7295
7296 APValue PreNarrowingValue;
7298 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/
7299 false, PreNarrowingValue);
7300 if (ArgResult.isInvalid())
7301 return ExprError();
7302 setDeductionArg(ArgResult.get());
7303
7304 if (Value.isLValue()) {
7305 APValue::LValueBase Base = Value.getLValueBase();
7306 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7307 // For a non-type template-parameter of pointer or reference type,
7308 // the value of the constant expression shall not refer to
7309 assert(ParamType->isPointerOrReferenceType() ||
7310 ParamType->isNullPtrType());
7311 // -- a temporary object
7312 // -- a string literal
7313 // -- the result of a typeid expression, or
7314 // -- a predefined __func__ variable
7315 if (Base &&
7316 (!VD ||
7317 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7318 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7319 << Arg->getSourceRange();
7320 return ExprError();
7321 }
7322
7323 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7324 VD->getType()->isArrayType() &&
7325 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7326 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7327 if (ArgPE) {
7328 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7329 CanonicalConverted =
7330 Context.getCanonicalTemplateArgument(SugaredConverted);
7331 } else {
7332 SugaredConverted = TemplateArgument(VD, ParamType);
7333 CanonicalConverted =
7334 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7335 ParamType.getCanonicalType());
7336 }
7337 return Arg;
7338 }
7339
7340 // -- a subobject [until C++20]
7341 if (!getLangOpts().CPlusPlus20) {
7342 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7343 Value.isLValueOnePastTheEnd()) {
7344 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7345 << Value.getAsString(Context, ParamType);
7346 return ExprError();
7347 }
7348 assert((VD || !ParamType->isReferenceType()) &&
7349 "null reference should not be a constant expression");
7350 assert((!VD || !ParamType->isNullPtrType()) &&
7351 "non-null value of type nullptr_t?");
7352 }
7353 }
7354
7355 if (Value.isAddrLabelDiff())
7356 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7357
7358 if (ArgPE) {
7359 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7360 CanonicalConverted =
7361 Context.getCanonicalTemplateArgument(SugaredConverted);
7362 } else {
7363 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7364 CanonicalConverted =
7366 }
7367 return Arg;
7368 }
7369
7370 // C++ [temp.arg.nontype]p5:
7371 // The following conversions are performed on each expression used
7372 // as a non-type template-argument. If a non-type
7373 // template-argument cannot be converted to the type of the
7374 // corresponding template-parameter then the program is
7375 // ill-formed.
7376 if (ParamType->isIntegralOrEnumerationType()) {
7377 // C++11:
7378 // -- for a non-type template-parameter of integral or
7379 // enumeration type, conversions permitted in a converted
7380 // constant expression are applied.
7381 //
7382 // C++98:
7383 // -- for a non-type template-parameter of integral or
7384 // enumeration type, integral promotions (4.5) and integral
7385 // conversions (4.7) are applied.
7386
7387 if (getLangOpts().CPlusPlus11) {
7388 // C++ [temp.arg.nontype]p1:
7389 // A template-argument for a non-type, non-template template-parameter
7390 // shall be one of:
7391 //
7392 // -- for a non-type template-parameter of integral or enumeration
7393 // type, a converted constant expression of the type of the
7394 // template-parameter; or
7395 llvm::APSInt Value;
7397 DeductionArg, ParamType, Value, CCEKind::TemplateArg);
7398 if (ArgResult.isInvalid())
7399 return ExprError();
7400 setDeductionArg(ArgResult.get());
7401
7402 // We can't check arbitrary value-dependent arguments.
7403 if (DeductionArg->isValueDependent()) {
7404 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7405 CanonicalConverted =
7406 Context.getCanonicalTemplateArgument(SugaredConverted);
7407 return Arg;
7408 }
7409
7410 // Widen the argument value to sizeof(parameter type). This is almost
7411 // always a no-op, except when the parameter type is bool. In
7412 // that case, this may extend the argument from 1 bit to 8 bits.
7413 QualType IntegerType = ParamType;
7414 if (const auto *ED = IntegerType->getAsEnumDecl())
7415 IntegerType = ED->getIntegerType();
7416 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7417 ? Context.getIntWidth(IntegerType)
7418 : Context.getTypeSize(IntegerType));
7419
7420 if (ArgPE) {
7421 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7422 CanonicalConverted =
7423 Context.getCanonicalTemplateArgument(SugaredConverted);
7424 } else {
7425 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7426 CanonicalConverted = TemplateArgument(
7427 Context, Value, Context.getCanonicalType(ParamType));
7428 }
7429 return Arg;
7430 }
7431
7432 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7433 if (ArgResult.isInvalid())
7434 return ExprError();
7435 DeductionArg = ArgResult.get();
7436
7437 QualType ArgType = DeductionArg->getType();
7438
7439 // C++ [temp.arg.nontype]p1:
7440 // A template-argument for a non-type, non-template
7441 // template-parameter shall be one of:
7442 //
7443 // -- an integral constant-expression of integral or enumeration
7444 // type; or
7445 // -- the name of a non-type template-parameter; or
7446 llvm::APSInt Value;
7447 if (!ArgType->isIntegralOrEnumerationType()) {
7448 Diag(StartLoc, diag::err_template_arg_not_integral_or_enumeral)
7449 << ArgType << DeductionArg->getSourceRange();
7451 return ExprError();
7452 } else if (!DeductionArg->isValueDependent()) {
7453 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7454 QualType T;
7455
7456 public:
7457 TmplArgICEDiagnoser(QualType T) : T(T) { }
7458
7459 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7460 SourceLocation Loc) override {
7461 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7462 }
7463 } Diagnoser(ArgType);
7464
7465 DeductionArg =
7466 VerifyIntegerConstantExpression(DeductionArg, &Value, Diagnoser)
7467 .get();
7468 if (!DeductionArg)
7469 return ExprError();
7470 }
7471
7472 // From here on out, all we care about is the unqualified form
7473 // of the argument type.
7474 ArgType = ArgType.getUnqualifiedType();
7475
7476 // Try to convert the argument to the parameter's type.
7477 if (Context.hasSameType(ParamType, ArgType)) {
7478 // Okay: no conversion necessary
7479 } else if (ParamType->isBooleanType()) {
7480 // This is an integral-to-boolean conversion.
7481 DeductionArg =
7482 ImpCastExprToType(DeductionArg, ParamType, CK_IntegralToBoolean)
7483 .get();
7484 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7485 !ParamType->isEnumeralType()) {
7486 // This is an integral promotion or conversion.
7487 DeductionArg =
7488 ImpCastExprToType(DeductionArg, ParamType, CK_IntegralCast).get();
7489 } else {
7490 // We can't perform this conversion.
7491 Diag(StartLoc, diag::err_template_arg_not_convertible)
7492 << DeductionArg->getType() << ParamType
7493 << DeductionArg->getSourceRange();
7495 return ExprError();
7496 }
7497 setDeductionArg(DeductionArg);
7498
7499 // Add the value of this argument to the list of converted
7500 // arguments. We use the bitwidth and signedness of the template
7501 // parameter.
7502 if (DeductionArg->isValueDependent()) {
7503 // The argument is value-dependent. Create a new
7504 // TemplateArgument with the converted expression.
7505 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7506 CanonicalConverted =
7507 Context.getCanonicalTemplateArgument(SugaredConverted);
7508 return Arg;
7509 }
7510
7511 QualType IntegerType = ParamType;
7512 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7513 IntegerType = ED->getIntegerType();
7514 }
7515
7516 if (ParamType->isBooleanType()) {
7517 // Value must be zero or one.
7518 Value = Value != 0;
7519 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7520 if (Value.getBitWidth() != AllowedBits)
7521 Value = Value.extOrTrunc(AllowedBits);
7522 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7523 } else {
7524 llvm::APSInt OldValue = Value;
7525
7526 // Coerce the template argument's value to the value it will have
7527 // based on the template parameter's type.
7528 unsigned AllowedBits = IntegerType->isBitIntType()
7529 ? Context.getIntWidth(IntegerType)
7530 : Context.getTypeSize(IntegerType);
7531 if (Value.getBitWidth() != AllowedBits)
7532 Value = Value.extOrTrunc(AllowedBits);
7533 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7534
7535 // Complain if an unsigned parameter received a negative value.
7536 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7537 (OldValue.isSigned() && OldValue.isNegative())) {
7538 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7539 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7540 << Arg->getSourceRange();
7542 }
7543
7544 // Complain if we overflowed the template parameter's type.
7545 unsigned RequiredBits;
7546 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7547 RequiredBits = OldValue.getActiveBits();
7548 else if (OldValue.isUnsigned())
7549 RequiredBits = OldValue.getActiveBits() + 1;
7550 else
7551 RequiredBits = OldValue.getSignificantBits();
7552 if (RequiredBits > AllowedBits) {
7553 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7554 << toString(OldValue, 10) << toString(Value, 10) << ParamType
7555 << Arg->getSourceRange();
7557 }
7558 }
7559
7560 if (ArgPE) {
7561 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7562 CanonicalConverted =
7563 Context.getCanonicalTemplateArgument(SugaredConverted);
7564 } else {
7565 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7566 SugaredConverted = TemplateArgument(Context, Value, T);
7567 CanonicalConverted =
7569 }
7570 return Arg;
7571 }
7572
7573 QualType ArgType = DeductionArg->getType();
7574 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7575
7576 // Handle pointer-to-function, reference-to-function, and
7577 // pointer-to-member-function all in (roughly) the same way.
7578 if (// -- For a non-type template-parameter of type pointer to
7579 // function, only the function-to-pointer conversion (4.3) is
7580 // applied. If the template-argument represents a set of
7581 // overloaded functions (or a pointer to such), the matching
7582 // function is selected from the set (13.4).
7583 (ParamType->isPointerType() &&
7584 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7585 // -- For a non-type template-parameter of type reference to
7586 // function, no conversions apply. If the template-argument
7587 // represents a set of overloaded functions, the matching
7588 // function is selected from the set (13.4).
7589 (ParamType->isReferenceType() &&
7590 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7591 // -- For a non-type template-parameter of type pointer to
7592 // member function, no conversions apply. If the
7593 // template-argument represents a set of overloaded member
7594 // functions, the matching member function is selected from
7595 // the set (13.4).
7596 (ParamType->isMemberPointerType() &&
7597 ParamType->castAs<MemberPointerType>()->getPointeeType()
7598 ->isFunctionType())) {
7599
7600 if (DeductionArg->getType() == Context.OverloadTy) {
7601 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7602 true,
7603 FoundResult)) {
7604 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7605 return ExprError();
7606
7607 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7608 if (Res.isInvalid())
7609 return ExprError();
7610 DeductionArg = Res.get();
7611 ArgType = Arg->getType();
7612 } else
7613 return ExprError();
7614 }
7615 setDeductionArg(DeductionArg);
7616
7617 if (!ParamType->isMemberPointerType()) {
7619 *this, Param, ParamType, Arg, SugaredConverted,
7620 CanonicalConverted))
7621 return ExprError();
7622 return Arg;
7623 }
7624
7626 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7627 return ExprError();
7628 return Arg;
7629 }
7630
7631 setDeductionArg(DeductionArg);
7632
7633 if (ParamType->isPointerType()) {
7634 // -- for a non-type template-parameter of type pointer to
7635 // object, qualification conversions (4.4) and the
7636 // array-to-pointer conversion (4.2) are applied.
7637 // C++0x also allows a value of std::nullptr_t.
7638 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7639 "Only object pointers allowed here");
7640
7641 // FIXME: Deal with pack expansions here.
7643 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7644 return ExprError();
7645 return Arg;
7646 }
7647
7648 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7649 // -- For a non-type template-parameter of type reference to
7650 // object, no conversions apply. The type referred to by the
7651 // reference may be more cv-qualified than the (otherwise
7652 // identical) type of the template-argument. The
7653 // template-parameter is bound directly to the
7654 // template-argument, which must be an lvalue.
7655 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7656 "Only object references allowed here");
7657
7658 // FIXME: Deal with pack expansions here.
7659 if (Arg->getType() == Context.OverloadTy) {
7661 ParamRefType->getPointeeType(),
7662 true,
7663 FoundResult)) {
7664 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7665 return ExprError();
7666 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7667 if (Res.isInvalid())
7668 return ExprError();
7669 Arg = Res.get();
7670 ArgType = Arg->getType();
7671 } else
7672 return ExprError();
7673 }
7674
7676 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7677 return ExprError();
7678 return Arg;
7679 }
7680
7681 // Deal with parameters of type std::nullptr_t.
7682 if (ParamType->isNullPtrType()) {
7683 if (DeductionArg->isTypeDependent() || DeductionArg->isValueDependent()) {
7684 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7685 CanonicalConverted =
7686 Context.getCanonicalTemplateArgument(SugaredConverted);
7687 return Arg;
7688 }
7689
7690 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType,
7691 DeductionArg)) {
7692 case NPV_NotNullPointer:
7693 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7694 << DeductionArg->getType() << ParamType;
7696 return ExprError();
7697
7698 case NPV_Error:
7699 return ExprError();
7700
7701 case NPV_NullPointer:
7702 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7703 if (ArgPE) {
7704 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7705 CanonicalConverted =
7706 Context.getCanonicalTemplateArgument(SugaredConverted);
7707 } else {
7708 SugaredConverted = TemplateArgument(ParamType,
7709 /*isNullPtr=*/true);
7710 CanonicalConverted =
7712 /*isNullPtr=*/true);
7713 }
7714 return Arg;
7715 }
7716 }
7717
7718 // -- For a non-type template-parameter of type pointer to data
7719 // member, qualification conversions (4.4) are applied.
7720 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7721
7722 // FIXME: Deal with pack expansions here.
7724 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7725 return ExprError();
7726 return Arg;
7727}
7728
7732
7735 const TemplateArgumentLoc &Arg) {
7736 // C++0x [temp.arg.template]p1:
7737 // A template-argument for a template template-parameter shall be
7738 // the name of a class template or an alias template, expressed as an
7739 // id-expression. When the template-argument names a class template, only
7740 // primary class templates are considered when matching the
7741 // template template argument with the corresponding parameter;
7742 // partial specializations are not considered even if their
7743 // parameter lists match that of the template template parameter.
7744 //
7745
7747 unsigned DiagFoundKind = 0;
7748
7749 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {
7750 switch (TTP->templateParameterKind()) {
7752 DiagFoundKind = 3;
7753 break;
7755 DiagFoundKind = 2;
7756 break;
7757 default:
7758 DiagFoundKind = 1;
7759 break;
7760 }
7761 Kind = TTP->templateParameterKind();
7762 } else if (isa<ConceptDecl>(Template)) {
7764 DiagFoundKind = 3;
7765 } else if (isa<FunctionTemplateDecl>(Template)) {
7767 DiagFoundKind = 0;
7768 } else if (isa<VarTemplateDecl>(Template)) {
7770 DiagFoundKind = 2;
7771 } else if (isa<ClassTemplateDecl>(Template) ||
7772 isa<TypeAliasTemplateDecl>(Template) ||
7773 isa<BuiltinTemplateDecl>(Template)) {
7775 DiagFoundKind = 1;
7776 } else {
7777 assert(false && "Unexpected Decl");
7778 }
7779
7780 if (Kind == Param->templateParameterKind()) {
7781 return true;
7782 }
7783
7784 unsigned DiagKind = 0;
7785 switch (Param->templateParameterKind()) {
7787 DiagKind = 2;
7788 break;
7790 DiagKind = 1;
7791 break;
7792 default:
7793 DiagKind = 0;
7794 break;
7795 }
7796 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)
7797 << DiagKind;
7798 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)
7799 << DiagFoundKind << Template;
7800 return false;
7801}
7802
7803/// Check a template argument against its corresponding
7804/// template template parameter.
7805///
7806/// This routine implements the semantics of C++ [temp.arg.template].
7807/// It returns true if an error occurred, and false otherwise.
7809 TemplateParameterList *Params,
7811 bool PartialOrdering,
7812 bool *StrictPackMatch) {
7814 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7815 if (!Template) {
7816 // Any dependent template name is fine.
7817 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7818 return false;
7819 }
7820
7821 if (Template->isInvalidDecl())
7822 return true;
7823
7825 return true;
7826 }
7827
7828 // C++1z [temp.arg.template]p3: (DR 150)
7829 // A template-argument matches a template template-parameter P when P
7830 // is at least as specialized as the template-argument A.
7832 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7833 PartialOrdering, StrictPackMatch))
7834 return true;
7835 // P2113
7836 // C++20[temp.func.order]p2
7837 // [...] If both deductions succeed, the partial ordering selects the
7838 // more constrained template (if one exists) as determined below.
7839 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7840 Params->getAssociatedConstraints(ParamsAC);
7841 // C++20[temp.arg.template]p3
7842 // [...] In this comparison, if P is unconstrained, the constraints on A
7843 // are not considered.
7844 if (ParamsAC.empty())
7845 return false;
7846
7847 Template->getAssociatedConstraints(TemplateAC);
7848
7849 bool IsParamAtLeastAsConstrained;
7850 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7851 IsParamAtLeastAsConstrained))
7852 return true;
7853 if (!IsParamAtLeastAsConstrained) {
7854 Diag(Arg.getLocation(),
7855 diag::err_template_template_parameter_not_at_least_as_constrained)
7856 << Template << Param << Arg.getSourceRange();
7857 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7858 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7860 TemplateAC);
7861 return true;
7862 }
7863 return false;
7864}
7865
7867 unsigned HereDiagID,
7868 unsigned ExternalDiagID) {
7869 if (Decl.getLocation().isValid())
7870 return S.Diag(Decl.getLocation(), HereDiagID);
7871
7872 SmallString<128> Str;
7873 llvm::raw_svector_ostream Out(Str);
7875 PP.TerseOutput = 1;
7876 Decl.print(Out, PP);
7877 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7878}
7879
7881 std::optional<SourceRange> ParamRange) {
7883 noteLocation(*this, Decl, diag::note_template_decl_here,
7884 diag::note_template_decl_external);
7885 if (ParamRange && ParamRange->isValid()) {
7886 assert(Decl.getLocation().isValid() &&
7887 "Parameter range has location when Decl does not");
7888 DB << *ParamRange;
7889 }
7890}
7891
7893 noteLocation(*this, Decl, diag::note_template_param_here,
7894 diag::note_template_param_external);
7895}
7896
7897/// Given a non-type template argument that refers to a
7898/// declaration and the type of its corresponding non-type template
7899/// parameter, produce an expression that properly refers to that
7900/// declaration.
7902 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7904 // C++ [temp.param]p8:
7905 //
7906 // A non-type template-parameter of type "array of T" or
7907 // "function returning T" is adjusted to be of type "pointer to
7908 // T" or "pointer to function returning T", respectively.
7909 if (ParamType->isArrayType())
7910 ParamType = Context.getArrayDecayedType(ParamType);
7911 else if (ParamType->isFunctionType())
7912 ParamType = Context.getPointerType(ParamType);
7913
7914 // For a NULL non-type template argument, return nullptr casted to the
7915 // parameter's type.
7916 if (Arg.getKind() == TemplateArgument::NullPtr) {
7917 return ImpCastExprToType(
7919 ParamType,
7920 ParamType->getAs<MemberPointerType>()
7921 ? CK_NullToMemberPointer
7922 : CK_NullToPointer);
7923 }
7924 assert(Arg.getKind() == TemplateArgument::Declaration &&
7925 "Only declaration template arguments permitted here");
7926
7927 ValueDecl *VD = Arg.getAsDecl();
7928
7929 CXXScopeSpec SS;
7930 if (ParamType->isMemberPointerType()) {
7931 // If this is a pointer to member, we need to use a qualified name to
7932 // form a suitable pointer-to-member constant.
7933 assert(VD->getDeclContext()->isRecord() &&
7934 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7935 isa<IndirectFieldDecl>(VD)));
7936 CanQualType ClassType =
7937 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));
7938 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7939 SS.MakeTrivial(Context, Qualifier, Loc);
7940 }
7941
7943 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7944 if (RefExpr.isInvalid())
7945 return ExprError();
7946
7947 // For a pointer, the argument declaration is the pointee. Take its address.
7948 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7949 if (ParamType->isPointerType() && !ElemT.isNull() &&
7950 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7951 // Decay an array argument if we want a pointer to its first element.
7952 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7953 if (RefExpr.isInvalid())
7954 return ExprError();
7955 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7956 // For any other pointer, take the address (or form a pointer-to-member).
7957 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7958 if (RefExpr.isInvalid())
7959 return ExprError();
7960 } else if (ParamType->isRecordType()) {
7961 assert(isa<TemplateParamObjectDecl>(VD) &&
7962 "arg for class template param not a template parameter object");
7963 // No conversions apply in this case.
7964 return RefExpr;
7965 } else {
7966 assert(ParamType->isReferenceType() &&
7967 "unexpected type for decl template argument");
7968 if (NonTypeTemplateParmDecl *NTTP =
7969 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7970 QualType TemplateParamType = NTTP->getType();
7971 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7972 if (AT && AT->isDecltypeAuto()) {
7974 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7975 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7976 /*PackIndex=*/std::nullopt,
7977 /*RefParam=*/true, /*Final=*/true);
7978 }
7979 }
7980 }
7981
7982 // At this point we should have the right value category.
7983 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7984 "value kind mismatch for non-type template argument");
7985
7986 // The type of the template parameter can differ from the type of the
7987 // argument in various ways; convert it now if necessary.
7988 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7989 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7990 CastKind CK;
7991 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7992 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {
7993 CK = CK_NoOp;
7994 } else if (ParamType->isVoidPointerType() &&
7995 RefExpr.get()->getType()->isPointerType()) {
7996 CK = CK_BitCast;
7997 } else {
7998 // FIXME: Pointers to members can need conversion derived-to-base or
7999 // base-to-derived conversions. We currently don't retain enough
8000 // information to convert properly (we need to track a cast path or
8001 // subobject number in the template argument).
8002 llvm_unreachable(
8003 "unexpected conversion required for non-type template argument");
8004 }
8005 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8006 RefExpr.get()->getValueKind());
8007 }
8008
8009 return RefExpr;
8010}
8011
8012/// Construct a new expression that refers to the given
8013/// integral template argument with the given source-location
8014/// information.
8015///
8016/// This routine takes care of the mapping from an integral template
8017/// argument (which may have any integral type) to the appropriate
8018/// literal value.
8020 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8021 assert(OrigT->isIntegralOrEnumerationType());
8022
8023 // If this is an enum type that we're instantiating, we need to use an integer
8024 // type the same size as the enumerator. We don't want to build an
8025 // IntegerLiteral with enum type. The integer type of an enum type can be of
8026 // any integral type with C++11 enum classes, make sure we create the right
8027 // type of literal for it.
8028 QualType T = OrigT;
8029 if (const auto *ED = OrigT->getAsEnumDecl())
8030 T = ED->getIntegerType();
8031
8032 Expr *E;
8033 if (T->isAnyCharacterType()) {
8035 if (T->isWideCharType())
8037 else if (T->isChar8Type() && S.getLangOpts().Char8)
8039 else if (T->isChar16Type())
8041 else if (T->isChar32Type())
8043 else
8045
8046 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8047 } else if (T->isBooleanType()) {
8048 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8049 } else {
8050 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8051 }
8052
8053 if (OrigT->isEnumeralType()) {
8054 // FIXME: This is a hack. We need a better way to handle substituted
8055 // non-type template parameters.
8056 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8057 nullptr, S.CurFPFeatureOverrides(),
8059 Loc, Loc);
8060 }
8061
8062 return E;
8063}
8064
8066 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8067 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8068 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8069 ILE->setType(T);
8070 return ILE;
8071 };
8072
8073 switch (Val.getKind()) {
8075 // This cannot occur in a template argument at all.
8076 case APValue::Array:
8077 case APValue::Struct:
8078 case APValue::Union:
8079 // These can only occur within a template parameter object, which is
8080 // represented as a TemplateArgument::Declaration.
8081 llvm_unreachable("unexpected template argument value");
8082
8083 case APValue::Int:
8085 Loc);
8086
8087 case APValue::Float:
8088 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8089 T, Loc);
8090
8093 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8094 Val.getFixedPoint().getScale());
8095
8096 case APValue::ComplexInt: {
8097 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8099 S, ElemT, Val.getComplexIntReal(), Loc),
8101 S, ElemT, Val.getComplexIntImag(), Loc)});
8102 }
8103
8104 case APValue::ComplexFloat: {
8105 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8106 return MakeInitList(
8108 ElemT, Loc),
8110 ElemT, Loc)});
8111 }
8112
8113 case APValue::Vector: {
8114 QualType ElemT = T->castAs<VectorType>()->getElementType();
8116 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8118 S, ElemT, Val.getVectorElt(I), Loc));
8119 return MakeInitList(Elts);
8120 }
8121
8122 case APValue::None:
8124 llvm_unreachable("Unexpected APValue kind.");
8125 case APValue::LValue:
8127 // There isn't necessarily a valid equivalent source-level syntax for
8128 // these; in particular, a naive lowering might violate access control.
8129 // So for now we lower to a ConstantExpr holding the value, wrapped around
8130 // an OpaqueValueExpr.
8131 // FIXME: We should have a better representation for this.
8133 if (T->isReferenceType()) {
8134 T = T->getPointeeType();
8135 VK = VK_LValue;
8136 }
8137 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8138 return ConstantExpr::Create(S.Context, OVE, Val);
8139 }
8140 llvm_unreachable("Unhandled APValue::ValueKind enum");
8141}
8142
8146 switch (Arg.getKind()) {
8152 llvm_unreachable("not a non-type template argument");
8153
8155 return Arg.getAsExpr();
8156
8161
8164 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8165
8168 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8169 }
8170 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8171}
8172
8173/// Match two template parameters within template parameter lists.
8175 Sema &S, NamedDecl *New,
8176 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8177 const NamedDecl *OldInstFrom, bool Complain,
8179 // Check the actual kind (type, non-type, template).
8180 if (Old->getKind() != New->getKind()) {
8181 if (Complain) {
8182 unsigned NextDiag = diag::err_template_param_different_kind;
8183 if (TemplateArgLoc.isValid()) {
8184 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8185 NextDiag = diag::note_template_param_different_kind;
8186 }
8187 S.Diag(New->getLocation(), NextDiag)
8188 << (Kind != Sema::TPL_TemplateMatch);
8189 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8190 << (Kind != Sema::TPL_TemplateMatch);
8191 }
8192
8193 return false;
8194 }
8195
8196 // Check that both are parameter packs or neither are parameter packs.
8197 // However, if we are matching a template template argument to a
8198 // template template parameter, the template template parameter can have
8199 // a parameter pack where the template template argument does not.
8200 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8201 if (Complain) {
8202 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8203 if (TemplateArgLoc.isValid()) {
8204 S.Diag(TemplateArgLoc,
8205 diag::err_template_arg_template_params_mismatch);
8206 NextDiag = diag::note_template_parameter_pack_non_pack;
8207 }
8208
8209 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8210 : isa<NonTypeTemplateParmDecl>(New)? 1
8211 : 2;
8212 S.Diag(New->getLocation(), NextDiag)
8213 << ParamKind << New->isParameterPack();
8214 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8215 << ParamKind << Old->isParameterPack();
8216 }
8217
8218 return false;
8219 }
8220 // For non-type template parameters, check the type of the parameter.
8221 if (NonTypeTemplateParmDecl *OldNTTP =
8222 dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8223 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8224
8225 // If we are matching a template template argument to a template
8226 // template parameter and one of the non-type template parameter types
8227 // is dependent, then we must wait until template instantiation time
8228 // to actually compare the arguments.
8230 (!OldNTTP->getType()->isDependentType() &&
8231 !NewNTTP->getType()->isDependentType())) {
8232 // C++20 [temp.over.link]p6:
8233 // Two [non-type] template-parameters are equivalent [if] they have
8234 // equivalent types ignoring the use of type-constraints for
8235 // placeholder types
8236 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8237 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8238 if (!S.Context.hasSameType(OldType, NewType)) {
8239 if (Complain) {
8240 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8241 if (TemplateArgLoc.isValid()) {
8242 S.Diag(TemplateArgLoc,
8243 diag::err_template_arg_template_params_mismatch);
8244 NextDiag = diag::note_template_nontype_parm_different_type;
8245 }
8246 S.Diag(NewNTTP->getLocation(), NextDiag)
8247 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8248 S.Diag(OldNTTP->getLocation(),
8249 diag::note_template_nontype_parm_prev_declaration)
8250 << OldNTTP->getType();
8251 }
8252 return false;
8253 }
8254 }
8255 }
8256 // For template template parameters, check the template parameter types.
8257 // The template parameter lists of template template
8258 // parameters must agree.
8259 else if (TemplateTemplateParmDecl *OldTTP =
8260 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8261 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8262 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8263 return false;
8265 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8266 OldTTP->getTemplateParameters(), Complain,
8269 : Kind),
8270 TemplateArgLoc))
8271 return false;
8272 }
8273
8276 !isa<TemplateTemplateParmDecl>(Old)) {
8277 const Expr *NewC = nullptr, *OldC = nullptr;
8278
8279 if (isa<TemplateTypeParmDecl>(New)) {
8280 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8281 NewC = TC->getImmediatelyDeclaredConstraint();
8282 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8283 OldC = TC->getImmediatelyDeclaredConstraint();
8284 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8285 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8286 ->getPlaceholderTypeConstraint())
8287 NewC = E;
8288 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8289 ->getPlaceholderTypeConstraint())
8290 OldC = E;
8291 } else
8292 llvm_unreachable("unexpected template parameter type");
8293
8294 auto Diagnose = [&] {
8295 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8296 diag::err_template_different_type_constraint);
8297 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8298 diag::note_template_prev_declaration) << /*declaration*/0;
8299 };
8300
8301 if (!NewC != !OldC) {
8302 if (Complain)
8303 Diagnose();
8304 return false;
8305 }
8306
8307 if (NewC) {
8308 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8309 NewC)) {
8310 if (Complain)
8311 Diagnose();
8312 return false;
8313 }
8314 }
8315 }
8316
8317 return true;
8318}
8319
8320/// Diagnose a known arity mismatch when comparing template argument
8321/// lists.
8322static
8327 SourceLocation TemplateArgLoc) {
8328 unsigned NextDiag = diag::err_template_param_list_different_arity;
8329 if (TemplateArgLoc.isValid()) {
8330 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8331 NextDiag = diag::note_template_param_list_different_arity;
8332 }
8333 S.Diag(New->getTemplateLoc(), NextDiag)
8334 << (New->size() > Old->size())
8335 << (Kind != Sema::TPL_TemplateMatch)
8336 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8337 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8338 << (Kind != Sema::TPL_TemplateMatch)
8339 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8340}
8341
8344 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8345 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8346 if (Old->size() != New->size()) {
8347 if (Complain)
8349 TemplateArgLoc);
8350
8351 return false;
8352 }
8353
8354 // C++0x [temp.arg.template]p3:
8355 // A template-argument matches a template template-parameter (call it P)
8356 // when each of the template parameters in the template-parameter-list of
8357 // the template-argument's corresponding class template or alias template
8358 // (call it A) matches the corresponding template parameter in the
8359 // template-parameter-list of P. [...]
8360 TemplateParameterList::iterator NewParm = New->begin();
8361 TemplateParameterList::iterator NewParmEnd = New->end();
8362 for (TemplateParameterList::iterator OldParm = Old->begin(),
8363 OldParmEnd = Old->end();
8364 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8365 if (NewParm == NewParmEnd) {
8366 if (Complain)
8368 TemplateArgLoc);
8369 return false;
8370 }
8371 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8372 OldInstFrom, Complain, Kind,
8373 TemplateArgLoc))
8374 return false;
8375 }
8376
8377 // Make sure we exhausted all of the arguments.
8378 if (NewParm != NewParmEnd) {
8379 if (Complain)
8381 TemplateArgLoc);
8382
8383 return false;
8384 }
8385
8386 if (Kind != TPL_TemplateParamsEquivalent) {
8387 const Expr *NewRC = New->getRequiresClause();
8388 const Expr *OldRC = Old->getRequiresClause();
8389
8390 auto Diagnose = [&] {
8391 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8392 diag::err_template_different_requires_clause);
8393 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8394 diag::note_template_prev_declaration) << /*declaration*/0;
8395 };
8396
8397 if (!NewRC != !OldRC) {
8398 if (Complain)
8399 Diagnose();
8400 return false;
8401 }
8402
8403 if (NewRC) {
8404 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8405 NewRC)) {
8406 if (Complain)
8407 Diagnose();
8408 return false;
8409 }
8410 }
8411 }
8412
8413 return true;
8414}
8415
8416bool
8418 if (!S)
8419 return false;
8420
8421 // Find the nearest enclosing declaration scope.
8422 S = S->getDeclParent();
8423
8424 // C++ [temp.pre]p6: [P2096]
8425 // A template, explicit specialization, or partial specialization shall not
8426 // have C linkage.
8427 DeclContext *Ctx = S->getEntity();
8428 if (Ctx && Ctx->isExternCContext()) {
8430 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8431 ? TemplateParams->getParam(0)->getSourceRange()
8432 : TemplateParams->getSourceRange();
8433 Diag(Range.getBegin(), diag::err_template_linkage) << Range;
8434 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8435 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8436 return true;
8437 }
8438 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8439
8440 // C++ [temp]p2:
8441 // A template-declaration can appear only as a namespace scope or
8442 // class scope declaration.
8443 // C++ [temp.expl.spec]p3:
8444 // An explicit specialization may be declared in any scope in which the
8445 // corresponding primary template may be defined.
8446 // C++ [temp.class.spec]p6: [P2096]
8447 // A partial specialization may be declared in any scope in which the
8448 // corresponding primary template may be defined.
8449 if (Ctx) {
8450 if (Ctx->isFileContext())
8451 return false;
8452 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8453 // C++ [temp.mem]p2:
8454 // A local class shall not have member templates.
8455 if (RD->isLocalClass())
8456 return Diag(TemplateParams->getTemplateLoc(),
8457 diag::err_template_inside_local_class)
8458 << TemplateParams->getSourceRange();
8459 else
8460 return false;
8461 }
8462 }
8463
8464 return Diag(TemplateParams->getTemplateLoc(),
8465 diag::err_template_outside_namespace_or_class_scope)
8466 << TemplateParams->getSourceRange();
8467}
8468
8469/// Determine what kind of template specialization the given declaration
8470/// is.
8472 if (!D)
8473 return TSK_Undeclared;
8474
8475 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8476 return Record->getTemplateSpecializationKind();
8477 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8478 return Function->getTemplateSpecializationKind();
8479 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8480 return Var->getTemplateSpecializationKind();
8481
8482 return TSK_Undeclared;
8483}
8484
8485/// Check whether a specialization is well-formed in the current
8486/// context.
8487///
8488/// This routine determines whether a template specialization can be declared
8489/// in the current context (C++ [temp.expl.spec]p2).
8490///
8491/// \param S the semantic analysis object for which this check is being
8492/// performed.
8493///
8494/// \param Specialized the entity being specialized or instantiated, which
8495/// may be a kind of template (class template, function template, etc.) or
8496/// a member of a class template (member function, static data member,
8497/// member class).
8498///
8499/// \param PrevDecl the previous declaration of this entity, if any.
8500///
8501/// \param Loc the location of the explicit specialization or instantiation of
8502/// this entity.
8503///
8504/// \param IsPartialSpecialization whether this is a partial specialization of
8505/// a class template.
8506///
8507/// \returns true if there was an error that we cannot recover from, false
8508/// otherwise.
8510 NamedDecl *Specialized,
8511 NamedDecl *PrevDecl,
8514 // Keep these "kind" numbers in sync with the %select statements in the
8515 // various diagnostics emitted by this routine.
8516 int EntityKind = 0;
8517 if (isa<ClassTemplateDecl>(Specialized))
8518 EntityKind = IsPartialSpecialization? 1 : 0;
8519 else if (isa<VarTemplateDecl>(Specialized))
8520 EntityKind = IsPartialSpecialization ? 3 : 2;
8521 else if (isa<FunctionTemplateDecl>(Specialized))
8522 EntityKind = 4;
8523 else if (isa<CXXMethodDecl>(Specialized))
8524 EntityKind = 5;
8525 else if (isa<VarDecl>(Specialized))
8526 EntityKind = 6;
8527 else if (isa<RecordDecl>(Specialized))
8528 EntityKind = 7;
8529 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8530 EntityKind = 8;
8531 else {
8532 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8533 << S.getLangOpts().CPlusPlus11;
8534 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8535 return true;
8536 }
8537
8538 // C++ [temp.expl.spec]p2:
8539 // An explicit specialization may be declared in any scope in which
8540 // the corresponding primary template may be defined.
8542 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8543 << Specialized;
8544 return true;
8545 }
8546
8547 // C++ [temp.class.spec]p6:
8548 // A class template partial specialization may be declared in any
8549 // scope in which the primary template may be defined.
8550 DeclContext *SpecializedContext =
8551 Specialized->getDeclContext()->getRedeclContext();
8553
8554 // Make sure that this redeclaration (or definition) occurs in the same
8555 // scope or an enclosing namespace.
8556 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8557 : DC->Equals(SpecializedContext))) {
8558 if (isa<TranslationUnitDecl>(SpecializedContext))
8559 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8560 << EntityKind << Specialized;
8561 else {
8562 auto *ND = cast<NamedDecl>(SpecializedContext);
8563 int Diag = diag::err_template_spec_redecl_out_of_scope;
8564 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8565 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8566 S.Diag(Loc, Diag) << EntityKind << Specialized
8567 << ND << isa<CXXRecordDecl>(ND);
8568 }
8569
8570 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8571
8572 // Don't allow specializing in the wrong class during error recovery.
8573 // Otherwise, things can go horribly wrong.
8574 if (DC->isRecord())
8575 return true;
8576 }
8577
8578 return false;
8579}
8580
8582 if (!E->isTypeDependent())
8583 return SourceLocation();
8584 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8585 Checker.TraverseStmt(E);
8586 if (Checker.MatchLoc.isInvalid())
8587 return E->getSourceRange();
8588 return Checker.MatchLoc;
8589}
8590
8591static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8592 if (!TL.getType()->isDependentType())
8593 return SourceLocation();
8594 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8595 Checker.TraverseTypeLoc(TL);
8596 if (Checker.MatchLoc.isInvalid())
8597 return TL.getSourceRange();
8598 return Checker.MatchLoc;
8599}
8600
8601/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8602/// that checks non-type template partial specialization arguments.
8604 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8605 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8606 for (unsigned I = 0; I != NumArgs; ++I) {
8607 if (Args[I].getKind() == TemplateArgument::Pack) {
8609 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8610 Args[I].pack_size(), IsDefaultArgument))
8611 return true;
8612
8613 continue;
8614 }
8615
8616 if (Args[I].getKind() != TemplateArgument::Expression)
8617 continue;
8618
8619 Expr *ArgExpr = Args[I].getAsExpr();
8620
8621 // We can have a pack expansion of any of the bullets below.
8622 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8623 ArgExpr = Expansion->getPattern();
8624
8625 // Strip off any implicit casts we added as part of type checking.
8626 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8627 ArgExpr = ICE->getSubExpr();
8628
8629 // C++ [temp.class.spec]p8:
8630 // A non-type argument is non-specialized if it is the name of a
8631 // non-type parameter. All other non-type arguments are
8632 // specialized.
8633 //
8634 // Below, we check the two conditions that only apply to
8635 // specialized non-type arguments, so skip any non-specialized
8636 // arguments.
8637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8638 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8639 continue;
8640
8641 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);
8642 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8643 continue;
8644 }
8645
8646 // C++ [temp.class.spec]p9:
8647 // Within the argument list of a class template partial
8648 // specialization, the following restrictions apply:
8649 // -- A partially specialized non-type argument expression
8650 // shall not involve a template parameter of the partial
8651 // specialization except when the argument expression is a
8652 // simple identifier.
8653 // -- The type of a template parameter corresponding to a
8654 // specialized non-type argument shall not be dependent on a
8655 // parameter of the specialization.
8656 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8657 // We implement a compromise between the original rules and DR1315:
8658 // -- A specialized non-type template argument shall not be
8659 // type-dependent and the corresponding template parameter
8660 // shall have a non-dependent type.
8661 SourceRange ParamUseRange =
8662 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8663 if (ParamUseRange.isValid()) {
8664 if (IsDefaultArgument) {
8665 S.Diag(TemplateNameLoc,
8666 diag::err_dependent_non_type_arg_in_partial_spec);
8667 S.Diag(ParamUseRange.getBegin(),
8668 diag::note_dependent_non_type_default_arg_in_partial_spec)
8669 << ParamUseRange;
8670 } else {
8671 S.Diag(ParamUseRange.getBegin(),
8672 diag::err_dependent_non_type_arg_in_partial_spec)
8673 << ParamUseRange;
8674 }
8675 return true;
8676 }
8677
8678 ParamUseRange = findTemplateParameter(
8679 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8680 if (ParamUseRange.isValid()) {
8681 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8682 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8683 << Param->getType();
8685 return true;
8686 }
8687 }
8688
8689 return false;
8690}
8691
8693 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8694 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8695 // We have to be conservative when checking a template in a dependent
8696 // context.
8697 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8698 return false;
8699
8700 TemplateParameterList *TemplateParams =
8701 PrimaryTemplate->getTemplateParameters();
8702 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8704 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8705 if (!Param)
8706 continue;
8707
8708 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8709 Param, &TemplateArgs[I],
8710 1, I >= NumExplicit))
8711 return true;
8712 }
8713
8714 return false;
8715}
8716
8718 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8719 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8721 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8722 assert(TUK != TagUseKind::Reference && "References are not specializations");
8723
8724 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8725 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8726 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8727
8728 // Find the class template we're specializing
8729 TemplateName Name = TemplateId.Template.get();
8731 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8732
8733 if (!ClassTemplate) {
8734 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8735 << (Name.getAsTemplateDecl() &&
8736 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8737 return true;
8738 }
8739
8740 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8741 auto Message = DSA->getMessage();
8742 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8743 << ClassTemplate << !Message.empty() << Message;
8744 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8745 }
8746
8747 if (S->isTemplateParamScope())
8748 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8749
8750 DeclContext *DC = ClassTemplate->getDeclContext();
8751
8752 bool isMemberSpecialization = false;
8753 bool isPartialSpecialization = false;
8754
8755 if (SS.isSet()) {
8756 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8757 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8758 TemplateNameLoc, &TemplateId,
8759 /*IsMemberSpecialization=*/false))
8760 return true;
8761 }
8762
8763 // Check the validity of the template headers that introduce this
8764 // template.
8765 // FIXME: We probably shouldn't complain about these headers for
8766 // friend declarations.
8767 bool Invalid = false;
8768 TemplateParameterList *TemplateParams =
8770 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8771 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8772 if (Invalid)
8773 return true;
8774
8775 // Check that we can declare a template specialization here.
8776 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8777 return true;
8778
8779 if (TemplateParams && DC->isDependentContext()) {
8780 ContextRAII SavedContext(*this, DC);
8782 return true;
8783 }
8784
8785 if (TemplateParams && TemplateParams->size() > 0) {
8786 isPartialSpecialization = true;
8787
8788 if (TUK == TagUseKind::Friend) {
8789 Diag(KWLoc, diag::err_partial_specialization_friend)
8790 << SourceRange(LAngleLoc, RAngleLoc);
8791 return true;
8792 }
8793
8794 // C++ [temp.class.spec]p10:
8795 // The template parameter list of a specialization shall not
8796 // contain default template argument values.
8797 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8798 Decl *Param = TemplateParams->getParam(I);
8799 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8800 if (TTP->hasDefaultArgument()) {
8801 Diag(TTP->getDefaultArgumentLoc(),
8802 diag::err_default_arg_in_partial_spec);
8803 TTP->removeDefaultArgument();
8804 }
8805 } else if (NonTypeTemplateParmDecl *NTTP
8806 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8807 if (NTTP->hasDefaultArgument()) {
8808 Diag(NTTP->getDefaultArgumentLoc(),
8809 diag::err_default_arg_in_partial_spec)
8810 << NTTP->getDefaultArgument().getSourceRange();
8811 NTTP->removeDefaultArgument();
8812 }
8813 } else {
8814 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8815 if (TTP->hasDefaultArgument()) {
8817 diag::err_default_arg_in_partial_spec)
8819 TTP->removeDefaultArgument();
8820 }
8821 }
8822 }
8823 } else if (TemplateParams) {
8824 if (TUK == TagUseKind::Friend)
8825 Diag(KWLoc, diag::err_template_spec_friend)
8827 SourceRange(TemplateParams->getTemplateLoc(),
8828 TemplateParams->getRAngleLoc()))
8829 << SourceRange(LAngleLoc, RAngleLoc);
8830 } else {
8831 assert(TUK == TagUseKind::Friend &&
8832 "should have a 'template<>' for this decl");
8833 }
8834
8835 // Check that the specialization uses the same tag kind as the
8836 // original template.
8838 assert(Kind != TagTypeKind::Enum &&
8839 "Invalid enum tag in class template spec!");
8840 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8841 TUK == TagUseKind::Definition, KWLoc,
8842 ClassTemplate->getIdentifier())) {
8843 Diag(KWLoc, diag::err_use_with_wrong_tag)
8844 << ClassTemplate
8846 ClassTemplate->getTemplatedDecl()->getKindName());
8847 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8848 diag::note_previous_use);
8849 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8850 }
8851
8852 // Translate the parser's template argument list in our AST format.
8853 TemplateArgumentListInfo TemplateArgs =
8854 makeTemplateArgumentListInfo(*this, TemplateId);
8855
8856 // Check for unexpanded parameter packs in any of the template arguments.
8857 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8858 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8859 isPartialSpecialization
8862 return true;
8863
8864 // Check that the template argument list is well-formed for this
8865 // template.
8867 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8868 /*DefaultArgs=*/{},
8869 /*PartialTemplateArgs=*/false, CTAI,
8870 /*UpdateArgsWithConversions=*/true))
8871 return true;
8872
8873 // Find the class template (partial) specialization declaration that
8874 // corresponds to these arguments.
8875 if (isPartialSpecialization) {
8877 TemplateArgs.size(),
8878 CTAI.CanonicalConverted))
8879 return true;
8880
8881 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8882 // also do it during instantiation.
8883 if (!Name.isDependent() &&
8885 TemplateArgs, CTAI.CanonicalConverted)) {
8886 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8887 << ClassTemplate->getDeclName();
8888 isPartialSpecialization = false;
8889 Invalid = true;
8890 }
8891 }
8892
8893 void *InsertPos = nullptr;
8894 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8895
8896 if (isPartialSpecialization)
8897 PrevDecl = ClassTemplate->findPartialSpecialization(
8898 CTAI.CanonicalConverted, TemplateParams, InsertPos);
8899 else
8900 PrevDecl =
8901 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
8902
8904
8905 // Check whether we can declare a class template specialization in
8906 // the current scope.
8907 if (TUK != TagUseKind::Friend &&
8909 TemplateNameLoc,
8910 isPartialSpecialization))
8911 return true;
8912
8913 if (!isPartialSpecialization) {
8914 // Create a new class template specialization declaration node for
8915 // this explicit specialization or friend declaration.
8917 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8918 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
8919 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8921 if (TemplateParameterLists.size() > 0) {
8922 Specialization->setTemplateParameterListsInfo(Context,
8923 TemplateParameterLists);
8924 }
8925
8926 if (!PrevDecl)
8927 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8928 } else {
8931 TemplateName(ClassTemplate->getCanonicalDecl()),
8932 CTAI.CanonicalConverted));
8933 if (Context.hasSameType(
8934 CanonType,
8935 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&
8936 (!Context.getLangOpts().CPlusPlus20 ||
8937 !TemplateParams->hasAssociatedConstraints())) {
8938 // C++ [temp.class.spec]p9b3:
8939 //
8940 // -- The argument list of the specialization shall not be identical
8941 // to the implicit argument list of the primary template.
8942 //
8943 // This rule has since been removed, because it's redundant given DR1495,
8944 // but we keep it because it produces better diagnostics and recovery.
8945 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8946 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8947 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8948 return CheckClassTemplate(
8949 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8950 TemplateNameLoc, Attr, TemplateParams, AS_none,
8951 /*ModulePrivateLoc=*/SourceLocation(),
8952 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8953 TemplateParameterLists.data());
8954 }
8955
8956 // Create a new class template partial specialization declaration node.
8958 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8961 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8962 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);
8963 Partial->setTemplateArgsAsWritten(TemplateArgs);
8964 SetNestedNameSpecifier(*this, Partial, SS);
8965 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8967 Context, TemplateParameterLists.drop_back(1));
8968 }
8969
8970 if (!PrevPartial)
8971 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8972 Specialization = Partial;
8973
8974 // If we are providing an explicit specialization of a member class
8975 // template specialization, make a note of that.
8976 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8977 PrevPartial->setMemberSpecialization();
8978
8980 }
8981
8982 // C++ [temp.expl.spec]p6:
8983 // If a template, a member template or the member of a class template is
8984 // explicitly specialized then that specialization shall be declared
8985 // before the first use of that specialization that would cause an implicit
8986 // instantiation to take place, in every translation unit in which such a
8987 // use occurs; no diagnostic is required.
8988 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8989 bool Okay = false;
8990 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8991 // Is there any previous explicit specialization declaration?
8993 Okay = true;
8994 break;
8995 }
8996 }
8997
8998 if (!Okay) {
8999 SourceRange Range(TemplateNameLoc, RAngleLoc);
9000 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9002
9003 Diag(PrevDecl->getPointOfInstantiation(),
9004 diag::note_instantiation_required_here)
9005 << (PrevDecl->getTemplateSpecializationKind()
9007 return true;
9008 }
9009 }
9010
9011 // If this is not a friend, note that this is an explicit specialization.
9012 if (TUK != TagUseKind::Friend)
9013 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9014
9015 // Check that this isn't a redefinition of this specialization.
9016 if (TUK == TagUseKind::Definition) {
9017 RecordDecl *Def = Specialization->getDefinition();
9018 NamedDecl *Hidden = nullptr;
9019 bool HiddenDefVisible = false;
9020 if (Def && SkipBody &&
9021 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {
9022 SkipBody->ShouldSkip = true;
9023 SkipBody->Previous = Def;
9024 if (!HiddenDefVisible && Hidden)
9026 } else if (Def) {
9027 SourceRange Range(TemplateNameLoc, RAngleLoc);
9028 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9029 Diag(Def->getLocation(), diag::note_previous_definition);
9030 Specialization->setInvalidDecl();
9031 return true;
9032 }
9033 }
9034
9037
9038 // Add alignment attributes if necessary; these attributes are checked when
9039 // the ASTContext lays out the structure.
9040 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9041 if (LangOpts.HLSL)
9042 Specialization->addAttr(PackedAttr::CreateImplicit(Context));
9045 }
9046
9047 if (ModulePrivateLoc.isValid())
9048 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9049 << (isPartialSpecialization? 1 : 0)
9050 << FixItHint::CreateRemoval(ModulePrivateLoc);
9051
9052 // C++ [temp.expl.spec]p9:
9053 // A template explicit specialization is in the scope of the
9054 // namespace in which the template was defined.
9055 //
9056 // We actually implement this paragraph where we set the semantic
9057 // context (in the creation of the ClassTemplateSpecializationDecl),
9058 // but we also maintain the lexical context where the actual
9059 // definition occurs.
9060 Specialization->setLexicalDeclContext(CurContext);
9061
9062 // We may be starting the definition of this specialization.
9063 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9064 Specialization->startDefinition();
9065
9066 if (TUK == TagUseKind::Friend) {
9069 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9071 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,
9072 TemplateArgs, CTAI.CanonicalConverted, CanonType);
9073
9074 // Build the fully-sugared type for this class template
9075 // specialization as the user wrote in the specialization
9076 // itself. This means that we'll pretty-print the type retrieved
9077 // from the specialization's declaration the way that the user
9078 // actually wrote the specialization, rather than formatting the
9079 // name based on the "canonical" representation used to store the
9080 // template arguments in the specialization.
9082 TemplateNameLoc,
9083 WrittenTy,
9084 /*FIXME:*/KWLoc);
9085 Friend->setAccess(AS_public);
9087 } else {
9088 // Add the specialization into its lexical context, so that it can
9089 // be seen when iterating through the list of declarations in that
9090 // context. However, specializations are not found by name lookup.
9092 }
9093
9094 if (SkipBody && SkipBody->ShouldSkip)
9095 return SkipBody->Previous;
9096
9097 Specialization->setInvalidDecl(Invalid);
9099 return Specialization;
9100}
9101
9103 MultiTemplateParamsArg TemplateParameterLists,
9104 Declarator &D) {
9105 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9106 ActOnDocumentableDecl(NewDecl);
9107 return NewDecl;
9108}
9109
9111 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9112 const IdentifierInfo *Name, SourceLocation NameLoc) {
9113 DeclContext *DC = CurContext;
9114
9115 if (!DC->getRedeclContext()->isFileContext()) {
9116 Diag(NameLoc,
9117 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9118 return nullptr;
9119 }
9120
9121 if (TemplateParameterLists.size() > 1) {
9122 Diag(NameLoc, diag::err_concept_extra_headers);
9123 return nullptr;
9124 }
9125
9126 TemplateParameterList *Params = TemplateParameterLists.front();
9127
9128 if (Params->size() == 0) {
9129 Diag(NameLoc, diag::err_concept_no_parameters);
9130 return nullptr;
9131 }
9132
9133 // Ensure that the parameter pack, if present, is the last parameter in the
9134 // template.
9135 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9136 ParamEnd = Params->end();
9137 ParamIt != ParamEnd; ++ParamIt) {
9138 Decl const *Param = *ParamIt;
9139 if (Param->isParameterPack()) {
9140 if (++ParamIt == ParamEnd)
9141 break;
9142 Diag(Param->getLocation(),
9143 diag::err_template_param_pack_must_be_last_template_parameter);
9144 return nullptr;
9145 }
9146 }
9147
9148 ConceptDecl *NewDecl =
9149 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
9150
9151 if (NewDecl->hasAssociatedConstraints()) {
9152 // C++2a [temp.concept]p4:
9153 // A concept shall not have associated constraints.
9154 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9155 NewDecl->setInvalidDecl();
9156 }
9157
9158 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9159 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9161 LookupName(Previous, S);
9162 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9163 /*AllowInlineNamespace*/ false);
9164
9165 // We cannot properly handle redeclarations until we parse the constraint
9166 // expression, so only inject the name if we are sure we are not redeclaring a
9167 // symbol
9168 if (Previous.empty())
9169 PushOnScopeChains(NewDecl, S, true);
9170
9171 return NewDecl;
9172}
9173
9175 bool Found = false;
9177 while (F.hasNext()) {
9178 NamedDecl *D = F.next();
9179 if (D == C) {
9180 F.erase();
9181 Found = true;
9182 break;
9183 }
9184 }
9185 F.done();
9186 return Found;
9187}
9188
9191 Expr *ConstraintExpr,
9192 const ParsedAttributesView &Attrs) {
9193 assert(!C->hasDefinition() && "Concept already defined");
9194 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {
9195 C->setInvalidDecl();
9196 return nullptr;
9197 }
9198 C->setDefinition(ConstraintExpr);
9199 ProcessDeclAttributeList(S, C, Attrs);
9200
9201 // Check for conflicting previous declaration.
9202 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9203 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9205 LookupName(Previous, S);
9206 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
9207 /*AllowInlineNamespace*/ false);
9208 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
9209 bool AddToScope = true;
9210 CheckConceptRedefinition(C, Previous, AddToScope);
9211
9213 if (!WasAlreadyAdded && AddToScope)
9214 PushOnScopeChains(C, S);
9215
9216 return C;
9217}
9218
9220 LookupResult &Previous, bool &AddToScope) {
9221 AddToScope = true;
9222
9223 if (Previous.empty())
9224 return;
9225
9226 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9227 if (!OldConcept) {
9228 auto *Old = Previous.getRepresentativeDecl();
9229 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9230 << NewDecl->getDeclName();
9231 notePreviousDefinition(Old, NewDecl->getLocation());
9232 AddToScope = false;
9233 return;
9234 }
9235 // Check if we can merge with a concept declaration.
9236 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9237 if (!IsSame) {
9238 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9239 << NewDecl->getDeclName();
9240 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9241 AddToScope = false;
9242 return;
9243 }
9244 if (hasReachableDefinition(OldConcept) &&
9245 IsRedefinitionInModule(NewDecl, OldConcept)) {
9246 Diag(NewDecl->getLocation(), diag::err_redefinition)
9247 << NewDecl->getDeclName();
9248 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9249 AddToScope = false;
9250 return;
9251 }
9252 if (!Previous.isSingleResult()) {
9253 // FIXME: we should produce an error in case of ambig and failed lookups.
9254 // Other decls (e.g. namespaces) also have this shortcoming.
9255 return;
9256 }
9257 // We unwrap canonical decl late to check for module visibility.
9258 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9259}
9260
9262 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);
9263 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9264 Diag(Loc, diag::err_recursive_concept) << CE;
9265 Diag(CE->getLocation(), diag::note_declared_at);
9266 return true;
9267 }
9268 // Concept template parameters don't have a definition and can't
9269 // be defined recursively.
9270 return false;
9271}
9272
9273/// \brief Strips various properties off an implicit instantiation
9274/// that has just been explicitly specialized.
9275static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9276 if (MinGW || (isa<FunctionDecl>(D) &&
9277 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9278 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9279
9280 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9281 FD->setInlineSpecified(false);
9282}
9283
9284/// Compute the diagnostic location for an explicit instantiation
9285// declaration or definition.
9287 NamedDecl* D, SourceLocation PointOfInstantiation) {
9288 // Explicit instantiations following a specialization have no effect and
9289 // hence no PointOfInstantiation. In that case, walk decl backwards
9290 // until a valid name loc is found.
9291 SourceLocation PrevDiagLoc = PointOfInstantiation;
9292 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9293 Prev = Prev->getPreviousDecl()) {
9294 PrevDiagLoc = Prev->getLocation();
9295 }
9296 assert(PrevDiagLoc.isValid() &&
9297 "Explicit instantiation without point of instantiation?");
9298 return PrevDiagLoc;
9299}
9300
9301bool
9304 NamedDecl *PrevDecl,
9306 SourceLocation PrevPointOfInstantiation,
9307 bool &HasNoEffect) {
9308 HasNoEffect = false;
9309
9310 switch (NewTSK) {
9311 case TSK_Undeclared:
9313 assert(
9314 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9315 "previous declaration must be implicit!");
9316 return false;
9317
9319 switch (PrevTSK) {
9320 case TSK_Undeclared:
9322 // Okay, we're just specializing something that is either already
9323 // explicitly specialized or has merely been mentioned without any
9324 // instantiation.
9325 return false;
9326
9328 if (PrevPointOfInstantiation.isInvalid()) {
9329 // The declaration itself has not actually been instantiated, so it is
9330 // still okay to specialize it.
9332 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());
9333 return false;
9334 }
9335 // Fall through
9336 [[fallthrough]];
9337
9340 assert((PrevTSK == TSK_ImplicitInstantiation ||
9341 PrevPointOfInstantiation.isValid()) &&
9342 "Explicit instantiation without point of instantiation?");
9343
9344 // C++ [temp.expl.spec]p6:
9345 // If a template, a member template or the member of a class template
9346 // is explicitly specialized then that specialization shall be declared
9347 // before the first use of that specialization that would cause an
9348 // implicit instantiation to take place, in every translation unit in
9349 // which such a use occurs; no diagnostic is required.
9350 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9351 // Is there any previous explicit specialization declaration?
9353 return false;
9354 }
9355
9356 Diag(NewLoc, diag::err_specialization_after_instantiation)
9357 << PrevDecl;
9358 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9359 << (PrevTSK != TSK_ImplicitInstantiation);
9360
9361 return true;
9362 }
9363 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9364
9366 switch (PrevTSK) {
9368 // This explicit instantiation declaration is redundant (that's okay).
9369 HasNoEffect = true;
9370 return false;
9371
9372 case TSK_Undeclared:
9374 // We're explicitly instantiating something that may have already been
9375 // implicitly instantiated; that's fine.
9376 return false;
9377
9379 // C++0x [temp.explicit]p4:
9380 // For a given set of template parameters, if an explicit instantiation
9381 // of a template appears after a declaration of an explicit
9382 // specialization for that template, the explicit instantiation has no
9383 // effect.
9384 HasNoEffect = true;
9385 return false;
9386
9388 // C++0x [temp.explicit]p10:
9389 // If an entity is the subject of both an explicit instantiation
9390 // declaration and an explicit instantiation definition in the same
9391 // translation unit, the definition shall follow the declaration.
9392 Diag(NewLoc,
9393 diag::err_explicit_instantiation_declaration_after_definition);
9394
9395 // Explicit instantiations following a specialization have no effect and
9396 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9397 // until a valid name loc is found.
9398 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9399 diag::note_explicit_instantiation_definition_here);
9400 HasNoEffect = true;
9401 return false;
9402 }
9403 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9404
9406 switch (PrevTSK) {
9407 case TSK_Undeclared:
9409 // We're explicitly instantiating something that may have already been
9410 // implicitly instantiated; that's fine.
9411 return false;
9412
9414 // C++ DR 259, C++0x [temp.explicit]p4:
9415 // For a given set of template parameters, if an explicit
9416 // instantiation of a template appears after a declaration of
9417 // an explicit specialization for that template, the explicit
9418 // instantiation has no effect.
9419 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9420 << PrevDecl;
9421 Diag(PrevDecl->getLocation(),
9422 diag::note_previous_template_specialization);
9423 HasNoEffect = true;
9424 return false;
9425
9427 // We're explicitly instantiating a definition for something for which we
9428 // were previously asked to suppress instantiations. That's fine.
9429
9430 // C++0x [temp.explicit]p4:
9431 // For a given set of template parameters, if an explicit instantiation
9432 // of a template appears after a declaration of an explicit
9433 // specialization for that template, the explicit instantiation has no
9434 // effect.
9435 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9436 // Is there any previous explicit specialization declaration?
9438 HasNoEffect = true;
9439 break;
9440 }
9441 }
9442
9443 return false;
9444
9446 // C++0x [temp.spec]p5:
9447 // For a given template and a given set of template-arguments,
9448 // - an explicit instantiation definition shall appear at most once
9449 // in a program,
9450
9451 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9452 Diag(NewLoc, (getLangOpts().MSVCCompat)
9453 ? diag::ext_explicit_instantiation_duplicate
9454 : diag::err_explicit_instantiation_duplicate)
9455 << PrevDecl;
9456 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9457 diag::note_previous_explicit_instantiation);
9458 HasNoEffect = true;
9459 return false;
9460 }
9461 }
9462
9463 llvm_unreachable("Missing specialization/instantiation case?");
9464}
9465
9467 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9469 // Remove anything from Previous that isn't a function template in
9470 // the correct context.
9471 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9472 LookupResult::Filter F = Previous.makeFilter();
9473 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9474 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9475 while (F.hasNext()) {
9477 if (!isa<FunctionTemplateDecl>(D)) {
9478 F.erase();
9479 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9480 continue;
9481 }
9482
9483 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9485 F.erase();
9486 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9487 continue;
9488 }
9489 }
9490 F.done();
9491
9492 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9493 if (Previous.empty()) {
9494 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9495 << IsFriend;
9496 for (auto &P : DiscardedCandidates)
9497 Diag(P.second->getLocation(),
9498 diag::note_dependent_function_template_spec_discard_reason)
9499 << P.first << IsFriend;
9500 return true;
9501 }
9502
9504 ExplicitTemplateArgs);
9505 return false;
9506}
9507
9509 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9510 LookupResult &Previous, bool QualifiedFriend) {
9511 // The set of function template specializations that could match this
9512 // explicit function template specialization.
9513 UnresolvedSet<8> Candidates;
9514 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9515 /*ForTakingAddress=*/false);
9516
9517 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9518 ConvertedTemplateArgs;
9519
9520 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9521 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9522 I != E; ++I) {
9523 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9524 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9525 // Only consider templates found within the same semantic lookup scope as
9526 // FD.
9527 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9529 continue;
9530
9531 QualType FT = FD->getType();
9532 // C++11 [dcl.constexpr]p8:
9533 // A constexpr specifier for a non-static member function that is not
9534 // a constructor declares that member function to be const.
9535 //
9536 // When matching a constexpr member function template specialization
9537 // against the primary template, we don't yet know whether the
9538 // specialization has an implicit 'const' (because we don't know whether
9539 // it will be a static member function until we know which template it
9540 // specializes). This rule was removed in C++14.
9541 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9542 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9543 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9544 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9545 if (OldMD && OldMD->isConst()) {
9546 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9548 EPI.TypeQuals.addConst();
9550 FPT->getParamTypes(), EPI);
9551 }
9552 }
9553
9555 if (ExplicitTemplateArgs)
9556 Args = *ExplicitTemplateArgs;
9557
9558 // C++ [temp.expl.spec]p11:
9559 // A trailing template-argument can be left unspecified in the
9560 // template-id naming an explicit function template specialization
9561 // provided it can be deduced from the function argument type.
9562 // Perform template argument deduction to determine whether we may be
9563 // specializing this template.
9564 // FIXME: It is somewhat wasteful to build
9565 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9566 FunctionDecl *Specialization = nullptr;
9568 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9569 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9571 // Template argument deduction failed; record why it failed, so
9572 // that we can provide nifty diagnostics.
9573 FailedCandidates.addCandidate().set(
9574 I.getPair(), FunTmpl->getTemplatedDecl(),
9575 MakeDeductionFailureInfo(Context, TDK, Info));
9576 (void)TDK;
9577 continue;
9578 }
9579
9580 // Target attributes are part of the cuda function signature, so
9581 // the deduced template's cuda target must match that of the
9582 // specialization. Given that C++ template deduction does not
9583 // take target attributes into account, we reject candidates
9584 // here that have a different target.
9585 if (LangOpts.CUDA &&
9587 /* IgnoreImplicitHDAttr = */ true) !=
9588 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9589 FailedCandidates.addCandidate().set(
9590 I.getPair(), FunTmpl->getTemplatedDecl(),
9593 continue;
9594 }
9595
9596 // Record this candidate.
9597 if (ExplicitTemplateArgs)
9598 ConvertedTemplateArgs[Specialization] = std::move(Args);
9599 Candidates.addDecl(Specialization, I.getAccess());
9600 }
9601 }
9602
9603 // For a qualified friend declaration (with no explicit marker to indicate
9604 // that a template specialization was intended), note all (template and
9605 // non-template) candidates.
9606 if (QualifiedFriend && Candidates.empty()) {
9607 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9608 << FD->getDeclName() << FDLookupContext;
9609 // FIXME: We should form a single candidate list and diagnose all
9610 // candidates at once, to get proper sorting and limiting.
9611 for (auto *OldND : Previous) {
9612 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9613 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9614 }
9615 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9616 return true;
9617 }
9618
9619 // Find the most specialized function template.
9621 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9622 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9623 PDiag(diag::err_function_template_spec_ambiguous)
9624 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9625 PDiag(diag::note_function_template_spec_matched));
9626
9627 if (Result == Candidates.end())
9628 return true;
9629
9630 // Ignore access information; it doesn't figure into redeclaration checking.
9631 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9632
9633 if (const auto *PT = Specialization->getPrimaryTemplate();
9634 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9635 auto Message = DSA->getMessage();
9636 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9637 << PT << !Message.empty() << Message;
9638 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9639 }
9640
9641 // C++23 [except.spec]p13:
9642 // An exception specification is considered to be needed when:
9643 // - [...]
9644 // - the exception specification is compared to that of another declaration
9645 // (e.g., an explicit specialization or an overriding virtual function);
9646 // - [...]
9647 //
9648 // The exception specification of a defaulted function is evaluated as
9649 // described above only when needed; similarly, the noexcept-specifier of a
9650 // specialization of a function template or member function of a class
9651 // template is instantiated only when needed.
9652 //
9653 // The standard doesn't specify what the "comparison with another declaration"
9654 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9655 // not state which properties of an explicit specialization must match the
9656 // primary template.
9657 //
9658 // We assume that an explicit specialization must correspond with (per
9659 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9660 // the declaration produced by substitution into the function template.
9661 //
9662 // Since the determination whether two function declarations correspond does
9663 // not consider exception specification, we only need to instantiate it once
9664 // we determine the primary template when comparing types per
9665 // [basic.link]p11.1.
9666 auto *SpecializationFPT =
9667 Specialization->getType()->castAs<FunctionProtoType>();
9668 // If the function has a dependent exception specification, resolve it after
9669 // we have selected the primary template so we can check whether it matches.
9670 if (getLangOpts().CPlusPlus17 &&
9671 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9672 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9673 return true;
9674
9676 = Specialization->getTemplateSpecializationInfo();
9677 assert(SpecInfo && "Function template specialization info missing?");
9678
9679 // Note: do not overwrite location info if previous template
9680 // specialization kind was explicit.
9682 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9683 Specialization->setLocation(FD->getLocation());
9684 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9685 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9686 // function can differ from the template declaration with respect to
9687 // the constexpr specifier.
9688 // FIXME: We need an update record for this AST mutation.
9689 // FIXME: What if there are multiple such prior declarations (for instance,
9690 // from different modules)?
9691 Specialization->setConstexprKind(FD->getConstexprKind());
9692 }
9693
9694 // FIXME: Check if the prior specialization has a point of instantiation.
9695 // If so, we have run afoul of .
9696
9697 // If this is a friend declaration, then we're not really declaring
9698 // an explicit specialization.
9699 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9700
9701 // Check the scope of this explicit specialization.
9702 if (!isFriend &&
9704 Specialization->getPrimaryTemplate(),
9706 false))
9707 return true;
9708
9709 // C++ [temp.expl.spec]p6:
9710 // If a template, a member template or the member of a class template is
9711 // explicitly specialized then that specialization shall be declared
9712 // before the first use of that specialization that would cause an implicit
9713 // instantiation to take place, in every translation unit in which such a
9714 // use occurs; no diagnostic is required.
9715 bool HasNoEffect = false;
9716 if (!isFriend &&
9721 SpecInfo->getPointOfInstantiation(),
9722 HasNoEffect))
9723 return true;
9724
9725 // Mark the prior declaration as an explicit specialization, so that later
9726 // clients know that this is an explicit specialization.
9727 // A dependent friend specialization which has a definition should be treated
9728 // as explicit specialization, despite being invalid.
9729 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9730 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9731 // Since explicit specializations do not inherit '=delete' from their
9732 // primary function template - check if the 'specialization' that was
9733 // implicitly generated (during template argument deduction for partial
9734 // ordering) from the most specialized of all the function templates that
9735 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9736 // first check that it was implicitly generated during template argument
9737 // deduction by making sure it wasn't referenced, and then reset the deleted
9738 // flag to not-deleted, so that we can inherit that information from 'FD'.
9739 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9740 !Specialization->getCanonicalDecl()->isReferenced()) {
9741 // FIXME: This assert will not hold in the presence of modules.
9742 assert(
9743 Specialization->getCanonicalDecl() == Specialization &&
9744 "This must be the only existing declaration of this specialization");
9745 // FIXME: We need an update record for this AST mutation.
9746 Specialization->setDeletedAsWritten(false);
9747 }
9748 // FIXME: We need an update record for this AST mutation.
9751 }
9752
9753 // Turn the given function declaration into a function template
9754 // specialization, with the template arguments from the previous
9755 // specialization.
9756 // Take copies of (semantic and syntactic) template argument lists.
9758 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9759 FD->setFunctionTemplateSpecialization(
9760 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9762 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9763
9764 // A function template specialization inherits the target attributes
9765 // of its template. (We require the attributes explicitly in the
9766 // code to match, but a template may have implicit attributes by
9767 // virtue e.g. of being constexpr, and it passes these implicit
9768 // attributes on to its specializations.)
9769 if (LangOpts.CUDA)
9770 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9771
9772 // The "previous declaration" for this function template specialization is
9773 // the prior function template specialization.
9774 Previous.clear();
9775 Previous.addDecl(Specialization);
9776 return false;
9777}
9778
9779bool
9781 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9782 "Only for non-template members");
9783
9784 // Try to find the member we are instantiating.
9785 NamedDecl *FoundInstantiation = nullptr;
9786 NamedDecl *Instantiation = nullptr;
9787 NamedDecl *InstantiatedFrom = nullptr;
9788 MemberSpecializationInfo *MSInfo = nullptr;
9789
9790 if (Previous.empty()) {
9791 // Nowhere to look anyway.
9792 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9793 UnresolvedSet<8> Candidates;
9794 for (NamedDecl *Candidate : Previous) {
9795 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9796 // Ignore any candidates that aren't member functions.
9797 if (!Method)
9798 continue;
9799
9800 QualType Adjusted = Function->getType();
9801 if (!hasExplicitCallingConv(Adjusted))
9802 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9803 // Ignore any candidates with the wrong type.
9804 // This doesn't handle deduced return types, but both function
9805 // declarations should be undeduced at this point.
9806 // FIXME: The exception specification should probably be ignored when
9807 // comparing the types.
9808 if (!Context.hasSameType(Adjusted, Method->getType()))
9809 continue;
9810
9811 // Ignore any candidates with unsatisfied constraints.
9812 if (ConstraintSatisfaction Satisfaction;
9813 Method->getTrailingRequiresClause() &&
9814 (CheckFunctionConstraints(Method, Satisfaction,
9815 /*UsageLoc=*/Member->getLocation(),
9816 /*ForOverloadResolution=*/true) ||
9817 !Satisfaction.IsSatisfied))
9818 continue;
9819
9820 Candidates.addDecl(Candidate);
9821 }
9822
9823 // If we have no viable candidates left after filtering, we are done.
9824 if (Candidates.empty())
9825 return false;
9826
9827 // Find the function that is more constrained than every other function it
9828 // has been compared to.
9829 UnresolvedSetIterator Best = Candidates.begin();
9830 CXXMethodDecl *BestMethod = nullptr;
9831 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9832 I != E; ++I) {
9833 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9834 if (I == Best ||
9835 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9836 Best = I;
9837 BestMethod = Method;
9838 }
9839 }
9840
9841 FoundInstantiation = *Best;
9842 Instantiation = BestMethod;
9843 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9844 MSInfo = BestMethod->getMemberSpecializationInfo();
9845
9846 // Make sure the best candidate is more constrained than all of the others.
9847 bool Ambiguous = false;
9848 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9849 I != E; ++I) {
9850 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9851 if (I != Best &&
9852 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9853 Ambiguous = true;
9854 break;
9855 }
9856 }
9857
9858 if (Ambiguous) {
9859 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9860 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9861 for (NamedDecl *Candidate : Candidates) {
9862 Candidate = Candidate->getUnderlyingDecl();
9863 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9864 << Candidate;
9865 }
9866 return true;
9867 }
9868 } else if (isa<VarDecl>(Member)) {
9869 VarDecl *PrevVar;
9870 if (Previous.isSingleResult() &&
9871 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9872 if (PrevVar->isStaticDataMember()) {
9873 FoundInstantiation = Previous.getRepresentativeDecl();
9874 Instantiation = PrevVar;
9875 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9876 MSInfo = PrevVar->getMemberSpecializationInfo();
9877 }
9878 } else if (isa<RecordDecl>(Member)) {
9879 CXXRecordDecl *PrevRecord;
9880 if (Previous.isSingleResult() &&
9881 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9882 FoundInstantiation = Previous.getRepresentativeDecl();
9883 Instantiation = PrevRecord;
9884 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9885 MSInfo = PrevRecord->getMemberSpecializationInfo();
9886 }
9887 } else if (isa<EnumDecl>(Member)) {
9888 EnumDecl *PrevEnum;
9889 if (Previous.isSingleResult() &&
9890 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9891 FoundInstantiation = Previous.getRepresentativeDecl();
9892 Instantiation = PrevEnum;
9893 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9894 MSInfo = PrevEnum->getMemberSpecializationInfo();
9895 }
9896 }
9897
9898 if (!Instantiation) {
9899 // There is no previous declaration that matches. Since member
9900 // specializations are always out-of-line, the caller will complain about
9901 // this mismatch later.
9902 return false;
9903 }
9904
9905 // A member specialization in a friend declaration isn't really declaring
9906 // an explicit specialization, just identifying a specific (possibly implicit)
9907 // specialization. Don't change the template specialization kind.
9908 //
9909 // FIXME: Is this really valid? Other compilers reject.
9910 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9911 // Preserve instantiation information.
9912 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9913 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9914 cast<CXXMethodDecl>(InstantiatedFrom),
9915 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9916 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9917 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9918 cast<CXXRecordDecl>(InstantiatedFrom),
9919 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9920 }
9921
9922 Previous.clear();
9923 Previous.addDecl(FoundInstantiation);
9924 return false;
9925 }
9926
9927 // Make sure that this is a specialization of a member.
9928 if (!InstantiatedFrom) {
9929 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9930 << Member;
9931 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9932 return true;
9933 }
9934
9935 // C++ [temp.expl.spec]p6:
9936 // If a template, a member template or the member of a class template is
9937 // explicitly specialized then that specialization shall be declared
9938 // before the first use of that specialization that would cause an implicit
9939 // instantiation to take place, in every translation unit in which such a
9940 // use occurs; no diagnostic is required.
9941 assert(MSInfo && "Member specialization info missing?");
9942
9943 bool HasNoEffect = false;
9946 Instantiation,
9948 MSInfo->getPointOfInstantiation(),
9949 HasNoEffect))
9950 return true;
9951
9952 // Check the scope of this explicit specialization.
9954 InstantiatedFrom,
9955 Instantiation, Member->getLocation(),
9956 false))
9957 return true;
9958
9959 // Note that this member specialization is an "instantiation of" the
9960 // corresponding member of the original template.
9961 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9962 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9963 if (InstantiationFunction->getTemplateSpecializationKind() ==
9965 // Explicit specializations of member functions of class templates do not
9966 // inherit '=delete' from the member function they are specializing.
9967 if (InstantiationFunction->isDeleted()) {
9968 // FIXME: This assert will not hold in the presence of modules.
9969 assert(InstantiationFunction->getCanonicalDecl() ==
9970 InstantiationFunction);
9971 // FIXME: We need an update record for this AST mutation.
9972 InstantiationFunction->setDeletedAsWritten(false);
9973 }
9974 }
9975
9976 MemberFunction->setInstantiationOfMemberFunction(
9977 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9978 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9979 MemberVar->setInstantiationOfStaticDataMember(
9980 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9981 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9982 MemberClass->setInstantiationOfMemberClass(
9983 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9984 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9985 MemberEnum->setInstantiationOfMemberEnum(
9986 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9987 } else {
9988 llvm_unreachable("unknown member specialization kind");
9989 }
9990
9991 // Save the caller the trouble of having to figure out which declaration
9992 // this specialization matches.
9993 Previous.clear();
9994 Previous.addDecl(FoundInstantiation);
9995 return false;
9996}
9997
9998/// Complete the explicit specialization of a member of a class template by
9999/// updating the instantiated member to be marked as an explicit specialization.
10000///
10001/// \param OrigD The member declaration instantiated from the template.
10002/// \param Loc The location of the explicit specialization of the member.
10003template<typename DeclT>
10004static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10006 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10007 return;
10008
10009 // FIXME: Inform AST mutation listeners of this AST mutation.
10010 // FIXME: If there are multiple in-class declarations of the member (from
10011 // multiple modules, or a declaration and later definition of a member type),
10012 // should we update all of them?
10013 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10014 OrigD->setLocation(Loc);
10015}
10016
10019 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10020 if (Instantiation == Member)
10021 return;
10022
10023 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10024 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10025 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10026 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10027 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10028 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10029 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10030 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10031 else
10032 llvm_unreachable("unknown member specialization kind");
10033}
10034
10035/// Check the scope of an explicit instantiation.
10036///
10037/// \returns true if a serious error occurs, false otherwise.
10039 SourceLocation InstLoc,
10040 bool WasQualifiedName) {
10042 DeclContext *CurContext = S.CurContext->getRedeclContext();
10043
10044 if (CurContext->isRecord()) {
10045 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10046 << D;
10047 return true;
10048 }
10049
10050 // C++11 [temp.explicit]p3:
10051 // An explicit instantiation shall appear in an enclosing namespace of its
10052 // template. If the name declared in the explicit instantiation is an
10053 // unqualified name, the explicit instantiation shall appear in the
10054 // namespace where its template is declared or, if that namespace is inline
10055 // (7.3.1), any namespace from its enclosing namespace set.
10056 //
10057 // This is DR275, which we do not retroactively apply to C++98/03.
10058 if (WasQualifiedName) {
10059 if (CurContext->Encloses(OrigContext))
10060 return false;
10061 } else {
10062 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10063 return false;
10064 }
10065
10066 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10067 if (WasQualifiedName)
10068 S.Diag(InstLoc,
10069 S.getLangOpts().CPlusPlus11?
10070 diag::err_explicit_instantiation_out_of_scope :
10071 diag::warn_explicit_instantiation_out_of_scope_0x)
10072 << D << NS;
10073 else
10074 S.Diag(InstLoc,
10075 S.getLangOpts().CPlusPlus11?
10076 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10077 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10078 << D << NS;
10079 } else
10080 S.Diag(InstLoc,
10081 S.getLangOpts().CPlusPlus11?
10082 diag::err_explicit_instantiation_must_be_global :
10083 diag::warn_explicit_instantiation_must_be_global_0x)
10084 << D;
10085 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10086 return false;
10087}
10088
10089/// Common checks for whether an explicit instantiation of \p D is valid.
10091 SourceLocation InstLoc,
10092 bool WasQualifiedName,
10094 // C++ [temp.explicit]p13:
10095 // An explicit instantiation declaration shall not name a specialization of
10096 // a template with internal linkage.
10098 D->getFormalLinkage() == Linkage::Internal) {
10099 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10100 return true;
10101 }
10102
10103 // C++11 [temp.explicit]p3: [DR 275]
10104 // An explicit instantiation shall appear in an enclosing namespace of its
10105 // template.
10106 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10107 return true;
10108
10109 return false;
10110}
10111
10112/// Determine whether the given scope specifier has a template-id in it.
10114 // C++11 [temp.explicit]p3:
10115 // If the explicit instantiation is for a member function, a member class
10116 // or a static data member of a class template specialization, the name of
10117 // the class template specialization in the qualified-id for the member
10118 // name shall be a simple-template-id.
10119 //
10120 // C++98 has the same restriction, just worded differently.
10121 for (NestedNameSpecifier NNS = SS.getScopeRep();
10123 /**/) {
10124 const Type *T = NNS.getAsType();
10125 if (isa<TemplateSpecializationType>(T))
10126 return true;
10127 NNS = T->getPrefix();
10128 }
10129 return false;
10130}
10131
10132/// Make a dllexport or dllimport attr on a class template specialization take
10133/// effect.
10136 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10137 assert(A && "dllExportImportClassTemplateSpecialization called "
10138 "on Def without dllexport or dllimport");
10139
10140 // We reject explicit instantiations in class scope, so there should
10141 // never be any delayed exported classes to worry about.
10142 assert(S.DelayedDllExportClasses.empty() &&
10143 "delayed exports present at explicit instantiation");
10145
10146 // Propagate attribute to base class templates.
10147 for (auto &B : Def->bases()) {
10148 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10149 B.getType()->getAsCXXRecordDecl()))
10151 }
10152
10154}
10155
10157 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10158 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10159 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10160 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10161 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10162 // Find the class template we're specializing
10163 TemplateName Name = TemplateD.get();
10164 TemplateDecl *TD = Name.getAsTemplateDecl();
10165 // Check that the specialization uses the same tag kind as the
10166 // original template.
10168 assert(Kind != TagTypeKind::Enum &&
10169 "Invalid enum tag in class template explicit instantiation!");
10170
10171 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10172
10173 if (!ClassTemplate) {
10174 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10175 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10176 Diag(TD->getLocation(), diag::note_previous_use);
10177 return true;
10178 }
10179
10180 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10181 Kind, /*isDefinition*/false, KWLoc,
10182 ClassTemplate->getIdentifier())) {
10183 Diag(KWLoc, diag::err_use_with_wrong_tag)
10184 << ClassTemplate
10186 ClassTemplate->getTemplatedDecl()->getKindName());
10187 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10188 diag::note_previous_use);
10189 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10190 }
10191
10192 // C++0x [temp.explicit]p2:
10193 // There are two forms of explicit instantiation: an explicit instantiation
10194 // definition and an explicit instantiation declaration. An explicit
10195 // instantiation declaration begins with the extern keyword. [...]
10196 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10199
10201 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10202 // Check for dllexport class template instantiation declarations,
10203 // except for MinGW mode.
10204 for (const ParsedAttr &AL : Attr) {
10205 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10206 Diag(ExternLoc,
10207 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10208 Diag(AL.getLoc(), diag::note_attribute);
10209 break;
10210 }
10211 }
10212
10213 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10214 Diag(ExternLoc,
10215 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10216 Diag(A->getLocation(), diag::note_attribute);
10217 }
10218 }
10219
10220 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10221 // instantiation declarations for most purposes.
10222 bool DLLImportExplicitInstantiationDef = false;
10225 // Check for dllimport class template instantiation definitions.
10226 bool DLLImport =
10227 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10228 for (const ParsedAttr &AL : Attr) {
10229 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10230 DLLImport = true;
10231 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10232 // dllexport trumps dllimport here.
10233 DLLImport = false;
10234 break;
10235 }
10236 }
10237 if (DLLImport) {
10239 DLLImportExplicitInstantiationDef = true;
10240 }
10241 }
10242
10243 // Translate the parser's template argument list in our AST format.
10244 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10245 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10246
10247 // Check that the template argument list is well-formed for this
10248 // template.
10250 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10251 /*DefaultArgs=*/{}, false, CTAI,
10252 /*UpdateArgsWithConversions=*/true,
10253 /*ConstraintsNotSatisfied=*/nullptr))
10254 return true;
10255
10256 // Find the class template specialization declaration that
10257 // corresponds to these arguments.
10258 void *InsertPos = nullptr;
10260 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);
10261
10262 TemplateSpecializationKind PrevDecl_TSK
10263 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10264
10265 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10266 Context.getTargetInfo().getTriple().isOSCygMing()) {
10267 // Check for dllexport class template instantiation definitions in MinGW
10268 // mode, if a previous declaration of the instantiation was seen.
10269 for (const ParsedAttr &AL : Attr) {
10270 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10271 Diag(AL.getLoc(),
10272 diag::warn_attribute_dllexport_explicit_instantiation_def);
10273 break;
10274 }
10275 }
10276 }
10277
10278 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10279 SS.isSet(), TSK))
10280 return true;
10281
10283
10284 bool HasNoEffect = false;
10285 if (PrevDecl) {
10286 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10287 PrevDecl, PrevDecl_TSK,
10288 PrevDecl->getPointOfInstantiation(),
10289 HasNoEffect))
10290 return PrevDecl;
10291
10292 // Even though HasNoEffect == true means that this explicit instantiation
10293 // has no effect on semantics, we go on to put its syntax in the AST.
10294
10295 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10296 PrevDecl_TSK == TSK_Undeclared) {
10297 // Since the only prior class template specialization with these
10298 // arguments was referenced but not declared, reuse that
10299 // declaration node as our own, updating the source location
10300 // for the template name to reflect our new declaration.
10301 // (Other source locations will be updated later.)
10302 Specialization = PrevDecl;
10303 Specialization->setLocation(TemplateNameLoc);
10304 PrevDecl = nullptr;
10305 }
10306
10307 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10308 DLLImportExplicitInstantiationDef) {
10309 // The new specialization might add a dllimport attribute.
10310 HasNoEffect = false;
10311 }
10312 }
10313
10314 if (!Specialization) {
10315 // Create a new class template specialization declaration node for
10316 // this explicit specialization.
10318 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10319 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);
10321
10322 // A MSInheritanceAttr attached to the previous declaration must be
10323 // propagated to the new node prior to instantiation.
10324 if (PrevDecl) {
10325 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10326 auto *Clone = A->clone(getASTContext());
10327 Clone->setInherited(true);
10328 Specialization->addAttr(Clone);
10330 }
10331 }
10332
10333 if (!HasNoEffect && !PrevDecl) {
10334 // Insert the new specialization.
10335 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10336 }
10337 }
10338
10339 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10340
10341 // Set source locations for keywords.
10342 Specialization->setExternKeywordLoc(ExternLoc);
10343 Specialization->setTemplateKeywordLoc(TemplateLoc);
10344 Specialization->setBraceRange(SourceRange());
10345
10346 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10349
10350 // Add the explicit instantiation into its lexical context. However,
10351 // since explicit instantiations are never found by name lookup, we
10352 // just put it into the declaration context directly.
10353 Specialization->setLexicalDeclContext(CurContext);
10355
10356 // Syntax is now OK, so return if it has no other effect on semantics.
10357 if (HasNoEffect) {
10358 // Set the template specialization kind.
10359 Specialization->setTemplateSpecializationKind(TSK);
10360 return Specialization;
10361 }
10362
10363 // C++ [temp.explicit]p3:
10364 // A definition of a class template or class member template
10365 // shall be in scope at the point of the explicit instantiation of
10366 // the class template or class member template.
10367 //
10368 // This check comes when we actually try to perform the
10369 // instantiation.
10371 = cast_or_null<ClassTemplateSpecializationDecl>(
10372 Specialization->getDefinition());
10373 if (!Def)
10375 /*Complain=*/true,
10376 CTAI.StrictPackMatch);
10377 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10378 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10379 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10380 }
10381
10382 // Instantiate the members of this class template specialization.
10383 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10384 Specialization->getDefinition());
10385 if (Def) {
10387 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10388 // TSK_ExplicitInstantiationDefinition
10389 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10391 DLLImportExplicitInstantiationDef)) {
10392 // FIXME: Need to notify the ASTMutationListener that we did this.
10394
10395 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10397 // An explicit instantiation definition can add a dll attribute to a
10398 // template with a previous instantiation declaration. MinGW doesn't
10399 // allow this.
10400 auto *A = cast<InheritableAttr>(
10402 A->setInherited(true);
10403 Def->addAttr(A);
10405 }
10406 }
10407
10408 // Fix a TSK_ImplicitInstantiation followed by a
10409 // TSK_ExplicitInstantiationDefinition
10410 bool NewlyDLLExported =
10411 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10412 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10414 // An explicit instantiation definition can add a dll attribute to a
10415 // template with a previous implicit instantiation. MinGW doesn't allow
10416 // this. We limit clang to only adding dllexport, to avoid potentially
10417 // strange codegen behavior. For example, if we extend this conditional
10418 // to dllimport, and we have a source file calling a method on an
10419 // implicitly instantiated template class instance and then declaring a
10420 // dllimport explicit instantiation definition for the same template
10421 // class, the codegen for the method call will not respect the dllimport,
10422 // while it will with cl. The Def will already have the DLL attribute,
10423 // since the Def and Specialization will be the same in the case of
10424 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10425 // attribute to the Specialization; we just need to make it take effect.
10426 assert(Def == Specialization &&
10427 "Def and Specialization should match for implicit instantiation");
10429 }
10430
10431 // In MinGW mode, export the template instantiation if the declaration
10432 // was marked dllexport.
10433 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10434 Context.getTargetInfo().getTriple().isOSCygMing() &&
10435 PrevDecl->hasAttr<DLLExportAttr>()) {
10437 }
10438
10439 // Set the template specialization kind. Make sure it is set before
10440 // instantiating the members which will trigger ASTConsumer callbacks.
10441 Specialization->setTemplateSpecializationKind(TSK);
10442 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10443 } else {
10444
10445 // Set the template specialization kind.
10446 Specialization->setTemplateSpecializationKind(TSK);
10447 }
10448
10449 return Specialization;
10450}
10451
10454 SourceLocation TemplateLoc, unsigned TagSpec,
10455 SourceLocation KWLoc, CXXScopeSpec &SS,
10456 IdentifierInfo *Name, SourceLocation NameLoc,
10457 const ParsedAttributesView &Attr) {
10458
10459 bool Owned = false;
10460 bool IsDependent = false;
10461 Decl *TagD =
10462 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10463 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10464 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10465 false, TypeResult(), /*IsTypeSpecifier*/ false,
10466 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10467 .get();
10468 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10469
10470 if (!TagD)
10471 return true;
10472
10473 TagDecl *Tag = cast<TagDecl>(TagD);
10474 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10475
10476 if (Tag->isInvalidDecl())
10477 return true;
10478
10479 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10481 if (!Pattern) {
10482 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10484 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10485 return true;
10486 }
10487
10488 // C++0x [temp.explicit]p2:
10489 // If the explicit instantiation is for a class or member class, the
10490 // elaborated-type-specifier in the declaration shall include a
10491 // simple-template-id.
10492 //
10493 // C++98 has the same restriction, just worded differently.
10495 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10496 << Record << SS.getRange();
10497
10498 // C++0x [temp.explicit]p2:
10499 // There are two forms of explicit instantiation: an explicit instantiation
10500 // definition and an explicit instantiation declaration. An explicit
10501 // instantiation declaration begins with the extern keyword. [...]
10505
10506 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10507
10508 // Verify that it is okay to explicitly instantiate here.
10509 CXXRecordDecl *PrevDecl
10510 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10511 if (!PrevDecl && Record->getDefinition())
10512 PrevDecl = Record;
10513 if (PrevDecl) {
10515 bool HasNoEffect = false;
10516 assert(MSInfo && "No member specialization information?");
10517 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10518 PrevDecl,
10520 MSInfo->getPointOfInstantiation(),
10521 HasNoEffect))
10522 return true;
10523 if (HasNoEffect)
10524 return TagD;
10525 }
10526
10527 CXXRecordDecl *RecordDef
10528 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10529 if (!RecordDef) {
10530 // C++ [temp.explicit]p3:
10531 // A definition of a member class of a class template shall be in scope
10532 // at the point of an explicit instantiation of the member class.
10533 CXXRecordDecl *Def
10534 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10535 if (!Def) {
10536 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10537 << 0 << Record->getDeclName() << Record->getDeclContext();
10538 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10539 << Pattern;
10540 return true;
10541 } else {
10542 if (InstantiateClass(NameLoc, Record, Def,
10544 TSK))
10545 return true;
10546
10547 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10548 if (!RecordDef)
10549 return true;
10550 }
10551 }
10552
10553 // Instantiate all of the members of the class.
10554 InstantiateClassMembers(NameLoc, RecordDef,
10556
10558 MarkVTableUsed(NameLoc, RecordDef, true);
10559
10560 // FIXME: We don't have any representation for explicit instantiations of
10561 // member classes. Such a representation is not needed for compilation, but it
10562 // should be available for clients that want to see all of the declarations in
10563 // the source code.
10564 return TagD;
10565}
10566
10568 SourceLocation ExternLoc,
10569 SourceLocation TemplateLoc,
10570 Declarator &D) {
10571 // Explicit instantiations always require a name.
10572 // TODO: check if/when DNInfo should replace Name.
10574 DeclarationName Name = NameInfo.getName();
10575 if (!Name) {
10576 if (!D.isInvalidType())
10577 Diag(D.getDeclSpec().getBeginLoc(),
10578 diag::err_explicit_instantiation_requires_name)
10579 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10580
10581 return true;
10582 }
10583
10584 // Get the innermost enclosing declaration scope.
10585 S = S->getDeclParent();
10586
10587 // Determine the type of the declaration.
10589 QualType R = T->getType();
10590 if (R.isNull())
10591 return true;
10592
10593 // C++ [dcl.stc]p1:
10594 // A storage-class-specifier shall not be specified in [...] an explicit
10595 // instantiation (14.7.2) directive.
10596 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10597 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10598 << Name;
10599 return true;
10600 } else if (D.getDeclSpec().getStorageClassSpec()
10602 // Complain about then remove the storage class specifier.
10603 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10604 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10605
10606 D.getMutableDeclSpec().ClearStorageClassSpecs();
10607 }
10608
10609 // C++0x [temp.explicit]p1:
10610 // [...] An explicit instantiation of a function template shall not use the
10611 // inline or constexpr specifiers.
10612 // Presumably, this also applies to member functions of class templates as
10613 // well.
10614 if (D.getDeclSpec().isInlineSpecified())
10615 Diag(D.getDeclSpec().getInlineSpecLoc(),
10617 diag::err_explicit_instantiation_inline :
10618 diag::warn_explicit_instantiation_inline_0x)
10619 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10620 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10621 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10622 // not already specified.
10623 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10624 diag::err_explicit_instantiation_constexpr);
10625
10626 // A deduction guide is not on the list of entities that can be explicitly
10627 // instantiated.
10628 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10629 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10630 << /*explicit instantiation*/ 0;
10631 return true;
10632 }
10633
10634 // C++0x [temp.explicit]p2:
10635 // There are two forms of explicit instantiation: an explicit instantiation
10636 // definition and an explicit instantiation declaration. An explicit
10637 // instantiation declaration begins with the extern keyword. [...]
10641
10642 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10643 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10644 /*ObjectType=*/QualType());
10645
10646 if (!R->isFunctionType()) {
10647 // C++ [temp.explicit]p1:
10648 // A [...] static data member of a class template can be explicitly
10649 // instantiated from the member definition associated with its class
10650 // template.
10651 // C++1y [temp.explicit]p1:
10652 // A [...] variable [...] template specialization can be explicitly
10653 // instantiated from its template.
10654 if (Previous.isAmbiguous())
10655 return true;
10656
10657 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10658 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10659
10660 if (!PrevTemplate) {
10661 if (!Prev || !Prev->isStaticDataMember()) {
10662 // We expect to see a static data member here.
10663 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10664 << Name;
10665 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10666 P != PEnd; ++P)
10667 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10668 return true;
10669 }
10670
10672 // FIXME: Check for explicit specialization?
10673 Diag(D.getIdentifierLoc(),
10674 diag::err_explicit_instantiation_data_member_not_instantiated)
10675 << Prev;
10676 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10677 // FIXME: Can we provide a note showing where this was declared?
10678 return true;
10679 }
10680 } else {
10681 // Explicitly instantiate a variable template.
10682
10683 // C++1y [dcl.spec.auto]p6:
10684 // ... A program that uses auto or decltype(auto) in a context not
10685 // explicitly allowed in this section is ill-formed.
10686 //
10687 // This includes auto-typed variable template instantiations.
10688 if (R->isUndeducedType()) {
10689 Diag(T->getTypeLoc().getBeginLoc(),
10690 diag::err_auto_not_allowed_var_inst);
10691 return true;
10692 }
10693
10694 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10695 // C++1y [temp.explicit]p3:
10696 // If the explicit instantiation is for a variable, the unqualified-id
10697 // in the declaration shall be a template-id.
10698 Diag(D.getIdentifierLoc(),
10699 diag::err_explicit_instantiation_without_template_id)
10700 << PrevTemplate;
10701 Diag(PrevTemplate->getLocation(),
10702 diag::note_explicit_instantiation_here);
10703 return true;
10704 }
10705
10706 // Translate the parser's template argument list into our AST format.
10707 TemplateArgumentListInfo TemplateArgs =
10708 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10709
10710 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10711 D.getIdentifierLoc(), TemplateArgs);
10712 if (Res.isInvalid())
10713 return true;
10714
10715 if (!Res.isUsable()) {
10716 // We somehow specified dependent template arguments in an explicit
10717 // instantiation. This should probably only happen during error
10718 // recovery.
10719 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10720 return true;
10721 }
10722
10723 // Ignore access control bits, we don't need them for redeclaration
10724 // checking.
10725 Prev = cast<VarDecl>(Res.get());
10726 }
10727
10728 // C++0x [temp.explicit]p2:
10729 // If the explicit instantiation is for a member function, a member class
10730 // or a static data member of a class template specialization, the name of
10731 // the class template specialization in the qualified-id for the member
10732 // name shall be a simple-template-id.
10733 //
10734 // C++98 has the same restriction, just worded differently.
10735 //
10736 // This does not apply to variable template specializations, where the
10737 // template-id is in the unqualified-id instead.
10738 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10739 Diag(D.getIdentifierLoc(),
10740 diag::ext_explicit_instantiation_without_qualified_id)
10741 << Prev << D.getCXXScopeSpec().getRange();
10742
10743 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10744
10745 // Verify that it is okay to explicitly instantiate here.
10748 bool HasNoEffect = false;
10749 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10750 PrevTSK, POI, HasNoEffect))
10751 return true;
10752
10753 if (!HasNoEffect) {
10754 // Instantiate static data member or variable template.
10755 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10756 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10757 VTSD->setExternKeywordLoc(ExternLoc);
10758 VTSD->setTemplateKeywordLoc(TemplateLoc);
10759 }
10760
10761 // Merge attributes.
10762 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10763 if (PrevTemplate)
10764 ProcessAPINotes(Prev);
10765
10767 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10768 }
10769
10770 // Check the new variable specialization against the parsed input.
10771 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10772 Diag(T->getTypeLoc().getBeginLoc(),
10773 diag::err_invalid_var_template_spec_type)
10774 << 0 << PrevTemplate << R << Prev->getType();
10775 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10776 << 2 << PrevTemplate->getDeclName();
10777 return true;
10778 }
10779
10780 // FIXME: Create an ExplicitInstantiation node?
10781 return (Decl*) nullptr;
10782 }
10783
10784 // If the declarator is a template-id, translate the parser's template
10785 // argument list into our AST format.
10786 bool HasExplicitTemplateArgs = false;
10787 TemplateArgumentListInfo TemplateArgs;
10788 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10789 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10790 HasExplicitTemplateArgs = true;
10791 }
10792
10793 // C++ [temp.explicit]p1:
10794 // A [...] function [...] can be explicitly instantiated from its template.
10795 // A member function [...] of a class template can be explicitly
10796 // instantiated from the member definition associated with its class
10797 // template.
10798 UnresolvedSet<8> TemplateMatches;
10799 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10801 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10802 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10803 P != PEnd; ++P) {
10804 NamedDecl *Prev = *P;
10805 if (!HasExplicitTemplateArgs) {
10806 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10807 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10808 /*AdjustExceptionSpec*/true);
10809 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10810 if (Method->getPrimaryTemplate()) {
10811 TemplateMatches.addDecl(Method, P.getAccess());
10812 } else {
10813 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10814 C.FoundDecl = P.getPair();
10815 C.Function = Method;
10816 C.Viable = true;
10818 if (Method->getTrailingRequiresClause() &&
10819 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10820 /*ForOverloadResolution=*/true) ||
10821 !S.IsSatisfied)) {
10822 C.Viable = false;
10824 }
10825 }
10826 }
10827 }
10828 }
10829
10830 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10831 if (!FunTmpl)
10832 continue;
10833
10834 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10835 FunctionDecl *Specialization = nullptr;
10837 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10838 Specialization, Info);
10840 // Keep track of almost-matches.
10841 FailedTemplateCandidates.addCandidate().set(
10842 P.getPair(), FunTmpl->getTemplatedDecl(),
10843 MakeDeductionFailureInfo(Context, TDK, Info));
10844 (void)TDK;
10845 continue;
10846 }
10847
10848 // Target attributes are part of the cuda function signature, so
10849 // the cuda target of the instantiated function must match that of its
10850 // template. Given that C++ template deduction does not take
10851 // target attributes into account, we reject candidates here that
10852 // have a different target.
10853 if (LangOpts.CUDA &&
10855 /* IgnoreImplicitHDAttr = */ true) !=
10856 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10857 FailedTemplateCandidates.addCandidate().set(
10858 P.getPair(), FunTmpl->getTemplatedDecl(),
10861 continue;
10862 }
10863
10864 TemplateMatches.addDecl(Specialization, P.getAccess());
10865 }
10866
10867 FunctionDecl *Specialization = nullptr;
10868 if (!NonTemplateMatches.empty()) {
10869 unsigned Msg = 0;
10870 OverloadCandidateDisplayKind DisplayKind;
10872 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10873 Best)) {
10874 case OR_Success:
10875 case OR_Deleted:
10876 Specialization = cast<FunctionDecl>(Best->Function);
10877 break;
10878 case OR_Ambiguous:
10879 Msg = diag::err_explicit_instantiation_ambiguous;
10880 DisplayKind = OCD_AmbiguousCandidates;
10881 break;
10883 Msg = diag::err_explicit_instantiation_no_candidate;
10884 DisplayKind = OCD_AllCandidates;
10885 break;
10886 }
10887 if (Msg) {
10888 PartialDiagnostic Diag = PDiag(Msg) << Name;
10889 NonTemplateMatches.NoteCandidates(
10890 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10891 {});
10892 return true;
10893 }
10894 }
10895
10896 if (!Specialization) {
10897 // Find the most specialized function template specialization.
10899 TemplateMatches.begin(), TemplateMatches.end(),
10900 FailedTemplateCandidates, D.getIdentifierLoc(),
10901 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10902 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10903 PDiag(diag::note_explicit_instantiation_candidate));
10904
10905 if (Result == TemplateMatches.end())
10906 return true;
10907
10908 // Ignore access control bits, we don't need them for redeclaration checking.
10909 Specialization = cast<FunctionDecl>(*Result);
10910 }
10911
10912 // C++11 [except.spec]p4
10913 // In an explicit instantiation an exception-specification may be specified,
10914 // but is not required.
10915 // If an exception-specification is specified in an explicit instantiation
10916 // directive, it shall be compatible with the exception-specifications of
10917 // other declarations of that function.
10918 if (auto *FPT = R->getAs<FunctionProtoType>())
10919 if (FPT->hasExceptionSpec()) {
10920 unsigned DiagID =
10921 diag::err_mismatched_exception_spec_explicit_instantiation;
10922 if (getLangOpts().MicrosoftExt)
10923 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10925 PDiag(DiagID) << Specialization->getType(),
10926 PDiag(diag::note_explicit_instantiation_here),
10927 Specialization->getType()->getAs<FunctionProtoType>(),
10928 Specialization->getLocation(), FPT, D.getBeginLoc());
10929 // In Microsoft mode, mismatching exception specifications just cause a
10930 // warning.
10931 if (!getLangOpts().MicrosoftExt && Result)
10932 return true;
10933 }
10934
10935 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10936 Diag(D.getIdentifierLoc(),
10937 diag::err_explicit_instantiation_member_function_not_instantiated)
10939 << (Specialization->getTemplateSpecializationKind() ==
10941 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10942 return true;
10943 }
10944
10945 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10946 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10947 PrevDecl = Specialization;
10948
10949 if (PrevDecl) {
10950 bool HasNoEffect = false;
10951 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10952 PrevDecl,
10954 PrevDecl->getPointOfInstantiation(),
10955 HasNoEffect))
10956 return true;
10957
10958 // FIXME: We may still want to build some representation of this
10959 // explicit specialization.
10960 if (HasNoEffect)
10961 return (Decl*) nullptr;
10962 }
10963
10964 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10965 // functions
10966 // valarray<size_t>::valarray(size_t) and
10967 // valarray<size_t>::~valarray()
10968 // that it declared to have internal linkage with the internal_linkage
10969 // attribute. Ignore the explicit instantiation declaration in this case.
10970 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10972 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10973 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10974 RD->isInStdNamespace())
10975 return (Decl*) nullptr;
10976 }
10977
10978 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10980
10981 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10982 // instantiation declarations.
10984 Specialization->hasAttr<DLLImportAttr>() &&
10987
10988 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10989
10990 if (Specialization->isDefined()) {
10991 // Let the ASTConsumer know that this function has been explicitly
10992 // instantiated now, and its linkage might have changed.
10994 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10995 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10996
10997 // C++0x [temp.explicit]p2:
10998 // If the explicit instantiation is for a member function, a member class
10999 // or a static data member of a class template specialization, the name of
11000 // the class template specialization in the qualified-id for the member
11001 // name shall be a simple-template-id.
11002 //
11003 // C++98 has the same restriction, just worded differently.
11004 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11005 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11006 D.getCXXScopeSpec().isSet() &&
11007 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
11008 Diag(D.getIdentifierLoc(),
11009 diag::ext_explicit_instantiation_without_qualified_id)
11010 << Specialization << D.getCXXScopeSpec().getRange();
11011
11013 *this,
11014 FunTmpl ? (NamedDecl *)FunTmpl
11015 : Specialization->getInstantiatedFromMemberFunction(),
11016 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11017
11018 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11019 return (Decl*) nullptr;
11020}
11021
11023 const CXXScopeSpec &SS,
11024 const IdentifierInfo *Name,
11025 SourceLocation TagLoc,
11026 SourceLocation NameLoc) {
11027 // This has to hold, because SS is expected to be defined.
11028 assert(Name && "Expected a name in a dependent tag");
11029
11031 if (!NNS)
11032 return true;
11033
11035
11036 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11037 Diag(NameLoc, diag::err_dependent_tag_decl)
11038 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11039 return true;
11040 }
11041
11042 // Create the resulting type.
11044 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11045
11046 // Create type-source location information for this type.
11047 TypeLocBuilder TLB;
11049 TL.setElaboratedKeywordLoc(TagLoc);
11051 TL.setNameLoc(NameLoc);
11053}
11054
11056 const CXXScopeSpec &SS,
11057 const IdentifierInfo &II,
11058 SourceLocation IdLoc,
11059 ImplicitTypenameContext IsImplicitTypename) {
11060 if (SS.isInvalid())
11061 return true;
11062
11063 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11064 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)
11065 << FixItHint::CreateRemoval(TypenameLoc);
11066
11068 TypeSourceInfo *TSI = nullptr;
11069 QualType T =
11072 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11073 /*DeducedTSTContext=*/true);
11074 if (T.isNull())
11075 return true;
11076 return CreateParsedType(T, TSI);
11077}
11078
11081 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11082 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11083 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11084 ASTTemplateArgsPtr TemplateArgsIn,
11085 SourceLocation RAngleLoc) {
11086 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11087 Diag(TypenameLoc, getLangOpts().CPlusPlus11
11088 ? diag::compat_cxx11_typename_outside_of_template
11089 : diag::compat_pre_cxx11_typename_outside_of_template)
11090 << FixItHint::CreateRemoval(TypenameLoc);
11091
11092 // Strangely, non-type results are not ignored by this lookup, so the
11093 // program is ill-formed if it finds an injected-class-name.
11094 if (TypenameLoc.isValid()) {
11095 auto *LookupRD =
11096 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11097 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11098 Diag(TemplateIILoc,
11099 diag::ext_out_of_line_qualified_id_type_names_constructor)
11100 << TemplateII << 0 /*injected-class-name used as template name*/
11101 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11102 }
11103 }
11104
11105 // Translate the parser's template argument list in our AST format.
11106 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11107 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11108
11109 auto Keyword = TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11111
11112 TemplateName Template = TemplateIn.get();
11113 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11114 // Construct a dependent template specialization type.
11115 assert(DTN && "dependent template has non-dependent name?");
11116 assert(DTN->getQualifier() == SS.getScopeRep());
11117
11118 if (!DTN->getName().getIdentifier()) {
11119 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
11121 return true;
11122 }
11123
11125 Keyword, *DTN, TemplateArgs.arguments());
11126
11127 // Create source-location information for this type.
11128 TypeLocBuilder Builder;
11131 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11133 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11134 SpecTL.setTemplateNameLoc(TemplateIILoc);
11135 SpecTL.setLAngleLoc(LAngleLoc);
11136 SpecTL.setRAngleLoc(RAngleLoc);
11137 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11138 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11139 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11140 }
11141
11142 QualType T = CheckTemplateIdType(TypenameLoc.isValid()
11145 Template, TemplateIILoc, TemplateArgs);
11146 if (T.isNull())
11147 return true;
11148
11149 // Provide source-location information for the template specialization type.
11150 TypeLocBuilder Builder;
11152 = Builder.push<TemplateSpecializationTypeLoc>(T);
11153 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,
11154 TemplateIILoc, TemplateArgs);
11155 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11156 return CreateParsedType(T, TSI);
11157}
11158
11159/// Determine whether this failed name lookup should be treated as being
11160/// disabled by a usage of std::enable_if.
11162 SourceRange &CondRange, Expr *&Cond) {
11163 // We must be looking for a ::type...
11164 if (!II.isStr("type"))
11165 return false;
11166
11167 // ... within an explicitly-written template specialization...
11169 return false;
11170
11171 // FIXME: Look through sugar.
11172 auto EnableIfTSTLoc =
11174 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11175 return false;
11176 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11177
11178 // ... which names a complete class template declaration...
11179 const TemplateDecl *EnableIfDecl =
11180 EnableIfTST->getTemplateName().getAsTemplateDecl();
11181 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11182 return false;
11183
11184 // ... called "enable_if".
11185 const IdentifierInfo *EnableIfII =
11186 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11187 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11188 return false;
11189
11190 // Assume the first template argument is the condition.
11191 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11192
11193 // Dig out the condition.
11194 Cond = nullptr;
11195 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11197 return true;
11198
11199 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11200
11201 // Ignore Boolean literals; they add no value.
11202 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11203 Cond = nullptr;
11204
11205 return true;
11206}
11207
11210 SourceLocation KeywordLoc,
11211 NestedNameSpecifierLoc QualifierLoc,
11212 const IdentifierInfo &II,
11213 SourceLocation IILoc,
11214 TypeSourceInfo **TSI,
11215 bool DeducedTSTContext) {
11216 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11217 DeducedTSTContext);
11218 if (T.isNull())
11219 return QualType();
11220
11221 TypeLocBuilder TLB;
11222 if (isa<DependentNameType>(T)) {
11223 auto TL = TLB.push<DependentNameTypeLoc>(T);
11224 TL.setElaboratedKeywordLoc(KeywordLoc);
11225 TL.setQualifierLoc(QualifierLoc);
11226 TL.setNameLoc(IILoc);
11227 } else if (isa<DeducedTemplateSpecializationType>(T)) {
11229 TL.setElaboratedKeywordLoc(KeywordLoc);
11230 TL.setQualifierLoc(QualifierLoc);
11231 TL.setNameLoc(IILoc);
11232 } else if (isa<TemplateTypeParmType>(T)) {
11233 // FIXME: There might be a 'typename' keyword here, but we just drop it
11234 // as it can't be represented.
11235 assert(!QualifierLoc);
11236 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11237 } else if (isa<TagType>(T)) {
11238 auto TL = TLB.push<TagTypeLoc>(T);
11239 TL.setElaboratedKeywordLoc(KeywordLoc);
11240 TL.setQualifierLoc(QualifierLoc);
11241 TL.setNameLoc(IILoc);
11242 } else if (isa<TypedefType>(T)) {
11243 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11244 } else {
11245 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);
11246 }
11247 *TSI = TLB.getTypeSourceInfo(Context, T);
11248 return T;
11249}
11250
11251/// Build the type that describes a C++ typename specifier,
11252/// e.g., "typename T::type".
11255 SourceLocation KeywordLoc,
11256 NestedNameSpecifierLoc QualifierLoc,
11257 const IdentifierInfo &II,
11258 SourceLocation IILoc, bool DeducedTSTContext) {
11259 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11260
11261 CXXScopeSpec SS;
11262 SS.Adopt(QualifierLoc);
11263
11264 DeclContext *Ctx = nullptr;
11265 if (QualifierLoc) {
11266 Ctx = computeDeclContext(SS);
11267 if (!Ctx) {
11268 // If the nested-name-specifier is dependent and couldn't be
11269 // resolved to a type, build a typename type.
11270 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11272 QualifierLoc.getNestedNameSpecifier(),
11273 &II);
11274 }
11275
11276 // If the nested-name-specifier refers to the current instantiation,
11277 // the "typename" keyword itself is superfluous. In C++03, the
11278 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11279 // allows such extraneous "typename" keywords, and we retroactively
11280 // apply this DR to C++03 code with only a warning. In any case we continue.
11281
11282 if (RequireCompleteDeclContext(SS, Ctx))
11283 return QualType();
11284 }
11285
11286 DeclarationName Name(&II);
11287 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11288 if (Ctx)
11289 LookupQualifiedName(Result, Ctx, SS);
11290 else
11291 LookupName(Result, CurScope);
11292 unsigned DiagID = 0;
11293 Decl *Referenced = nullptr;
11294 switch (Result.getResultKind()) {
11296 // If we're looking up 'type' within a template named 'enable_if', produce
11297 // a more specific diagnostic.
11298 SourceRange CondRange;
11299 Expr *Cond = nullptr;
11300 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11301 // If we have a condition, narrow it down to the specific failed
11302 // condition.
11303 if (Cond) {
11304 Expr *FailedCond;
11305 std::string FailedDescription;
11306 std::tie(FailedCond, FailedDescription) =
11308
11309 Diag(FailedCond->getExprLoc(),
11310 diag::err_typename_nested_not_found_requirement)
11311 << FailedDescription
11312 << FailedCond->getSourceRange();
11313 return QualType();
11314 }
11315
11316 Diag(CondRange.getBegin(),
11317 diag::err_typename_nested_not_found_enable_if)
11318 << Ctx << CondRange;
11319 return QualType();
11320 }
11321
11322 DiagID = Ctx ? diag::err_typename_nested_not_found
11323 : diag::err_unknown_typename;
11324 break;
11325 }
11326
11328 // We found a using declaration that is a value. Most likely, the using
11329 // declaration itself is meant to have the 'typename' keyword.
11330 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11331 IILoc);
11332 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11333 << Name << Ctx << FullRange;
11334 if (UnresolvedUsingValueDecl *Using
11335 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11336 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11337 Diag(Loc, diag::note_using_value_decl_missing_typename)
11338 << FixItHint::CreateInsertion(Loc, "typename ");
11339 }
11340 }
11341 // Fall through to create a dependent typename type, from which we can
11342 // recover better.
11343 [[fallthrough]];
11344
11346 // Okay, it's a member of an unknown instantiation.
11348 QualifierLoc.getNestedNameSpecifier(),
11349 &II);
11350
11352 // FXIME: Missing support for UsingShadowDecl on this path?
11353 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11354 // C++ [class.qual]p2:
11355 // In a lookup in which function names are not ignored and the
11356 // nested-name-specifier nominates a class C, if the name specified
11357 // after the nested-name-specifier, when looked up in C, is the
11358 // injected-class-name of C [...] then the name is instead considered
11359 // to name the constructor of class C.
11360 //
11361 // Unlike in an elaborated-type-specifier, function names are not ignored
11362 // in typename-specifier lookup. However, they are ignored in all the
11363 // contexts where we form a typename type with no keyword (that is, in
11364 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11365 //
11366 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11367 // ignore functions, but that appears to be an oversight.
11372 Type, IILoc);
11373 // FIXME: This appears to be the only case where a template type parameter
11374 // can have an elaborated keyword. We should preserve it somehow.
11375 if (isa<TemplateTypeParmDecl>(Type)) {
11377 assert(!QualifierLoc);
11379 }
11380 return Context.getTypeDeclType(
11381 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);
11382 }
11383
11384 // C++ [dcl.type.simple]p2:
11385 // A type-specifier of the form
11386 // typename[opt] nested-name-specifier[opt] template-name
11387 // is a placeholder for a deduced class type [...].
11388 if (getLangOpts().CPlusPlus17) {
11389 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11390 if (!DeducedTSTContext) {
11391 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11392 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11393 Diag(IILoc, diag::err_dependent_deduced_tst)
11395 << QualType(Qualifier.getAsType(), 0);
11396 else
11397 Diag(IILoc, diag::err_deduced_tst)
11400 return QualType();
11401 }
11403 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11404 TemplateName(TD));
11406 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11407 }
11408 }
11409
11410 DiagID = Ctx ? diag::err_typename_nested_not_type
11411 : diag::err_typename_not_type;
11412 Referenced = Result.getFoundDecl();
11413 break;
11414
11416 DiagID = Ctx ? diag::err_typename_nested_not_type
11417 : diag::err_typename_not_type;
11418 Referenced = *Result.begin();
11419 break;
11420
11422 return QualType();
11423 }
11424
11425 // If we get here, it's because name lookup did not find a
11426 // type. Emit an appropriate diagnostic and return an error.
11427 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11428 IILoc);
11429 if (Ctx)
11430 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11431 else
11432 Diag(IILoc, DiagID) << FullRange << Name;
11433 if (Referenced)
11434 Diag(Referenced->getLocation(),
11435 Ctx ? diag::note_typename_member_refers_here
11436 : diag::note_typename_refers_here)
11437 << Name;
11438 return QualType();
11439}
11440
11441namespace {
11442 // See Sema::RebuildTypeInCurrentInstantiation
11443 class CurrentInstantiationRebuilder
11444 : public TreeTransform<CurrentInstantiationRebuilder> {
11446 DeclarationName Entity;
11447
11448 public:
11450
11451 CurrentInstantiationRebuilder(Sema &SemaRef,
11453 DeclarationName Entity)
11454 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11455 Loc(Loc), Entity(Entity) { }
11456
11457 /// Determine whether the given type \p T has already been
11458 /// transformed.
11459 ///
11460 /// For the purposes of type reconstruction, a type has already been
11461 /// transformed if it is NULL or if it is not dependent.
11462 bool AlreadyTransformed(QualType T) {
11463 return T.isNull() || !T->isInstantiationDependentType();
11464 }
11465
11466 /// Returns the location of the entity whose type is being
11467 /// rebuilt.
11468 SourceLocation getBaseLocation() { return Loc; }
11469
11470 /// Returns the name of the entity whose type is being rebuilt.
11471 DeclarationName getBaseEntity() { return Entity; }
11472
11473 /// Sets the "base" location and entity when that
11474 /// information is known based on another transformation.
11475 void setBase(SourceLocation Loc, DeclarationName Entity) {
11476 this->Loc = Loc;
11477 this->Entity = Entity;
11478 }
11479
11480 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11481 // Lambdas never need to be transformed.
11482 return E;
11483 }
11484 };
11485} // end anonymous namespace
11486
11489 DeclarationName Name) {
11490 if (!T || !T->getType()->isInstantiationDependentType())
11491 return T;
11492
11493 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11494 return Rebuilder.TransformType(T);
11495}
11496
11498 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11499 DeclarationName());
11500 return Rebuilder.TransformExpr(E);
11501}
11502
11504 if (SS.isInvalid())
11505 return true;
11506
11508 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11509 DeclarationName());
11511 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11512 if (!Rebuilt)
11513 return true;
11514
11515 SS.Adopt(Rebuilt);
11516 return false;
11517}
11518
11520 TemplateParameterList *Params) {
11521 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11522 Decl *Param = Params->getParam(I);
11523
11524 // There is nothing to rebuild in a type parameter.
11525 if (isa<TemplateTypeParmDecl>(Param))
11526 continue;
11527
11528 // Rebuild the template parameter list of a template template parameter.
11530 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11532 TTP->getTemplateParameters()))
11533 return true;
11534
11535 continue;
11536 }
11537
11538 // Rebuild the type of a non-type template parameter.
11539 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11540 TypeSourceInfo *NewTSI
11542 NTTP->getLocation(),
11543 NTTP->getDeclName());
11544 if (!NewTSI)
11545 return true;
11546
11547 if (NewTSI->getType()->isUndeducedType()) {
11548 // C++17 [temp.dep.expr]p3:
11549 // An id-expression is type-dependent if it contains
11550 // - an identifier associated by name lookup with a non-type
11551 // template-parameter declared with a type that contains a
11552 // placeholder type (7.1.7.4),
11553 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11554 }
11555
11556 if (NewTSI != NTTP->getTypeSourceInfo()) {
11557 NTTP->setTypeSourceInfo(NewTSI);
11558 NTTP->setType(NewTSI->getType());
11559 }
11560 }
11561
11562 return false;
11563}
11564
11565std::string
11567 const TemplateArgumentList &Args) {
11568 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11569}
11570
11571std::string
11573 const TemplateArgument *Args,
11574 unsigned NumArgs) {
11575 SmallString<128> Str;
11576 llvm::raw_svector_ostream Out(Str);
11577
11578 if (!Params || Params->size() == 0 || NumArgs == 0)
11579 return std::string();
11580
11581 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11582 if (I >= NumArgs)
11583 break;
11584
11585 if (I == 0)
11586 Out << "[with ";
11587 else
11588 Out << ", ";
11589
11590 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11591 Out << Id->getName();
11592 } else {
11593 Out << '$' << I;
11594 }
11595
11596 Out << " = ";
11597 Args[I].print(getPrintingPolicy(), Out,
11599 getPrintingPolicy(), Params, I));
11600 }
11601
11602 Out << ']';
11603 return std::string(Out.str());
11604}
11605
11607 CachedTokens &Toks) {
11608 if (!FD)
11609 return;
11610
11611 auto LPT = std::make_unique<LateParsedTemplate>();
11612
11613 // Take tokens to avoid allocations
11614 LPT->Toks.swap(Toks);
11615 LPT->D = FnD;
11616 LPT->FPO = getCurFPFeatures();
11617 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11618
11619 FD->setLateTemplateParsed(true);
11620}
11621
11623 if (!FD)
11624 return;
11625 FD->setLateTemplateParsed(false);
11626}
11627
11629 DeclContext *DC = CurContext;
11630
11631 while (DC) {
11632 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11633 const FunctionDecl *FD = RD->isLocalClass();
11634 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11635 } else if (DC->isTranslationUnit() || DC->isNamespace())
11636 return false;
11637
11638 DC = DC->getParent();
11639 }
11640 return false;
11641}
11642
11643namespace {
11644/// Walk the path from which a declaration was instantiated, and check
11645/// that every explicit specialization along that path is visible. This enforces
11646/// C++ [temp.expl.spec]/6:
11647///
11648/// If a template, a member template or a member of a class template is
11649/// explicitly specialized then that specialization shall be declared before
11650/// the first use of that specialization that would cause an implicit
11651/// instantiation to take place, in every translation unit in which such a
11652/// use occurs; no diagnostic is required.
11653///
11654/// and also C++ [temp.class.spec]/1:
11655///
11656/// A partial specialization shall be declared before the first use of a
11657/// class template specialization that would make use of the partial
11658/// specialization as the result of an implicit or explicit instantiation
11659/// in every translation unit in which such a use occurs; no diagnostic is
11660/// required.
11661class ExplicitSpecializationVisibilityChecker {
11662 Sema &S;
11666
11667public:
11668 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11670 : S(S), Loc(Loc), Kind(Kind) {}
11671
11672 void check(NamedDecl *ND) {
11673 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11674 return checkImpl(FD);
11675 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11676 return checkImpl(RD);
11677 if (auto *VD = dyn_cast<VarDecl>(ND))
11678 return checkImpl(VD);
11679 if (auto *ED = dyn_cast<EnumDecl>(ND))
11680 return checkImpl(ED);
11681 }
11682
11683private:
11684 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11685 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11686 : Sema::MissingImportKind::ExplicitSpecialization;
11687 const bool Recover = true;
11688
11689 // If we got a custom set of modules (because only a subset of the
11690 // declarations are interesting), use them, otherwise let
11691 // diagnoseMissingImport intelligently pick some.
11692 if (Modules.empty())
11693 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11694 else
11695 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11696 }
11697
11698 bool CheckMemberSpecialization(const NamedDecl *D) {
11699 return Kind == Sema::AcceptableKind::Visible
11702 }
11703
11704 bool CheckExplicitSpecialization(const NamedDecl *D) {
11705 return Kind == Sema::AcceptableKind::Visible
11708 }
11709
11710 bool CheckDeclaration(const NamedDecl *D) {
11711 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11713 }
11714
11715 // Check a specific declaration. There are three problematic cases:
11716 //
11717 // 1) The declaration is an explicit specialization of a template
11718 // specialization.
11719 // 2) The declaration is an explicit specialization of a member of an
11720 // templated class.
11721 // 3) The declaration is an instantiation of a template, and that template
11722 // is an explicit specialization of a member of a templated class.
11723 //
11724 // We don't need to go any deeper than that, as the instantiation of the
11725 // surrounding class / etc is not triggered by whatever triggered this
11726 // instantiation, and thus should be checked elsewhere.
11727 template<typename SpecDecl>
11728 void checkImpl(SpecDecl *Spec) {
11729 bool IsHiddenExplicitSpecialization = false;
11730 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11731 // Some invalid friend declarations are written as specializations but are
11732 // instantiated implicitly.
11733 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11734 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11735 if (SpecKind == TSK_ExplicitSpecialization) {
11736 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11737 ? !CheckMemberSpecialization(Spec)
11738 : !CheckExplicitSpecialization(Spec);
11739 } else {
11740 checkInstantiated(Spec);
11741 }
11742
11743 if (IsHiddenExplicitSpecialization)
11744 diagnose(Spec->getMostRecentDecl(), false);
11745 }
11746
11747 void checkInstantiated(FunctionDecl *FD) {
11748 if (auto *TD = FD->getPrimaryTemplate())
11749 checkTemplate(TD);
11750 }
11751
11752 void checkInstantiated(CXXRecordDecl *RD) {
11753 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11754 if (!SD)
11755 return;
11756
11757 auto From = SD->getSpecializedTemplateOrPartial();
11758 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11759 checkTemplate(TD);
11760 else if (auto *TD =
11761 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11762 if (!CheckDeclaration(TD))
11763 diagnose(TD, true);
11764 checkTemplate(TD);
11765 }
11766 }
11767
11768 void checkInstantiated(VarDecl *RD) {
11769 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11770 if (!SD)
11771 return;
11772
11773 auto From = SD->getSpecializedTemplateOrPartial();
11774 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11775 checkTemplate(TD);
11776 else if (auto *TD =
11777 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11778 if (!CheckDeclaration(TD))
11779 diagnose(TD, true);
11780 checkTemplate(TD);
11781 }
11782 }
11783
11784 void checkInstantiated(EnumDecl *FD) {}
11785
11786 template<typename TemplDecl>
11787 void checkTemplate(TemplDecl *TD) {
11788 if (TD->isMemberSpecialization()) {
11789 if (!CheckMemberSpecialization(TD))
11790 diagnose(TD->getMostRecentDecl(), false);
11791 }
11792 }
11793};
11794} // end anonymous namespace
11795
11797 if (!getLangOpts().Modules)
11798 return;
11799
11800 ExplicitSpecializationVisibilityChecker(*this, Loc,
11802 .check(Spec);
11803}
11804
11806 NamedDecl *Spec) {
11807 if (!getLangOpts().CPlusPlusModules)
11808 return checkSpecializationVisibility(Loc, Spec);
11809
11810 ExplicitSpecializationVisibilityChecker(*this, Loc,
11812 .check(Spec);
11813}
11814
11817 return N->getLocation();
11818 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11820 return FD->getLocation();
11823 return N->getLocation();
11824 }
11825 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11826 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11827 continue;
11828 return CSC.PointOfInstantiation;
11829 }
11830 return N->getLocation();
11831}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1840::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
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.
MatchFinder::MatchResult MatchResult
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1179
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:7002
SourceRange Range
Definition: SemaObjC.cpp:753
SourceLocation Loc
Definition: SemaObjC.cpp:754
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
static Expr * BuildExpressionFromNonTypeTemplateArgumentValue(Sema &S, QualType T, const APValue &Val, SourceLocation Loc)
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, const IdentifierInfo *Name)
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, unsigned HereDiagID, unsigned ExternalDiagID)
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
static Expr * BuildExpressionFromIntegralTemplateArgumentValue(Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, TemplateParameterList *SpecParams, ArrayRef< TemplateArgument > Args)
static bool SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
static void StripImplicitInstantiation(NamedDecl *D, bool MinGW)
Strips various properties off an implicit instantiation that has just been explicitly specialized.
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool isInVkNamespace(const RecordType *RT)
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef, QualType OperandArg, SourceLocation Loc)
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is the address of an object or function according to C++ [...
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
static bool CheckTemplateArgumentPointerToMember(Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp....
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, const NamedDecl *OldInstFrom, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
Defines the clang::SourceLocation class and associated facilities.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
StateNode * Previous
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:983
APSInt & getInt()
Definition: APValue.h:489
APSInt & getComplexIntImag()
Definition: APValue.h:527
ValueKind getKind() const
Definition: APValue.h:461
APFixedPoint & getFixedPoint()
Definition: APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1066
APValue & getVectorElt(unsigned I)
Definition: APValue.h:563
unsigned getVectorLength() const
Definition: APValue.h:571
bool isLValue() const
Definition: APValue.h:472
bool isMemberPointer() const
Definition: APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:956
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isNullPointer() const
Definition: APValue.cpp:1019
APSInt & getComplexIntReal()
Definition: APValue.h:519
APFloat & getComplexFloatImag()
Definition: APValue.h:543
APFloat & getComplexFloatReal()
Definition: APValue.h:535
APFloat & getFloat()
Definition: APValue.h:503
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1201
unsigned getIntWidth(QualType T) const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:744
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, const DependentTemplateStorage &Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType getSubstBuiltinTemplatePack(const TemplateArgument &ArgPack)
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
TemplateName getDependentTemplateName(const DependentTemplateStorage &Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template operat...
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1249
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier NNS, const IdentifierInfo *Name) const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1223
TypeSourceInfo * getTemplateSpecializationTypeInfo(ElaboratedTypeKeyword Keyword, SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Canon=QualType()) const
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1250
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const
Determine whether the two declarations refer to the same entity.
QualType getHLSLInlineSpirvType(uint32_t Opcode, uint32_t Size, uint32_t Alignment, ArrayRef< SpirvOperand > Operands)
CanQualType IntTy
Definition: ASTContext.h:1231
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
CanQualType OverloadTy
Definition: ASTContext.h:1250
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
QualType getTypeDeclType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypeDecl *Decl) const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2625
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
QualType getTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName T, ArrayRef< TemplateArgument > SpecifiedArgs, ArrayRef< TemplateArgument > CanonicalArgs, QualType Underlying=QualType()) const
TemplateName getQualifiedTemplateName(NestedNameSpecifier Qualifier, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1750
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:859
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
QualType getDeducedTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1161
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
bool isUnset() const
Definition: Ownership.h:168
PtrTy get() const
Definition: Ownership.h:171
bool isInvalid() const
Definition: Ownership.h:167
bool isUsable() const
Definition: Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: TypeBase.h:3908
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition: Attr.h:44
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2373
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2391
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2441
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2434
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2409
TemplateDecl * getNamedConcept() const
Definition: TypeLoc.h:2415
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2421
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
bool isDecltypeAuto() const
Definition: TypeBase.h:7203
A fixed int type of a specified bitwidth.
Definition: TypeBase.h:8195
Pointer to a block type.
Definition: TypeBase.h:3558
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
BuiltinTemplateKind getBuiltinTemplateKind() const
This class is used for builtin types like 'int'.
Definition: TypeBase.h:3182
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:2099
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:735
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3864
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1550
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:768
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition: DeclCXX.cpp:132
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:539
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:2020
base_class_range bases()
Definition: DeclCXX.h:608
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2050
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2046
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:2027
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2061
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:530
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:180
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:206
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:185
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:97
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:183
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:178
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:103
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1069
static CanQual< Type > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:84
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a class template node.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, CanQualType CanonInjectedTST, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, bool StrictPackMatch, ClassTemplateSpecializationDecl *PrevDecl)
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition: TypeBase.h:3293
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
Represents the canonical version of C arrays with a specified constant size.
Definition: TypeBase.h:3776
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:346
Represents a concrete matrix type with constant number of rows and columns.
Definition: TypeBase.h:4389
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2238
bool isFileContext() const
Definition: DeclBase.h:2180
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2077
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1392
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1358
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...
Definition: DeclBase.cpp:2059
bool isNamespace() const
Definition: DeclBase.h:2198
bool isTranslationUnit() const
Definition: DeclBase.h:2185
bool isRecord() const
Definition: DeclBase.h:2189
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2022
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1793
bool isStdNamespace() const
Definition: DeclBase.cpp:1342
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2040
bool isFunctionOrMethod() const
Definition: DeclBase.h:2161
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1309
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
Definition: DeclBase.cpp:1428
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1373
ValueDecl * getDecl()
Definition: Expr.h:1340
Captures information about "declaration specifiers".
Definition: DeclSpec.h:217
bool isVirtualSpecified() const
Definition: DeclSpec.h:618
bool isNoreturnSpecified() const
Definition: DeclSpec.h:631
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:480
SCS getStorageClassSpec() const
Definition: DeclSpec.h:471
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:632
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:624
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:472
bool isInlineSpecified() const
Definition: DeclSpec.h:607
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:481
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:619
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:806
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:610
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:621
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:807
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1061
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1226
T * getAttr() const
Definition: DeclBase.h:573
void addAttr(Attr *A)
Definition: DeclBase.cpp:1022
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:156
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1217
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:286
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:842
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:298
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:251
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:812
void dropAttrs()
Definition: DeclBase.cpp:1015
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1063
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1180
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2793
bool isInvalidDecl() const
Definition: DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:502
SourceLocation getLocation() const
Definition: DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:234
DeclContext * getDeclContext()
Definition: DeclBase.h:448
AccessSpecifier getAccess() const
Definition: DeclBase.h:507
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:431
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:918
bool hasAttr() const
Definition: DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:364
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
Kind getKind() const
Definition: DeclBase.h:442
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:427
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:813
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:808
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1874
Represents the type decltype(expr) (C++11).
Definition: TypeBase.h:6270
Represents a C++17 deduced template specialization type.
Definition: TypeBase.h:7228
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: TypeBase.h:7146
bool isDeduced() const
Definition: TypeBase.h:7168
Represents an extended address space qualifier where the input address space value is dependent.
Definition: TypeBase.h:4077
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2581
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2561
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2570
Represents a qualified type name for which the type name is dependent.
Definition: TypeBase.h:7414
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3504
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:544
Represents an array type in C++ whose size is a value-dependent expression.
Definition: TypeBase.h:4027
Represents an extended vector type where either the type or size is dependent.
Definition: TypeBase.h:4117
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: TypeBase.h:4448
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2631
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2651
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2618
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2675
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2667
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2683
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2659
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: TypeBase.h:7465
Represents a vector type where either the type or size is dependent.
Definition: TypeBase.h:4243
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
Recursively visit a template argument location and dispatch to the appropriate method for the argumen...
virtual bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier=true)
Recursively visit a type with location, by dispatching to Traverse*TypeLoc() based on the argument ty...
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:4004
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4267
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:5033
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: TypeBase.h:6522
This represents one expression.
Definition: Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3078
void setType(QualType t)
Definition: Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3073
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:829
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3053
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:4001
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
QualType getType() const
Definition: Expr.h:144
ExtVectorType - Extended vector type.
Definition: TypeBase.h:4283
Represents a member of a struct/union/class.
Definition: Decl.h:3157
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:102
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1072
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1999
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2475
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4146
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4455
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4254
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4113
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3688
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2539
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4085
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition: Decl.cpp:4319
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2361
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4358
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3161
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4106
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: TypeBase.h:4860
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
ArrayRef< QualType > param_types() const
Definition: TypeBase.h:5722
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:470
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:543
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:554
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:526
QualType getReturnType() const
Definition: TypeBase.h:4818
Represents an arbitrary, user-specified SPIR-V type instruction.
Definition: TypeBase.h:6860
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.
void AddDecl(NamedDecl *D)
AddDecl - Link the decl to its shadowed decl chain.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3789
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: TypeBase.h:3925
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:531
Describes an C or C++ initializer list.
Definition: Expr.h:5235
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7739
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
The injected class name of a C++ class template or class template partial specialization.
Definition: TypeBase.h:6553
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:971
An lvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3633
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
Represents a linkage specification.
Definition: DeclCXX.h:3009
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
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
bool hasNext() const
Definition: Lookup.h:708
NamedDecl * next()
Definition: Lookup.h:712
Represents the results of name lookup.
Definition: Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:607
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:318
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:666
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:751
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:569
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4392
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
QualType getPointeeType() const
Definition: TypeBase.h:3687
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:614
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:636
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:654
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:239
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:486
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1680
NamedDecl * getMostRecentDecl()
Definition: Decl.h:500
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1206
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:706
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1930
Represent a C++ namespace.
Definition: Decl.h:591
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
TypeLoc castAsTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Type
A type, stored as a Type*.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Interfaces are the core concept in Objective-C for object oriented design.
Definition: TypeBase.h:7905
Represents a pointer to an Objective C object.
Definition: TypeBase.h:7961
Represents a class type in Objective C.
Definition: TypeBase.h:7707
PtrTy get() const
Definition: Ownership.h:81
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1369
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1416
bool isVarDeclReference() const
Definition: ExprCXX.h:3296
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition: ExprCXX.h:3312
bool isConceptReference() const
Definition: ExprCXX.h:3285
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition: ExprCXX.h:3331
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:118
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4357
Represents a pack expansion of types.
Definition: TypeBase.h:7524
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:256
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2184
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:119
Represents the parsed form of a C++ template argument.
KindType getKind() const
Determine what kind of template argument we have.
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
ParsedType getAsType() const
Retrieve the template type argument's type.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion.
SourceLocation getTemplateKwLoc() const
Retrieve the location of the template argument.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
SourceLocation getNameLoc() const
Retrieve the location of the template argument.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition: TypeBase.h:8161
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
bool NeedsStdLibCxxWorkaroundBefore(std::uint64_t FixedVersion)
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: TypeBase.h:8432
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3591
void addConst()
Add the const type qualifier to this QualType.
Definition: TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: TypeBase.h:1438
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: TypeBase.h:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
void * getAsOpaquePtr() const
Definition: TypeBase.h:984
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition: Type.cpp:3584
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: TypeBase.h:1332
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: TypeBase.h:361
void setObjCLifetime(ObjCLifetime type)
Definition: TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3651
Represents a struct/union/class.
Definition: Decl.h:4309
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4493
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: TypeBase.h:6502
RecordDecl * getOriginalDecl() const
Definition: TypeBase.h:6509
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:857
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:201
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:5292
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
QualType getPointeeType() const
Definition: TypeBase.h:3607
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:271
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:287
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId, bool DeferHint=false)
Emit a compatibility diagnostic.
Definition: SemaBase.cpp:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:33
Sema & SemaRef
Definition: SemaBase.h:40
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1078
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13496
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8393
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3468
Whether and why a template name is required in this lookup.
Definition: Sema.h:11339
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11347
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12359
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12392
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7668
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9378
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6383
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
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:13430
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12936
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2539
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1617
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15759
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:9277
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9281
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9289
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9284
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19987
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.
Definition: SemaAccess.cpp:35
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...
Definition: SemaDecl.cpp:17346
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.
Definition: SemaDecl.cpp:6251
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is visible.
Definition: Sema.h:9591
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6236
void NoteAllFoundTemplates(TemplateName Name)
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition: Sema.h:1438
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6393
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
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:2042
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11310
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11892
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11895
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11899
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition: Sema.h:1276
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5943
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isRedefinitionAllowedFor(NamedDecl *D, NamedDecl **Suggested, bool &Visible)
Determine if D has a definition which allows we redefine it in current TU.
Definition: SemaDecl.cpp:20860
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.
Definition: SemaDecl.cpp:1555
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
ASTContext & getASTContext() const
Definition: Sema.h:918
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1771
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:756
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9606
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:1184
bool CheckDeclCompatibleWithTemplateTemplate(TemplateDecl *Template, TemplateTemplateParmDecl *Param, const TemplateArgumentLoc &Arg)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:17371
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2298
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, UnsignedOrNone NumExpansions)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:11300
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:12065
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:12083
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:12073
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:12093
NamedDecl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed.
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
AssumedTemplateKind
Definition: Sema.h:11360
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
@ None
This is not assumed to be a template name.
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:11293
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:168
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool TypenameKeyword, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
FPOptions & getCurFPFeatures()
Definition: Sema.h:913
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition: Sema.h:14268
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:14256
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:14265
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:14259
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:14283
const LangOptions & getLangOpts() const
Definition: Sema.h:911
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14709
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1446
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:1275
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool hasVisibleMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is a member specialization declaration (as oppo...
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
const LangOptions & LangOpts
Definition: Sema.h:1274
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20409
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.
AcceptableKind
Definition: Sema.h:9269
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)
Definition: SemaType.cpp:8217
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1333
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9944
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:633
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3230
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool hasReachableDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a reachable default argument.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15277
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5948
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9928
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)
Definition: SemaDecl.cpp:1347
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4868
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool CheckTypeConstraint(TemplateIdAnnotation *TypeConstraint)
TemplateNameKind ActOnTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a template name from a name that is syntactically required to name a template,...
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
void AddMsStructLayoutForRecord(RecordDecl *RD)
AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
Definition: SemaAttr.cpp:90
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
SourceLocation getTopMostPointOfInstantiation(const NamedDecl *) const
Returns the top most location responsible for the definition of N.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:218
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc)
Invoked when parsing a template argument followed by an ellipsis, which creates a pack expansion.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II)
Try to resolve an undeclared template name as a type template.
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:15279
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool hasReachableMemberSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is a member specialization declaration (as op...
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1951
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 ...
Definition: SemaExpr.cpp:17422
ASTConsumer & Consumer
Definition: Sema.h:1277
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4622
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *StrictPackMatch)
Check a template argument against its corresponding template template parameter.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8547
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
Definition: SemaType.cpp:9813
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.
Definition: SemaType.cpp:5693
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 {'.
Definition: SemaDecl.cpp:17555
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9241
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3184
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)
@ TemplateNameIsRequired
Definition: Sema.h:11337
bool hasReachableExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a reachable declaration of D that is an explicit specialization declaration for...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, CXXScopeSpec &SS, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:509
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:15312
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:11524
@ TPC_TemplateTemplateParameterPack
Definition: Sema.h:11534
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11532
@ TPC_ClassTemplateMember
Definition: Sema.h:11530
@ TPC_FunctionTemplate
Definition: Sema.h:11529
@ TPC_FriendClassTemplate
Definition: Sema.h:11531
@ TPC_Other
Definition: Sema.h:11527
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11533
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1637
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose=true)
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1622
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:6238
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21528
ExprResult CheckVarOrConceptTemplateTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1761
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2773
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void NoteTemplateParameterLocation(const NamedDecl &Decl)
IdentifierResolver IdResolver
Definition: Sema.h:3461
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11302
void checkTypeDeclType(DeclContext *LookupCtx, DiagCtorKind DCK, TypeDecl *TD, SourceLocation NameLoc)
Returns the TypeDeclType for the given type declaration, as ASTContext::getTypeDeclType would,...
Definition: SemaDecl.cpp:143
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:9600
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12779
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6197
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:322
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8599
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Instances of this class represent operands to a SPIR-V type instruction.
Definition: TypeBase.h:6782
static SpirvOperand createConstant(QualType ResultType, llvm::APInt Val)
Definition: TypeBase.h:6837
static SpirvOperand createType(QualType T)
Definition: TypeBase.h:6845
static SpirvOperand createLiteral(llvm::APInt Val)
Definition: TypeBase.h:6841
Stmt - This represents one statement.
Definition: Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
Represents the result of substituting a builtin template as a pack.
Definition: TypeBase.h:7062
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4658
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:151
Represents the result of substituting a set of types for a template type parameter pack.
Definition: TypeBase.h:7091
Represents the result of substituting a type for a template type parameter.
Definition: TypeBase.h:6972
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3714
StringRef getKindName() const
Definition: Decl.h:3904
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4847
bool isEntityBeingDefined() const
Determines whether this entity is in the process of being defined.
Definition: Decl.h:3898
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4921
TagKind getTagKind() const
Definition: Decl.h:3908
TagDecl * getOriginalDecl() const
Definition: TypeBase.h:6441
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1288
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1360
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1326
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:650
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:652
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:653
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:669
ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:661
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:649
A template argument list.
Definition: DeclTemplate.h:250
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:289
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.
Definition: DeclTemplate.h:286
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
SourceLocation getLocation() const
Definition: TemplateBase.h:563
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:625
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:576
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:618
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:452
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:402
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:411
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.
Definition: TemplateBase.h:426
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.
Definition: TemplateBase.h:322
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:366
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.
Definition: TemplateBase.h:346
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.
Definition: TemplateBase.h:299
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:446
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.
Definition: TemplateBase.h:380
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:329
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
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,...
Definition: TemplateBase.h:353
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:399
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
bool hasAssociatedConstraints() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:146
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
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.
Definition: DeclTemplate.h:133
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:182
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
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
Definition: DeclTemplate.h:205
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKeywordLoc, SourceLocation NameLoc, SourceLocation LAngleLoc, SourceLocation RAngleLoc)
Definition: TypeLoc.cpp:707
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: TypeBase.h:7290
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: TypeBase.h:7355
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4601
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
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.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isParameterPack() const
Returns whether this is a parameter pack.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:890
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:892
unsigned getIndex() const
Definition: TypeBase.h:6932
unsigned getDepth() const
Definition: TypeBase.h:6931
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3685
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:223
Represents a declaration of a type.
Definition: Decl.h:3510
const Type * getTypeForDecl() const
Definition: Decl.h:3535
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3544
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:154
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition: TypeLoc.cpp:942
bool isNull() const
Definition: TypeLoc.h:121
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:193
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: TypeBase.h:6193
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: TypeBase.h:6243
A container of type source information.
Definition: TypeBase.h:8314
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition: TypeBase.h:8325
SourceLocation getNameLoc() const
Definition: TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:556
An operation on a type.
Definition: TypeVisitor.h:64
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: TypeBase.h:2503
bool isBooleanType() const
Definition: TypeBase.h:9066
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2229
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2277
bool isRValueReferenceType() const
Definition: TypeBase.h:8612
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.h:26
bool isVoidPointerType() const
Definition: Type.cpp:712
bool isArrayType() const
Definition: TypeBase.h:8679
bool isPointerType() const
Definition: TypeBase.h:8580
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
bool isEnumeralType() const
Definition: TypeBase.h:8711
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition: Type.cpp:1928
bool isScalarType() const
Definition: TypeBase.h:9038
bool isChar8Type() const
Definition: Type.cpp:2152
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2107
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition: Type.cpp:471
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: TypeBase.h:9054
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2172
bool isObjCObjectOrInterfaceType() const
Definition: TypeBase.h:8757
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: TypeBase.h:2917
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: TypeBase.h:2808
bool isLValueReferenceType() const
Definition: TypeBase.h:8608
bool isBitIntType() const
Definition: TypeBase.h:8845
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: TypeBase.h:8703
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:3063
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
bool isChar16Type() const
Definition: Type.cpp:2158
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2060
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: TypeBase.h:2423
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isChar32Type() const
Definition: Type.cpp:2164
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: TypeBase.h:2818
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5355
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition: Type.h:53
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4948
bool isPointerOrReferenceType() const
Definition: TypeBase.h:8584
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2440
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isVectorType() const
Definition: TypeBase.h:8719
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition: TypeBase.h:2939
bool isWideCharType() const
Definition: Type.cpp:2145
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isNullPtrType() const
Definition: TypeBase.h:8973
bool isRecordType() const
Definition: TypeBase.h:8707
QualType getUnderlyingType() const
Definition: Decl.h:3614
Wrapper for source info for typedefs.
Definition: TypeLoc.h:782
Simple class containing the result of Sema::CorrectTypo.
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
DeclClass * getCorrectionDeclAs() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2246
A unary type transform, which is a type constructed from another.
Definition: TypeBase.h:6375
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:998
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3384
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:432
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:787
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: TypeBase.h:5998
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3934
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3393
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3457
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
void setType(QualType newType)
Definition: Decl.h:723
QualType getType() const
Definition: Decl.h:722
Represents a variable declaration or definition.
Definition: Decl.h:925
TLSKind getTLSKind() const
Definition: Decl.cpp:2168
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1282
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2772
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2907
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2800
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2898
Declaration of a variable template.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: TypeBase.h:3982
Represents a GCC generic vector type.
Definition: TypeBase.h:4191
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
Definition: larchintrin.h:181
Definition: SPIR.cpp:35
Definition: SPIR.cpp:47
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
ImplicitTypenameContext
Definition: DeclSpec.h:1857
@ Match
This is not an overload because the signature exactly matches an existing declaration.
bool isa(CodeGen::Address addr)
Definition: Address.h:330
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
@ NotFound
No entity found met the criteria.
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
@ Found
Name lookup found a single declaration that met the criteria.
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:913
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:602
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Extern
Definition: Specifiers.h:251
@ TSCS_unspecified
Definition: Specifiers.h:236
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...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:51
@ Template
We are parsing a template declaration.
TagUseKind
Definition: Sema.h:448
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:249
TagTypeKind
The kind of a tag type.
Definition: TypeBase.h:5906
@ Enum
The "enum" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:263
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.
@ Concept
The name was classified as a concept name.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:66
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.
bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, const NamedDecl *Param, ArrayRef< TemplateArgument > Args, unsigned Depth)
Make a best-effort determination of whether the type T can be produced by substituting Args into the ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Non_template
The name does not refer to a template.
Definition: TemplateKinds.h:22
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:251
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:366
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:255
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
@ TemplateArg
Value of a non-type template parameter.
@ TempArgStrict
As above, but applies strict template checking rules.
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: TypeBase.h:5881
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ Parens
New-expression has a C++98 paren-delimited initializer.
CharacterLiteralKind
Definition: Expr.h:1605
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:678
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
Definition: TemplateName.h:189
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:647
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:633
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:612
Extra information about a function prototype.
Definition: TypeBase.h:5367
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3264
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:3281
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3246
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:926
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned TerseOutput
Provide a 'terse' output.
unsigned PrintAsCanonical
Whether to print entities as written or canonically.
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition: Sema.h:11930
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition: Sema.h:11926
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition: Sema.h:11919
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition: Sema.h:11916
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition: Sema.h:11916
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12953
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:13060
A stack object to be created when performing template instantiation.
Definition: Sema.h:13144
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13304
NamedDecl * Previous
Definition: Sema.h:353
Location information for a TemplateArgument.
Definition: TemplateBase.h:480
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)