clang 19.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"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/SmallBitVector.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43
44#include <iterator>
45#include <optional>
46using namespace clang;
47using namespace sema;
48
49// Exported for use by Parser.
52 unsigned N) {
53 if (!N) return SourceRange();
54 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
55}
56
57unsigned Sema::getTemplateDepth(Scope *S) const {
58 unsigned Depth = 0;
59
60 // Each template parameter scope represents one level of template parameter
61 // depth.
62 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
63 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
64 ++Depth;
65 }
66
67 // Note that there are template parameters with the given depth.
68 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
69
70 // Look for parameters of an enclosing generic lambda. We don't create a
71 // template parameter scope for these.
73 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
74 if (!LSI->TemplateParams.empty()) {
75 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
76 break;
77 }
78 if (LSI->GLTemplateParameterList) {
79 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
80 break;
81 }
82 }
83 }
84
85 // Look for parameters of an enclosing terse function template. We don't
86 // create a template parameter scope for these either.
87 for (const InventedTemplateParameterInfo &Info :
89 if (!Info.TemplateParams.empty()) {
90 ParamsAtDepth(Info.AutoTemplateParameterDepth);
91 break;
92 }
93 }
94
95 return Depth;
96}
97
98/// \brief Determine whether the declaration found is acceptable as the name
99/// of a template and, if so, return that template declaration. Otherwise,
100/// returns null.
101///
102/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
103/// is true. In all other cases it will return a TemplateDecl (or null).
105 bool AllowFunctionTemplates,
106 bool AllowDependent) {
107 D = D->getUnderlyingDecl();
108
109 if (isa<TemplateDecl>(D)) {
110 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
111 return nullptr;
112
113 return D;
114 }
115
116 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
117 // C++ [temp.local]p1:
118 // Like normal (non-template) classes, class templates have an
119 // injected-class-name (Clause 9). The injected-class-name
120 // can be used with or without a template-argument-list. When
121 // it is used without a template-argument-list, it is
122 // equivalent to the injected-class-name followed by the
123 // template-parameters of the class template enclosed in
124 // <>. When it is used with a template-argument-list, it
125 // refers to the specified class template specialization,
126 // which could be the current specialization or another
127 // specialization.
128 if (Record->isInjectedClassName()) {
129 Record = cast<CXXRecordDecl>(Record->getDeclContext());
130 if (Record->getDescribedClassTemplate())
131 return Record->getDescribedClassTemplate();
132
133 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
134 return Spec->getSpecializedTemplate();
135 }
136
137 return nullptr;
138 }
139
140 // 'using Dependent::foo;' can resolve to a template name.
141 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
142 // injected-class-name).
143 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
144 return D;
145
146 return nullptr;
147}
148
150 bool AllowFunctionTemplates,
151 bool AllowDependent) {
152 LookupResult::Filter filter = R.makeFilter();
153 while (filter.hasNext()) {
154 NamedDecl *Orig = filter.next();
155 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
156 filter.erase();
157 }
158 filter.done();
159}
160
162 bool AllowFunctionTemplates,
163 bool AllowDependent,
164 bool AllowNonTemplateFunctions) {
165 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
166 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
167 return true;
168 if (AllowNonTemplateFunctions &&
169 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
170 return true;
171 }
172
173 return false;
174}
175
177 CXXScopeSpec &SS,
178 bool hasTemplateKeyword,
179 const UnqualifiedId &Name,
180 ParsedType ObjectTypePtr,
181 bool EnteringContext,
182 TemplateTy &TemplateResult,
183 bool &MemberOfUnknownSpecialization,
184 bool Disambiguation) {
185 assert(getLangOpts().CPlusPlus && "No template names in C!");
186
187 DeclarationName TName;
188 MemberOfUnknownSpecialization = false;
189
190 switch (Name.getKind()) {
192 TName = DeclarationName(Name.Identifier);
193 break;
194
197 Name.OperatorFunctionId.Operator);
198 break;
199
201 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
202 break;
203
204 default:
205 return TNK_Non_template;
206 }
207
208 QualType ObjectType = ObjectTypePtr.get();
209
210 AssumedTemplateKind AssumedTemplate;
211 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
212 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
213 MemberOfUnknownSpecialization, SourceLocation(),
214 &AssumedTemplate,
215 /*AllowTypoCorrection=*/!Disambiguation))
216 return TNK_Non_template;
217
218 if (AssumedTemplate != AssumedTemplateKind::None) {
219 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
220 // Let the parser know whether we found nothing or found functions; if we
221 // found nothing, we want to more carefully check whether this is actually
222 // a function template name versus some other kind of undeclared identifier.
223 return AssumedTemplate == AssumedTemplateKind::FoundNothing
226 }
227
228 if (R.empty())
229 return TNK_Non_template;
230
231 NamedDecl *D = nullptr;
232 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
233 if (R.isAmbiguous()) {
234 // If we got an ambiguity involving a non-function template, treat this
235 // as a template name, and pick an arbitrary template for error recovery.
236 bool AnyFunctionTemplates = false;
237 for (NamedDecl *FoundD : R) {
238 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
239 if (isa<FunctionTemplateDecl>(FoundTemplate))
240 AnyFunctionTemplates = true;
241 else {
242 D = FoundTemplate;
243 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
244 break;
245 }
246 }
247 }
248
249 // If we didn't find any templates at all, this isn't a template name.
250 // Leave the ambiguity for a later lookup to diagnose.
251 if (!D && !AnyFunctionTemplates) {
252 R.suppressDiagnostics();
253 return TNK_Non_template;
254 }
255
256 // If the only templates were function templates, filter out the rest.
257 // We'll diagnose the ambiguity later.
258 if (!D)
260 }
261
262 // At this point, we have either picked a single template name declaration D
263 // or we have a non-empty set of results R containing either one template name
264 // declaration or a set of function templates.
265
266 TemplateName Template;
267 TemplateNameKind TemplateKind;
268
269 unsigned ResultCount = R.end() - R.begin();
270 if (!D && ResultCount > 1) {
271 // We assume that we'll preserve the qualifier from a function
272 // template name in other ways.
273 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
274 TemplateKind = TNK_Function_template;
275
276 // We'll do this lookup again later.
278 } else {
279 if (!D) {
281 assert(D && "unambiguous result is not a template name");
282 }
283
284 if (isa<UnresolvedUsingValueDecl>(D)) {
285 // We don't yet know whether this is a template-name or not.
286 MemberOfUnknownSpecialization = true;
287 return TNK_Non_template;
288 }
289
290 TemplateDecl *TD = cast<TemplateDecl>(D);
291 Template =
292 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
293 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
294 if (SS.isSet() && !SS.isInvalid()) {
295 NestedNameSpecifier *Qualifier = SS.getScopeRep();
296 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
297 Template);
298 }
299
300 if (isa<FunctionTemplateDecl>(TD)) {
301 TemplateKind = TNK_Function_template;
302
303 // We'll do this lookup again later.
305 } else {
306 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
307 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
308 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
309 TemplateKind =
310 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
311 isa<ConceptDecl>(TD) ? TNK_Concept_template :
313 }
314 }
315
316 TemplateResult = TemplateTy::make(Template);
317 return TemplateKind;
318}
319
321 SourceLocation NameLoc, CXXScopeSpec &SS,
322 ParsedTemplateTy *Template /*=nullptr*/) {
323 bool MemberOfUnknownSpecialization = false;
324
325 // We could use redeclaration lookup here, but we don't need to: the
326 // syntactic form of a deduction guide is enough to identify it even
327 // if we can't look up the template name at all.
328 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330 /*EnteringContext*/ false,
331 MemberOfUnknownSpecialization))
332 return false;
333
334 if (R.empty()) return false;
335 if (R.isAmbiguous()) {
336 // FIXME: Diagnose an ambiguity if we find at least one template.
338 return false;
339 }
340
341 // We only treat template-names that name type templates as valid deduction
342 // guide names.
344 if (!TD || !getAsTypeTemplateDecl(TD))
345 return false;
346
347 if (Template)
348 *Template = TemplateTy::make(TemplateName(TD));
349 return true;
350}
351
353 SourceLocation IILoc,
354 Scope *S,
355 const CXXScopeSpec *SS,
356 TemplateTy &SuggestedTemplate,
357 TemplateNameKind &SuggestedKind) {
358 // We can't recover unless there's a dependent scope specifier preceding the
359 // template name.
360 // FIXME: Typo correction?
361 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
363 return false;
364
365 // The code is missing a 'template' keyword prior to the dependent template
366 // name.
368 Diag(IILoc, diag::err_template_kw_missing)
369 << Qualifier << II.getName()
370 << FixItHint::CreateInsertion(IILoc, "template ");
371 SuggestedTemplate
373 SuggestedKind = TNK_Dependent_template_name;
374 return true;
375}
376
378 Scope *S, CXXScopeSpec &SS,
379 QualType ObjectType,
380 bool EnteringContext,
381 bool &MemberOfUnknownSpecialization,
382 RequiredTemplateKind RequiredTemplate,
384 bool AllowTypoCorrection) {
385 if (ATK)
387
388 if (SS.isInvalid())
389 return true;
390
391 Found.setTemplateNameLookup(true);
392
393 // Determine where to perform name lookup
394 MemberOfUnknownSpecialization = false;
395 DeclContext *LookupCtx = nullptr;
396 bool IsDependent = false;
397 if (!ObjectType.isNull()) {
398 // This nested-name-specifier occurs in a member access expression, e.g.,
399 // x->B::f, and we are looking into the type of the object.
400 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
401 LookupCtx = computeDeclContext(ObjectType);
402 IsDependent = !LookupCtx && ObjectType->isDependentType();
403 assert((IsDependent || !ObjectType->isIncompleteType() ||
404 !ObjectType->getAs<TagType>() ||
405 ObjectType->castAs<TagType>()->isBeingDefined()) &&
406 "Caller should have completed object type");
407
408 // Template names cannot appear inside an Objective-C class or object type
409 // or a vector type.
410 //
411 // FIXME: This is wrong. For example:
412 //
413 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
414 // Vec<int> vi;
415 // vi.Vec<int>::~Vec<int>();
416 //
417 // ... should be accepted but we will not treat 'Vec' as a template name
418 // here. The right thing to do would be to check if the name is a valid
419 // vector component name, and look up a template name if not. And similarly
420 // for lookups into Objective-C class and object types, where the same
421 // problem can arise.
422 if (ObjectType->isObjCObjectOrInterfaceType() ||
423 ObjectType->isVectorType()) {
424 Found.clear();
425 return false;
426 }
427 } else if (SS.isNotEmpty()) {
428 // This nested-name-specifier occurs after another nested-name-specifier,
429 // so long into the context associated with the prior nested-name-specifier.
430 LookupCtx = computeDeclContext(SS, EnteringContext);
431 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
432
433 // The declaration context must be complete.
434 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
435 return true;
436 }
437
438 bool ObjectTypeSearchedInScope = false;
439 bool AllowFunctionTemplatesInLookup = true;
440 if (LookupCtx) {
441 // Perform "qualified" name lookup into the declaration context we
442 // computed, which is either the type of the base of a member access
443 // expression or the declaration context associated with a prior
444 // nested-name-specifier.
445 LookupQualifiedName(Found, LookupCtx);
446
447 // FIXME: The C++ standard does not clearly specify what happens in the
448 // case where the object type is dependent, and implementations vary. In
449 // Clang, we treat a name after a . or -> as a template-name if lookup
450 // finds a non-dependent member or member of the current instantiation that
451 // is a type template, or finds no such members and lookup in the context
452 // of the postfix-expression finds a type template. In the latter case, the
453 // name is nonetheless dependent, and we may resolve it to a member of an
454 // unknown specialization when we come to instantiate the template.
455 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
456 }
457
458 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
459 // C++ [basic.lookup.classref]p1:
460 // In a class member access expression (5.2.5), if the . or -> token is
461 // immediately followed by an identifier followed by a <, the
462 // identifier must be looked up to determine whether the < is the
463 // beginning of a template argument list (14.2) or a less-than operator.
464 // The identifier is first looked up in the class of the object
465 // expression. If the identifier is not found, it is then looked up in
466 // the context of the entire postfix-expression and shall name a class
467 // template.
468 if (S)
469 LookupName(Found, S);
470
471 if (!ObjectType.isNull()) {
472 // FIXME: We should filter out all non-type templates here, particularly
473 // variable templates and concepts. But the exclusion of alias templates
474 // and template template parameters is a wording defect.
475 AllowFunctionTemplatesInLookup = false;
476 ObjectTypeSearchedInScope = true;
477 }
478
479 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
480 }
481
482 if (Found.isAmbiguous())
483 return false;
484
485 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
486 !RequiredTemplate.hasTemplateKeyword()) {
487 // C++2a [temp.names]p2:
488 // A name is also considered to refer to a template if it is an
489 // unqualified-id followed by a < and name lookup finds either one or more
490 // functions or finds nothing.
491 //
492 // To keep our behavior consistent, we apply the "finds nothing" part in
493 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
494 // successfully form a call to an undeclared template-id.
495 bool AllFunctions =
496 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
497 return isa<FunctionDecl>(ND->getUnderlyingDecl());
498 });
499 if (AllFunctions || (Found.empty() && !IsDependent)) {
500 // If lookup found any functions, or if this is a name that can only be
501 // used for a function, then strongly assume this is a function
502 // template-id.
503 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
506 Found.clear();
507 return false;
508 }
509 }
510
511 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
512 // If we did not find any names, and this is not a disambiguation, attempt
513 // to correct any typos.
514 DeclarationName Name = Found.getLookupName();
515 Found.clear();
516 // Simple filter callback that, for keywords, only accepts the C++ *_cast
517 DefaultFilterCCC FilterCCC{};
518 FilterCCC.WantTypeSpecifiers = false;
519 FilterCCC.WantExpressionKeywords = false;
520 FilterCCC.WantRemainingKeywords = false;
521 FilterCCC.WantCXXNamedCasts = true;
522 if (TypoCorrection Corrected =
523 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
524 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
525 if (auto *ND = Corrected.getFoundDecl())
526 Found.addDecl(ND);
528 if (Found.isAmbiguous()) {
529 Found.clear();
530 } else if (!Found.empty()) {
531 Found.setLookupName(Corrected.getCorrection());
532 if (LookupCtx) {
533 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
534 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
535 Name.getAsString() == CorrectedStr;
536 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
537 << Name << LookupCtx << DroppedSpecifier
538 << SS.getRange());
539 } else {
540 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
541 }
542 }
543 }
544 }
545
546 NamedDecl *ExampleLookupResult =
547 Found.empty() ? nullptr : Found.getRepresentativeDecl();
548 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
549 if (Found.empty()) {
550 if (IsDependent) {
551 MemberOfUnknownSpecialization = true;
552 return false;
553 }
554
555 // If a 'template' keyword was used, a lookup that finds only non-template
556 // names is an error.
557 if (ExampleLookupResult && RequiredTemplate) {
558 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
559 << Found.getLookupName() << SS.getRange()
560 << RequiredTemplate.hasTemplateKeyword()
561 << RequiredTemplate.getTemplateKeywordLoc();
562 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
563 diag::note_template_kw_refers_to_non_template)
564 << Found.getLookupName();
565 return true;
566 }
567
568 return false;
569 }
570
571 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
573 // C++03 [basic.lookup.classref]p1:
574 // [...] If the lookup in the class of the object expression finds a
575 // template, the name is also looked up in the context of the entire
576 // postfix-expression and [...]
577 //
578 // Note: C++11 does not perform this second lookup.
579 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
581 FoundOuter.setTemplateNameLookup(true);
582 LookupName(FoundOuter, S);
583 // FIXME: We silently accept an ambiguous lookup here, in violation of
584 // [basic.lookup]/1.
585 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
586
587 NamedDecl *OuterTemplate;
588 if (FoundOuter.empty()) {
589 // - if the name is not found, the name found in the class of the
590 // object expression is used, otherwise
591 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
592 !(OuterTemplate =
593 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
594 // - if the name is found in the context of the entire
595 // postfix-expression and does not name a class template, the name
596 // found in the class of the object expression is used, otherwise
597 FoundOuter.clear();
598 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
599 // - if the name found is a class template, it must refer to the same
600 // entity as the one found in the class of the object expression,
601 // otherwise the program is ill-formed.
602 if (!Found.isSingleResult() ||
604 OuterTemplate->getCanonicalDecl()) {
605 Diag(Found.getNameLoc(),
606 diag::ext_nested_name_member_ref_lookup_ambiguous)
607 << Found.getLookupName()
608 << ObjectType;
610 diag::note_ambig_member_ref_object_type)
611 << ObjectType;
612 Diag(FoundOuter.getFoundDecl()->getLocation(),
613 diag::note_ambig_member_ref_scope);
614
615 // Recover by taking the template that we found in the object
616 // expression's type.
617 }
618 }
619 }
620
621 return false;
622}
623
627 if (TemplateName.isInvalid())
628 return;
629
630 DeclarationNameInfo NameInfo;
631 CXXScopeSpec SS;
632 LookupNameKind LookupKind;
633
634 DeclContext *LookupCtx = nullptr;
635 NamedDecl *Found = nullptr;
636 bool MissingTemplateKeyword = false;
637
638 // Figure out what name we looked up.
639 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
640 NameInfo = DRE->getNameInfo();
641 SS.Adopt(DRE->getQualifierLoc());
642 LookupKind = LookupOrdinaryName;
643 Found = DRE->getFoundDecl();
644 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
645 NameInfo = ME->getMemberNameInfo();
646 SS.Adopt(ME->getQualifierLoc());
647 LookupKind = LookupMemberName;
648 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
649 Found = ME->getMemberDecl();
650 } else if (auto *DSDRE =
651 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
652 NameInfo = DSDRE->getNameInfo();
653 SS.Adopt(DSDRE->getQualifierLoc());
654 MissingTemplateKeyword = true;
655 } else if (auto *DSME =
656 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
657 NameInfo = DSME->getMemberNameInfo();
658 SS.Adopt(DSME->getQualifierLoc());
659 MissingTemplateKeyword = true;
660 } else {
661 llvm_unreachable("unexpected kind of potential template name");
662 }
663
664 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
665 // was missing.
666 if (MissingTemplateKeyword) {
667 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
668 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
669 return;
670 }
671
672 // Try to correct the name by looking for templates and C++ named casts.
673 struct TemplateCandidateFilter : CorrectionCandidateCallback {
674 Sema &S;
675 TemplateCandidateFilter(Sema &S) : S(S) {
676 WantTypeSpecifiers = false;
677 WantExpressionKeywords = false;
678 WantRemainingKeywords = false;
679 WantCXXNamedCasts = true;
680 };
681 bool ValidateCandidate(const TypoCorrection &Candidate) override {
682 if (auto *ND = Candidate.getCorrectionDecl())
683 return S.getAsTemplateNameDecl(ND);
684 return Candidate.isKeyword();
685 }
686
687 std::unique_ptr<CorrectionCandidateCallback> clone() override {
688 return std::make_unique<TemplateCandidateFilter>(*this);
689 }
690 };
691
692 DeclarationName Name = NameInfo.getName();
693 TemplateCandidateFilter CCC(*this);
694 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
695 CTK_ErrorRecovery, LookupCtx)) {
696 auto *ND = Corrected.getFoundDecl();
697 if (ND)
698 ND = getAsTemplateNameDecl(ND);
699 if (ND || Corrected.isKeyword()) {
700 if (LookupCtx) {
701 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
702 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
703 Name.getAsString() == CorrectedStr;
704 diagnoseTypo(Corrected,
705 PDiag(diag::err_non_template_in_member_template_id_suggest)
706 << Name << LookupCtx << DroppedSpecifier
707 << SS.getRange(), false);
708 } else {
709 diagnoseTypo(Corrected,
710 PDiag(diag::err_non_template_in_template_id_suggest)
711 << Name, false);
712 }
713 if (Found)
714 Diag(Found->getLocation(),
715 diag::note_non_template_in_template_id_found);
716 return;
717 }
718 }
719
720 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
721 << Name << SourceRange(Less, Greater);
722 if (Found)
723 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
724}
725
726/// ActOnDependentIdExpression - Handle a dependent id-expression that
727/// was just parsed. This is only possible with an explicit scope
728/// specifier naming a dependent type.
731 SourceLocation TemplateKWLoc,
732 const DeclarationNameInfo &NameInfo,
733 bool isAddressOfOperand,
734 const TemplateArgumentListInfo *TemplateArgs) {
736
737 // C++11 [expr.prim.general]p12:
738 // An id-expression that denotes a non-static data member or non-static
739 // member function of a class can only be used:
740 // (...)
741 // - if that id-expression denotes a non-static data member and it
742 // appears in an unevaluated operand.
743 //
744 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
745 // CXXDependentScopeMemberExpr. The former can instantiate to either
746 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
747 // always a MemberExpr.
748 bool MightBeCxx11UnevalField =
749 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
750
751 // Check if the nested name specifier is an enum type.
752 bool IsEnum = false;
753 if (NestedNameSpecifier *NNS = SS.getScopeRep())
754 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
755
756 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
757 isa<CXXMethodDecl>(DC) &&
758 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
759 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
760
761 // Since the 'this' expression is synthesized, we don't need to
762 // perform the double-lookup check.
763 NamedDecl *FirstQualifierInScope = nullptr;
764
766 Context, /*This=*/nullptr, ThisType,
767 /*IsArrow=*/!Context.getLangOpts().HLSL,
768 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
769 FirstQualifierInScope, NameInfo, TemplateArgs);
770 }
771
772 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
773}
774
777 SourceLocation TemplateKWLoc,
778 const DeclarationNameInfo &NameInfo,
779 const TemplateArgumentListInfo *TemplateArgs) {
780 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
782 if (!QualifierLoc)
783 return ExprError();
784
786 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
787}
788
789
790/// Determine whether we would be unable to instantiate this template (because
791/// it either has no definition, or is in the process of being instantiated).
793 NamedDecl *Instantiation,
794 bool InstantiatedFromMember,
795 const NamedDecl *Pattern,
796 const NamedDecl *PatternDef,
798 bool Complain /*= true*/) {
799 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
800 isa<VarDecl>(Instantiation));
801
802 bool IsEntityBeingDefined = false;
803 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
804 IsEntityBeingDefined = TD->isBeingDefined();
805
806 if (PatternDef && !IsEntityBeingDefined) {
807 NamedDecl *SuggestedDef = nullptr;
808 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
809 &SuggestedDef,
810 /*OnlyNeedComplete*/ false)) {
811 // If we're allowed to diagnose this and recover, do so.
812 bool Recover = Complain && !isSFINAEContext();
813 if (Complain)
814 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
816 return !Recover;
817 }
818 return false;
819 }
820
821 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
822 return true;
823
824 QualType InstantiationTy;
825 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
826 InstantiationTy = Context.getTypeDeclType(TD);
827 if (PatternDef) {
828 Diag(PointOfInstantiation,
829 diag::err_template_instantiate_within_definition)
830 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
831 << InstantiationTy;
832 // Not much point in noting the template declaration here, since
833 // we're lexically inside it.
834 Instantiation->setInvalidDecl();
835 } else if (InstantiatedFromMember) {
836 if (isa<FunctionDecl>(Instantiation)) {
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*member function*/ 1 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
842 } else {
843 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
844 Diag(PointOfInstantiation,
845 diag::err_implicit_instantiate_member_undefined)
846 << InstantiationTy;
847 Diag(Pattern->getLocation(), diag::note_member_declared_at);
848 }
849 } else {
850 if (isa<FunctionDecl>(Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_func_template)
853 << Pattern;
854 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
855 } else if (isa<TagDecl>(Instantiation)) {
856 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
857 << (TSK != TSK_ImplicitInstantiation)
858 << InstantiationTy;
859 NoteTemplateLocation(*Pattern);
860 } else {
861 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
862 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
863 Diag(PointOfInstantiation,
864 diag::err_explicit_instantiation_undefined_var_template)
865 << Instantiation;
866 Instantiation->setInvalidDecl();
867 } else
868 Diag(PointOfInstantiation,
869 diag::err_explicit_instantiation_undefined_member)
870 << /*static data member*/ 2 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
873 }
874 }
875
876 // In general, Instantiation isn't marked invalid to get more than one
877 // error for multiple undefined instantiations. But the code that does
878 // explicit declaration -> explicit definition conversion can't handle
879 // invalid declarations, so mark as invalid in that case.
881 Instantiation->setInvalidDecl();
882 return true;
883}
884
886 bool SupportedForCompatibility) {
887 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
888
889 // C++23 [temp.local]p6:
890 // The name of a template-parameter shall not be bound to any following.
891 // declaration whose locus is contained by the scope to which the
892 // template-parameter belongs.
893 //
894 // When MSVC compatibility is enabled, the diagnostic is always a warning
895 // by default. Otherwise, it an error unless SupportedForCompatibility is
896 // true, in which case it is a default-to-error warning.
897 unsigned DiagId =
898 getLangOpts().MSVCCompat
899 ? diag::ext_template_param_shadow
900 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
901 : diag::err_template_param_shadow);
902 const auto *ND = cast<NamedDecl>(PrevDecl);
903 Diag(Loc, DiagId) << ND->getDeclName();
905}
906
907/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
908/// the parameter D to reference the templated declaration and return a pointer
909/// to the template declaration. Otherwise, do nothing to D and return null.
911 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
912 D = Temp->getTemplatedDecl();
913 return Temp;
914 }
915 return nullptr;
916}
917
919 SourceLocation EllipsisLoc) const {
920 assert(Kind == Template &&
921 "Only template template arguments can be pack expansions here");
922 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
923 "Template template argument pack expansion without packs");
925 Result.EllipsisLoc = EllipsisLoc;
926 return Result;
927}
928
930 const ParsedTemplateArgument &Arg) {
931
932 switch (Arg.getKind()) {
934 TypeSourceInfo *DI;
935 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
936 if (!DI)
937 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
939 }
940
942 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
944 }
945
947 TemplateName Template = Arg.getAsTemplate().get();
948 TemplateArgument TArg;
949 if (Arg.getEllipsisLoc().isValid())
950 TArg = TemplateArgument(Template, std::optional<unsigned int>());
951 else
952 TArg = Template;
953 return TemplateArgumentLoc(
954 SemaRef.Context, TArg,
956 Arg.getLocation(), Arg.getEllipsisLoc());
957 }
958 }
959
960 llvm_unreachable("Unhandled parsed template argument");
961}
962
963/// Translates template arguments as provided by the parser
964/// into template arguments used by semantic analysis.
966 TemplateArgumentListInfo &TemplateArgs) {
967 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
968 TemplateArgs.addArgument(translateTemplateArgument(*this,
969 TemplateArgsIn[I]));
970}
971
973 SourceLocation Loc,
974 const IdentifierInfo *Name) {
975 NamedDecl *PrevDecl =
976 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
977 RedeclarationKind::ForVisibleRedeclaration);
978 if (PrevDecl && PrevDecl->isTemplateParameter())
979 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
980}
981
982/// Convert a parsed type into a parsed template argument. This is mostly
983/// trivial, except that we may have parsed a C++17 deduced class template
984/// specialization type, in which case we should form a template template
985/// argument instead of a type template argument.
987 TypeSourceInfo *TInfo;
989 if (T.isNull())
990 return ParsedTemplateArgument();
991 assert(TInfo && "template argument with no location");
992
993 // If we might have formed a deduced template specialization type, convert
994 // it to a template template argument.
995 if (getLangOpts().CPlusPlus17) {
996 TypeLoc TL = TInfo->getTypeLoc();
997 SourceLocation EllipsisLoc;
998 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
999 EllipsisLoc = PET.getEllipsisLoc();
1000 TL = PET.getPatternLoc();
1001 }
1002
1003 CXXScopeSpec SS;
1004 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1005 SS.Adopt(ET.getQualifierLoc());
1006 TL = ET.getNamedTypeLoc();
1007 }
1008
1009 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1010 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1011 if (SS.isSet())
1013 /*HasTemplateKeyword=*/false,
1014 Name);
1016 DTST.getTemplateNameLoc());
1017 if (EllipsisLoc.isValid())
1018 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1019 return Result;
1020 }
1021 }
1022
1023 // This is a normal type template argument. Note, if the type template
1024 // argument is an injected-class-name for a template, it has a dual nature
1025 // and can be used as either a type or a template. We handle that in
1026 // convertTypeTemplateArgumentToTemplate.
1029 TInfo->getTypeLoc().getBeginLoc());
1030}
1031
1032/// ActOnTypeParameter - Called when a C++ template type parameter
1033/// (e.g., "typename T") has been parsed. Typename specifies whether
1034/// the keyword "typename" was used to declare the type parameter
1035/// (otherwise, "class" was used), and KeyLoc is the location of the
1036/// "class" or "typename" keyword. ParamName is the name of the
1037/// parameter (NULL indicates an unnamed template parameter) and
1038/// ParamNameLoc is the location of the parameter name (if any).
1039/// If the type parameter has a default argument, it will be added
1040/// later via ActOnTypeParameterDefault.
1042 SourceLocation EllipsisLoc,
1043 SourceLocation KeyLoc,
1044 IdentifierInfo *ParamName,
1045 SourceLocation ParamNameLoc,
1046 unsigned Depth, unsigned Position,
1047 SourceLocation EqualLoc,
1048 ParsedType DefaultArg,
1049 bool HasTypeConstraint) {
1050 assert(S->isTemplateParamScope() &&
1051 "Template type parameter not in template parameter scope!");
1052
1053 bool IsParameterPack = EllipsisLoc.isValid();
1056 KeyLoc, ParamNameLoc, Depth, Position,
1057 ParamName, Typename, IsParameterPack,
1058 HasTypeConstraint);
1059 Param->setAccess(AS_public);
1060
1061 if (Param->isParameterPack())
1062 if (auto *LSI = getEnclosingLambda())
1063 LSI->LocalPacks.push_back(Param);
1064
1065 if (ParamName) {
1066 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1067
1068 // Add the template parameter into the current scope.
1069 S->AddDecl(Param);
1070 IdResolver.AddDecl(Param);
1071 }
1072
1073 // C++0x [temp.param]p9:
1074 // A default template-argument may be specified for any kind of
1075 // template-parameter that is not a template parameter pack.
1076 if (DefaultArg && IsParameterPack) {
1077 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1078 DefaultArg = nullptr;
1079 }
1080
1081 // Handle the default argument, if provided.
1082 if (DefaultArg) {
1083 TypeSourceInfo *DefaultTInfo;
1084 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1085
1086 assert(DefaultTInfo && "expected source information for type");
1087
1088 // Check for unexpanded parameter packs.
1089 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1091 return Param;
1092
1093 // Check the template argument itself.
1094 if (CheckTemplateArgument(DefaultTInfo)) {
1095 Param->setInvalidDecl();
1096 return Param;
1097 }
1098
1099 Param->setDefaultArgument(DefaultTInfo);
1100 }
1101
1102 return Param;
1103}
1104
1105/// Convert the parser's template argument list representation into our form.
1108 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1109 TemplateId.RAngleLoc);
1110 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1111 TemplateId.NumArgs);
1112 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1113 return TemplateArgs;
1114}
1115
1117
1118 TemplateName TN = TypeConstr->Template.get();
1119 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1120
1121 // C++2a [temp.param]p4:
1122 // [...] The concept designated by a type-constraint shall be a type
1123 // concept ([temp.concept]).
1124 if (!CD->isTypeConcept()) {
1125 Diag(TypeConstr->TemplateNameLoc,
1126 diag::err_type_constraint_non_type_concept);
1127 return true;
1128 }
1129
1130 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1131
1132 if (!WereArgsSpecified &&
1134 Diag(TypeConstr->TemplateNameLoc,
1135 diag::err_type_constraint_missing_arguments)
1136 << CD;
1137 return true;
1138 }
1139 return false;
1140}
1141
1143 TemplateIdAnnotation *TypeConstr,
1144 TemplateTypeParmDecl *ConstrainedParameter,
1145 SourceLocation EllipsisLoc) {
1146 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1147 false);
1148}
1149
1151 TemplateIdAnnotation *TypeConstr,
1152 TemplateTypeParmDecl *ConstrainedParameter,
1153 SourceLocation EllipsisLoc,
1154 bool AllowUnexpandedPack) {
1155
1156 if (CheckTypeConstraint(TypeConstr))
1157 return true;
1158
1159 TemplateName TN = TypeConstr->Template.get();
1160 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1162
1163 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1164 TypeConstr->TemplateNameLoc);
1165
1166 TemplateArgumentListInfo TemplateArgs;
1167 if (TypeConstr->LAngleLoc.isValid()) {
1168 TemplateArgs =
1169 makeTemplateArgumentListInfo(*this, *TypeConstr);
1170
1171 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1172 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1174 return true;
1175 }
1176 }
1177 }
1178 return AttachTypeConstraint(
1180 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1181 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1182 ConstrainedParameter, EllipsisLoc);
1183}
1184
1185template <typename ArgumentLocAppender>
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1189 SourceLocation RAngleLoc, QualType ConstrainedType,
1190 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1191 SourceLocation EllipsisLoc) {
1192
1193 TemplateArgumentListInfo ConstraintArgs;
1194 ConstraintArgs.addArgument(
1196 /*NTTPType=*/QualType(), ParamNameLoc));
1197
1198 ConstraintArgs.setRAngleLoc(RAngleLoc);
1199 ConstraintArgs.setLAngleLoc(LAngleLoc);
1200 Appender(ConstraintArgs);
1201
1202 // C++2a [temp.param]p4:
1203 // [...] This constraint-expression E is called the immediately-declared
1204 // constraint of T. [...]
1205 CXXScopeSpec SS;
1206 SS.Adopt(NS);
1207 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1208 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1209 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1210 &ConstraintArgs);
1211 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1212 return ImmediatelyDeclaredConstraint;
1213
1214 // C++2a [temp.param]p4:
1215 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1216 //
1217 // We have the following case:
1218 //
1219 // template<typename T> concept C1 = true;
1220 // template<C1... T> struct s1;
1221 //
1222 // The constraint: (C1<T> && ...)
1223 //
1224 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1225 // any unqualified lookups for 'operator&&' here.
1226 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1227 /*LParenLoc=*/SourceLocation(),
1228 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1229 EllipsisLoc, /*RHS=*/nullptr,
1230 /*RParenLoc=*/SourceLocation(),
1231 /*NumExpansions=*/std::nullopt);
1232}
1233
1234/// Attach a type-constraint to a template parameter.
1235/// \returns true if an error occurred. This can happen if the
1236/// immediately-declared constraint could not be formed (e.g. incorrect number
1237/// of arguments for the named concept).
1239 DeclarationNameInfo NameInfo,
1240 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1241 const TemplateArgumentListInfo *TemplateArgs,
1242 TemplateTypeParmDecl *ConstrainedParameter,
1243 SourceLocation EllipsisLoc) {
1244 // C++2a [temp.param]p4:
1245 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1246 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1247 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1249 *TemplateArgs) : nullptr;
1250
1251 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1252
1253 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1254 *this, NS, NameInfo, NamedConcept, FoundDecl,
1255 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1256 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1257 ParamAsArgument, ConstrainedParameter->getLocation(),
1258 [&](TemplateArgumentListInfo &ConstraintArgs) {
1259 if (TemplateArgs)
1260 for (const auto &ArgLoc : TemplateArgs->arguments())
1261 ConstraintArgs.addArgument(ArgLoc);
1262 },
1263 EllipsisLoc);
1264 if (ImmediatelyDeclaredConstraint.isInvalid())
1265 return true;
1266
1267 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1268 /*TemplateKWLoc=*/SourceLocation{},
1269 /*ConceptNameInfo=*/NameInfo,
1270 /*FoundDecl=*/FoundDecl,
1271 /*NamedConcept=*/NamedConcept,
1272 /*ArgsWritten=*/ArgsAsWritten);
1273 ConstrainedParameter->setTypeConstraint(CL,
1274 ImmediatelyDeclaredConstraint.get());
1275 return false;
1276}
1277
1279 NonTypeTemplateParmDecl *NewConstrainedParm,
1280 NonTypeTemplateParmDecl *OrigConstrainedParm,
1281 SourceLocation EllipsisLoc) {
1282 if (NewConstrainedParm->getType() != TL.getType() ||
1284 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1285 diag::err_unsupported_placeholder_constraint)
1286 << NewConstrainedParm->getTypeSourceInfo()
1287 ->getTypeLoc()
1288 .getSourceRange();
1289 return true;
1290 }
1291 // FIXME: Concepts: This should be the type of the placeholder, but this is
1292 // unclear in the wording right now.
1293 DeclRefExpr *Ref =
1294 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1295 VK_PRValue, OrigConstrainedParm->getLocation());
1296 if (!Ref)
1297 return true;
1298 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1300 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1302 OrigConstrainedParm->getLocation(),
1303 [&](TemplateArgumentListInfo &ConstraintArgs) {
1304 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1305 ConstraintArgs.addArgument(TL.getArgLoc(I));
1306 },
1307 EllipsisLoc);
1308 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1309 !ImmediatelyDeclaredConstraint.isUsable())
1310 return true;
1311
1312 NewConstrainedParm->setPlaceholderTypeConstraint(
1313 ImmediatelyDeclaredConstraint.get());
1314 return false;
1315}
1316
1317/// Check that the type of a non-type template parameter is
1318/// well-formed.
1319///
1320/// \returns the (possibly-promoted) parameter type if valid;
1321/// otherwise, produces a diagnostic and returns a NULL type.
1323 SourceLocation Loc) {
1324 if (TSI->getType()->isUndeducedType()) {
1325 // C++17 [temp.dep.expr]p3:
1326 // An id-expression is type-dependent if it contains
1327 // - an identifier associated by name lookup with a non-type
1328 // template-parameter declared with a type that contains a
1329 // placeholder type (7.1.7.4),
1331 }
1332
1333 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1334}
1335
1336/// Require the given type to be a structural type, and diagnose if it is not.
1337///
1338/// \return \c true if an error was produced.
1340 if (T->isDependentType())
1341 return false;
1342
1343 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1344 return true;
1345
1346 if (T->isStructuralType())
1347 return false;
1348
1349 // Structural types are required to be object types or lvalue references.
1350 if (T->isRValueReferenceType()) {
1351 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1352 return true;
1353 }
1354
1355 // Don't mention structural types in our diagnostic prior to C++20. Also,
1356 // there's not much more we can say about non-scalar non-class types --
1357 // because we can't see functions or arrays here, those can only be language
1358 // extensions.
1359 if (!getLangOpts().CPlusPlus20 ||
1360 (!T->isScalarType() && !T->isRecordType())) {
1361 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1362 return true;
1363 }
1364
1365 // Structural types are required to be literal types.
1366 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1367 return true;
1368
1369 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1370
1371 // Drill down into the reason why the class is non-structural.
1372 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1373 // All members are required to be public and non-mutable, and can't be of
1374 // rvalue reference type. Check these conditions first to prefer a "local"
1375 // reason over a more distant one.
1376 for (const FieldDecl *FD : RD->fields()) {
1377 if (FD->getAccess() != AS_public) {
1378 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1379 return true;
1380 }
1381 if (FD->isMutable()) {
1382 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1383 return true;
1384 }
1385 if (FD->getType()->isRValueReferenceType()) {
1386 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1387 << T;
1388 return true;
1389 }
1390 }
1391
1392 // All bases are required to be public.
1393 for (const auto &BaseSpec : RD->bases()) {
1394 if (BaseSpec.getAccessSpecifier() != AS_public) {
1395 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1396 << T << 1;
1397 return true;
1398 }
1399 }
1400
1401 // All subobjects are required to be of structural types.
1402 SourceLocation SubLoc;
1403 QualType SubType;
1404 int Kind = -1;
1405
1406 for (const FieldDecl *FD : RD->fields()) {
1407 QualType T = Context.getBaseElementType(FD->getType());
1408 if (!T->isStructuralType()) {
1409 SubLoc = FD->getLocation();
1410 SubType = T;
1411 Kind = 0;
1412 break;
1413 }
1414 }
1415
1416 if (Kind == -1) {
1417 for (const auto &BaseSpec : RD->bases()) {
1418 QualType T = BaseSpec.getType();
1419 if (!T->isStructuralType()) {
1420 SubLoc = BaseSpec.getBaseTypeLoc();
1421 SubType = T;
1422 Kind = 1;
1423 break;
1424 }
1425 }
1426 }
1427
1428 assert(Kind != -1 && "couldn't find reason why type is not structural");
1429 Diag(SubLoc, diag::note_not_structural_subobject)
1430 << T << Kind << SubType;
1431 T = SubType;
1432 RD = T->getAsCXXRecordDecl();
1433 }
1434
1435 return true;
1436}
1437
1439 SourceLocation Loc) {
1440 // We don't allow variably-modified types as the type of non-type template
1441 // parameters.
1442 if (T->isVariablyModifiedType()) {
1443 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1444 << T;
1445 return QualType();
1446 }
1447
1448 // C++ [temp.param]p4:
1449 //
1450 // A non-type template-parameter shall have one of the following
1451 // (optionally cv-qualified) types:
1452 //
1453 // -- integral or enumeration type,
1455 // -- pointer to object or pointer to function,
1456 T->isPointerType() ||
1457 // -- lvalue reference to object or lvalue reference to function,
1459 // -- pointer to member,
1461 // -- std::nullptr_t, or
1462 T->isNullPtrType() ||
1463 // -- a type that contains a placeholder type.
1464 T->isUndeducedType()) {
1465 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1466 // are ignored when determining its type.
1467 return T.getUnqualifiedType();
1468 }
1469
1470 // C++ [temp.param]p8:
1471 //
1472 // A non-type template-parameter of type "array of T" or
1473 // "function returning T" is adjusted to be of type "pointer to
1474 // T" or "pointer to function returning T", respectively.
1475 if (T->isArrayType() || T->isFunctionType())
1476 return Context.getDecayedType(T);
1477
1478 // If T is a dependent type, we can't do the check now, so we
1479 // assume that it is well-formed. Note that stripping off the
1480 // qualifiers here is not really correct if T turns out to be
1481 // an array type, but we'll recompute the type everywhere it's
1482 // used during instantiation, so that should be OK. (Using the
1483 // qualified type is equally wrong.)
1484 if (T->isDependentType())
1485 return T.getUnqualifiedType();
1486
1487 // C++20 [temp.param]p6:
1488 // -- a structural type
1489 if (RequireStructuralType(T, Loc))
1490 return QualType();
1491
1492 if (!getLangOpts().CPlusPlus20) {
1493 // FIXME: Consider allowing structural types as an extension in C++17. (In
1494 // earlier language modes, the template argument evaluation rules are too
1495 // inflexible.)
1496 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1497 return QualType();
1498 }
1499
1500 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1501 return T.getUnqualifiedType();
1502}
1503
1505 unsigned Depth,
1506 unsigned Position,
1507 SourceLocation EqualLoc,
1508 Expr *Default) {
1510
1511 // Check that we have valid decl-specifiers specified.
1512 auto CheckValidDeclSpecifiers = [this, &D] {
1513 // C++ [temp.param]
1514 // p1
1515 // template-parameter:
1516 // ...
1517 // parameter-declaration
1518 // p2
1519 // ... A storage class shall not be specified in a template-parameter
1520 // declaration.
1521 // [dcl.typedef]p1:
1522 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1523 // of a parameter-declaration
1524 const DeclSpec &DS = D.getDeclSpec();
1525 auto EmitDiag = [this](SourceLocation Loc) {
1526 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1528 };
1530 EmitDiag(DS.getStorageClassSpecLoc());
1531
1533 EmitDiag(DS.getThreadStorageClassSpecLoc());
1534
1535 // [dcl.inline]p1:
1536 // The inline specifier can be applied only to the declaration or
1537 // definition of a variable or function.
1538
1539 if (DS.isInlineSpecified())
1540 EmitDiag(DS.getInlineSpecLoc());
1541
1542 // [dcl.constexpr]p1:
1543 // The constexpr specifier shall be applied only to the definition of a
1544 // variable or variable template or the declaration of a function or
1545 // function template.
1546
1547 if (DS.hasConstexprSpecifier())
1548 EmitDiag(DS.getConstexprSpecLoc());
1549
1550 // [dcl.fct.spec]p1:
1551 // Function-specifiers can be used only in function declarations.
1552
1553 if (DS.isVirtualSpecified())
1554 EmitDiag(DS.getVirtualSpecLoc());
1555
1556 if (DS.hasExplicitSpecifier())
1557 EmitDiag(DS.getExplicitSpecLoc());
1558
1559 if (DS.isNoreturnSpecified())
1560 EmitDiag(DS.getNoreturnSpecLoc());
1561 };
1562
1563 CheckValidDeclSpecifiers();
1564
1565 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1566 if (isa<AutoType>(T))
1568 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1569 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1570
1571 assert(S->isTemplateParamScope() &&
1572 "Non-type template parameter not in template parameter scope!");
1573 bool Invalid = false;
1574
1576 if (T.isNull()) {
1577 T = Context.IntTy; // Recover with an 'int' type.
1578 Invalid = true;
1579 }
1580
1582
1583 const IdentifierInfo *ParamName = D.getIdentifier();
1584 bool IsParameterPack = D.hasEllipsis();
1587 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1588 TInfo);
1589 Param->setAccess(AS_public);
1590
1592 if (TL.isConstrained())
1593 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1594 Invalid = true;
1595
1596 if (Invalid)
1597 Param->setInvalidDecl();
1598
1599 if (Param->isParameterPack())
1600 if (auto *LSI = getEnclosingLambda())
1601 LSI->LocalPacks.push_back(Param);
1602
1603 if (ParamName) {
1605 ParamName);
1606
1607 // Add the template parameter into the current scope.
1608 S->AddDecl(Param);
1609 IdResolver.AddDecl(Param);
1610 }
1611
1612 // C++0x [temp.param]p9:
1613 // A default template-argument may be specified for any kind of
1614 // template-parameter that is not a template parameter pack.
1615 if (Default && IsParameterPack) {
1616 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1617 Default = nullptr;
1618 }
1619
1620 // Check the well-formedness of the default template argument, if provided.
1621 if (Default) {
1622 // Check for unexpanded parameter packs.
1624 return Param;
1625
1627 }
1628
1629 return Param;
1630}
1631
1632/// ActOnTemplateTemplateParameter - Called when a C++ template template
1633/// parameter (e.g. T in template <template <typename> class T> class array)
1634/// has been parsed. S is the current scope.
1636 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1637 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1638 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1640 assert(S->isTemplateParamScope() &&
1641 "Template template parameter not in template parameter scope!");
1642
1643 // Construct the parameter object.
1644 bool IsParameterPack = EllipsisLoc.isValid();
1647 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1648 Name, Typename, Params);
1649 Param->setAccess(AS_public);
1650
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambda())
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 Param->setInvalidDecl();
1668 }
1669
1670 // C++0x [temp.param]p9:
1671 // A default template-argument may be specified for any kind of
1672 // template-parameter that is not a template parameter pack.
1673 if (IsParameterPack && !Default.isInvalid()) {
1674 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1676 }
1677
1678 if (!Default.isInvalid()) {
1679 // Check only that we have a template template argument. We don't want to
1680 // try to check well-formedness now, because our template template parameter
1681 // might have dependent types in its template parameters, which we wouldn't
1682 // be able to match now.
1683 //
1684 // If none of the template template parameter's template arguments mention
1685 // other template parameters, we could actually perform more checking here.
1686 // However, it isn't worth doing.
1688 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1689 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1690 << DefaultArg.getSourceRange();
1691 return Param;
1692 }
1693
1694 // Check for unexpanded parameter packs.
1696 DefaultArg.getArgument().getAsTemplate(),
1698 return Param;
1699
1700 Param->setDefaultArgument(Context, DefaultArg);
1701 }
1702
1703 return Param;
1704}
1705
1706namespace {
1707class ConstraintRefersToContainingTemplateChecker
1708 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1709 bool Result = false;
1710 const FunctionDecl *Friend = nullptr;
1711 unsigned TemplateDepth = 0;
1712
1713 // Check a record-decl that we've seen to see if it is a lexical parent of the
1714 // Friend, likely because it was referred to without its template arguments.
1715 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1716 CheckingRD = CheckingRD->getMostRecentDecl();
1717 if (!CheckingRD->isTemplated())
1718 return;
1719
1720 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1721 DC && !DC->isFileContext(); DC = DC->getParent())
1722 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1723 if (CheckingRD == RD->getMostRecentDecl())
1724 Result = true;
1725 }
1726
1727 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1728 assert(D->getDepth() <= TemplateDepth &&
1729 "Nothing should reference a value below the actual template depth, "
1730 "depth is likely wrong");
1731 if (D->getDepth() != TemplateDepth)
1732 Result = true;
1733
1734 // Necessary because the type of the NTTP might be what refers to the parent
1735 // constriant.
1736 TransformType(D->getType());
1737 }
1738
1739public:
1741
1742 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1743 const FunctionDecl *Friend,
1744 unsigned TemplateDepth)
1745 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1746 bool getResult() const { return Result; }
1747
1748 // This should be the only template parm type that we have to deal with.
1749 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1750 // FunctionParmPackExpr are all partially substituted, which cannot happen
1751 // with concepts at this point in translation.
1752 using inherited::TransformTemplateTypeParmType;
1753 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1754 TemplateTypeParmTypeLoc TL, bool) {
1755 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1756 "Nothing should reference a value below the actual template depth, "
1757 "depth is likely wrong");
1758 if (TL.getDecl()->getDepth() != TemplateDepth)
1759 Result = true;
1760 return inherited::TransformTemplateTypeParmType(
1761 TLB, TL,
1762 /*SuppressObjCLifetime=*/false);
1763 }
1764
1765 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1766 if (!D)
1767 return D;
1768 // FIXME : This is possibly an incomplete list, but it is unclear what other
1769 // Decl kinds could be used to refer to the template parameters. This is a
1770 // best guess so far based on examples currently available, but the
1771 // unreachable should catch future instances/cases.
1772 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1773 TransformType(TD->getUnderlyingType());
1774 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1775 CheckNonTypeTemplateParmDecl(NTTPD);
1776 else if (auto *VD = dyn_cast<ValueDecl>(D))
1777 TransformType(VD->getType());
1778 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1779 TransformTemplateParameterList(TD->getTemplateParameters());
1780 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1781 CheckIfContainingRecord(RD);
1782 else if (isa<NamedDecl>(D)) {
1783 // No direct types to visit here I believe.
1784 } else
1785 llvm_unreachable("Don't know how to handle this declaration type yet");
1786 return D;
1787 }
1788};
1789} // namespace
1790
1792 const FunctionDecl *Friend, unsigned TemplateDepth,
1793 const Expr *Constraint) {
1794 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1795 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1796 TemplateDepth);
1797 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1798 return Checker.getResult();
1799}
1800
1801/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1802/// constrained by RequiresClause, that contains the template parameters in
1803/// Params.
1806 SourceLocation ExportLoc,
1807 SourceLocation TemplateLoc,
1808 SourceLocation LAngleLoc,
1809 ArrayRef<NamedDecl *> Params,
1810 SourceLocation RAngleLoc,
1811 Expr *RequiresClause) {
1812 if (ExportLoc.isValid())
1813 Diag(ExportLoc, diag::warn_template_export_unsupported);
1814
1815 for (NamedDecl *P : Params)
1817
1819 Context, TemplateLoc, LAngleLoc,
1820 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1821}
1822
1824 const CXXScopeSpec &SS) {
1825 if (SS.isSet())
1826 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1827}
1828
1829// Returns the template parameter list with all default template argument
1830// information.
1832 // Make sure we get the template parameter list from the most
1833 // recent declaration, since that is the only one that is guaranteed to
1834 // have all the default template argument information.
1835 Decl *D = TD->getMostRecentDecl();
1836 // C++11 N3337 [temp.param]p12:
1837 // A default template argument shall not be specified in a friend class
1838 // template declaration.
1839 //
1840 // Skip past friend *declarations* because they are not supposed to contain
1841 // default template arguments. Moreover, these declarations may introduce
1842 // template parameters living in different template depths than the
1843 // corresponding template parameters in TD, causing unmatched constraint
1844 // substitution.
1845 //
1846 // FIXME: Diagnose such cases within a class template:
1847 // template <class T>
1848 // struct S {
1849 // template <class = void> friend struct C;
1850 // };
1851 // template struct S<int>;
1853 D->getPreviousDecl())
1854 D = D->getPreviousDecl();
1855 return cast<TemplateDecl>(D)->getTemplateParameters();
1856}
1857
1859 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1860 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1861 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1862 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1863 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1864 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1865 assert(TemplateParams && TemplateParams->size() > 0 &&
1866 "No template parameters");
1867 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1868 bool Invalid = false;
1869
1870 // Check that we can declare a template here.
1871 if (CheckTemplateDeclScope(S, TemplateParams))
1872 return true;
1873
1875 assert(Kind != TagTypeKind::Enum &&
1876 "can't build template of enumerated type");
1877
1878 // There is no such thing as an unnamed class template.
1879 if (!Name) {
1880 Diag(KWLoc, diag::err_template_unnamed_class);
1881 return true;
1882 }
1883
1884 // Find any previous declaration with this name. For a friend with no
1885 // scope explicitly specified, we only look for tag declarations (per
1886 // C++11 [basic.lookup.elab]p2).
1887 DeclContext *SemanticContext;
1888 LookupResult Previous(*this, Name, NameLoc,
1889 (SS.isEmpty() && TUK == TUK_Friend)
1892 if (SS.isNotEmpty() && !SS.isInvalid()) {
1893 SemanticContext = computeDeclContext(SS, true);
1894 if (!SemanticContext) {
1895 // FIXME: Horrible, horrible hack! We can't currently represent this
1896 // in the AST, and historically we have just ignored such friend
1897 // class templates, so don't complain here.
1898 Diag(NameLoc, TUK == TUK_Friend
1899 ? diag::warn_template_qualified_friend_ignored
1900 : diag::err_template_qualified_declarator_no_match)
1901 << SS.getScopeRep() << SS.getRange();
1902 return TUK != TUK_Friend;
1903 }
1904
1905 if (RequireCompleteDeclContext(SS, SemanticContext))
1906 return true;
1907
1908 // If we're adding a template to a dependent context, we may need to
1909 // rebuilding some of the types used within the template parameter list,
1910 // now that we know what the current instantiation is.
1911 if (SemanticContext->isDependentContext()) {
1912 ContextRAII SavedContext(*this, SemanticContext);
1914 Invalid = true;
1915 }
1916
1917 if (TUK != TUK_Friend && TUK != TUK_Reference)
1918 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1919 /*TemplateId-*/ nullptr,
1920 /*IsMemberSpecialization*/ false);
1921
1922 LookupQualifiedName(Previous, SemanticContext);
1923 } else {
1924 SemanticContext = CurContext;
1925
1926 // C++14 [class.mem]p14:
1927 // If T is the name of a class, then each of the following shall have a
1928 // name different from T:
1929 // -- every member template of class T
1930 if (TUK != TUK_Friend &&
1931 DiagnoseClassNameShadow(SemanticContext,
1932 DeclarationNameInfo(Name, NameLoc)))
1933 return true;
1934
1935 LookupName(Previous, S);
1936 }
1937
1938 if (Previous.isAmbiguous())
1939 return true;
1940
1941 NamedDecl *PrevDecl = nullptr;
1942 if (Previous.begin() != Previous.end())
1943 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1944
1945 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1946 // Maybe we will complain about the shadowed template parameter.
1947 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1948 // Just pretend that we didn't see the previous declaration.
1949 PrevDecl = nullptr;
1950 }
1951
1952 // If there is a previous declaration with the same name, check
1953 // whether this is a valid redeclaration.
1954 ClassTemplateDecl *PrevClassTemplate =
1955 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1956
1957 // We may have found the injected-class-name of a class template,
1958 // class template partial specialization, or class template specialization.
1959 // In these cases, grab the template that is being defined or specialized.
1960 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1961 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1962 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1963 PrevClassTemplate
1964 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1965 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1966 PrevClassTemplate
1967 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1968 ->getSpecializedTemplate();
1969 }
1970 }
1971
1972 if (TUK == TUK_Friend) {
1973 // C++ [namespace.memdef]p3:
1974 // [...] When looking for a prior declaration of a class or a function
1975 // declared as a friend, and when the name of the friend class or
1976 // function is neither a qualified name nor a template-id, scopes outside
1977 // the innermost enclosing namespace scope are not considered.
1978 if (!SS.isSet()) {
1979 DeclContext *OutermostContext = CurContext;
1980 while (!OutermostContext->isFileContext())
1981 OutermostContext = OutermostContext->getLookupParent();
1982
1983 if (PrevDecl &&
1984 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1985 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1986 SemanticContext = PrevDecl->getDeclContext();
1987 } else {
1988 // Declarations in outer scopes don't matter. However, the outermost
1989 // context we computed is the semantic context for our new
1990 // declaration.
1991 PrevDecl = PrevClassTemplate = nullptr;
1992 SemanticContext = OutermostContext;
1993
1994 // Check that the chosen semantic context doesn't already contain a
1995 // declaration of this name as a non-tag type.
1997 DeclContext *LookupContext = SemanticContext;
1998 while (LookupContext->isTransparentContext())
1999 LookupContext = LookupContext->getLookupParent();
2000 LookupQualifiedName(Previous, LookupContext);
2001
2002 if (Previous.isAmbiguous())
2003 return true;
2004
2005 if (Previous.begin() != Previous.end())
2006 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2007 }
2008 }
2009 } else if (PrevDecl &&
2010 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
2011 S, SS.isValid()))
2012 PrevDecl = PrevClassTemplate = nullptr;
2013
2014 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2015 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2016 if (SS.isEmpty() &&
2017 !(PrevClassTemplate &&
2018 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2019 SemanticContext->getRedeclContext()))) {
2020 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2021 Diag(Shadow->getTargetDecl()->getLocation(),
2022 diag::note_using_decl_target);
2023 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2024 // Recover by ignoring the old declaration.
2025 PrevDecl = PrevClassTemplate = nullptr;
2026 }
2027 }
2028
2029 if (PrevClassTemplate) {
2030 // Ensure that the template parameter lists are compatible. Skip this check
2031 // for a friend in a dependent context: the template parameter list itself
2032 // could be dependent.
2033 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2035 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2036 : CurContext,
2037 CurContext, KWLoc),
2038 TemplateParams, PrevClassTemplate,
2039 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2041 return true;
2042
2043 // C++ [temp.class]p4:
2044 // In a redeclaration, partial specialization, explicit
2045 // specialization or explicit instantiation of a class template,
2046 // the class-key shall agree in kind with the original class
2047 // template declaration (7.1.5.3).
2048 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2049 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2050 TUK == TUK_Definition, KWLoc, Name)) {
2051 Diag(KWLoc, diag::err_use_with_wrong_tag)
2052 << Name
2053 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2054 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2055 Kind = PrevRecordDecl->getTagKind();
2056 }
2057
2058 // Check for redefinition of this class template.
2059 if (TUK == TUK_Definition) {
2060 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2061 // If we have a prior definition that is not visible, treat this as
2062 // simply making that previous definition visible.
2063 NamedDecl *Hidden = nullptr;
2064 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2065 SkipBody->ShouldSkip = true;
2066 SkipBody->Previous = Def;
2067 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2068 assert(Tmpl && "original definition of a class template is not a "
2069 "class template?");
2072 } else {
2073 Diag(NameLoc, diag::err_redefinition) << Name;
2074 Diag(Def->getLocation(), diag::note_previous_definition);
2075 // FIXME: Would it make sense to try to "forget" the previous
2076 // definition, as part of error recovery?
2077 return true;
2078 }
2079 }
2080 }
2081 } else if (PrevDecl) {
2082 // C++ [temp]p5:
2083 // A class template shall not have the same name as any other
2084 // template, class, function, object, enumeration, enumerator,
2085 // namespace, or type in the same scope (3.3), except as specified
2086 // in (14.5.4).
2087 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2088 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2089 return true;
2090 }
2091
2092 // Check the template parameter list of this declaration, possibly
2093 // merging in the template parameter list from the previous class
2094 // template declaration. Skip this check for a friend in a dependent
2095 // context, because the template parameter list might be dependent.
2096 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2098 TemplateParams,
2099 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2100 : nullptr,
2101 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2102 SemanticContext->isDependentContext())
2106 SkipBody))
2107 Invalid = true;
2108
2109 if (SS.isSet()) {
2110 // If the name of the template was qualified, we must be defining the
2111 // template out-of-line.
2112 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2113 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2114 : diag::err_member_decl_does_not_match)
2115 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2116 Invalid = true;
2117 }
2118 }
2119
2120 // If this is a templated friend in a dependent context we should not put it
2121 // on the redecl chain. In some cases, the templated friend can be the most
2122 // recent declaration tricking the template instantiator to make substitutions
2123 // there.
2124 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2125 bool ShouldAddRedecl
2126 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2127
2128 CXXRecordDecl *NewClass =
2129 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2130 PrevClassTemplate && ShouldAddRedecl ?
2131 PrevClassTemplate->getTemplatedDecl() : nullptr,
2132 /*DelayTypeCreation=*/true);
2133 SetNestedNameSpecifier(*this, NewClass, SS);
2134 if (NumOuterTemplateParamLists > 0)
2136 Context,
2137 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2138
2139 // Add alignment attributes if necessary; these attributes are checked when
2140 // the ASTContext lays out the structure.
2141 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2144 }
2145
2146 ClassTemplateDecl *NewTemplate
2147 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2148 DeclarationName(Name), TemplateParams,
2149 NewClass);
2150
2151 if (ShouldAddRedecl)
2152 NewTemplate->setPreviousDecl(PrevClassTemplate);
2153
2154 NewClass->setDescribedClassTemplate(NewTemplate);
2155
2156 if (ModulePrivateLoc.isValid())
2157 NewTemplate->setModulePrivate();
2158
2159 // Build the type for the class template declaration now.
2161 T = Context.getInjectedClassNameType(NewClass, T);
2162 assert(T->isDependentType() && "Class template type is not dependent?");
2163 (void)T;
2164
2165 // If we are providing an explicit specialization of a member that is a
2166 // class template, make a note of that.
2167 if (PrevClassTemplate &&
2168 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2169 PrevClassTemplate->setMemberSpecialization();
2170
2171 // Set the access specifier.
2172 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2173 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2174
2175 // Set the lexical context of these templates
2177 NewTemplate->setLexicalDeclContext(CurContext);
2178
2179 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2180 NewClass->startDefinition();
2181
2182 ProcessDeclAttributeList(S, NewClass, Attr);
2183 ProcessAPINotes(NewClass);
2184
2185 if (PrevClassTemplate)
2186 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2187
2191
2192 if (TUK != TUK_Friend) {
2193 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2194 Scope *Outer = S;
2195 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2196 Outer = Outer->getParent();
2197 PushOnScopeChains(NewTemplate, Outer);
2198 } else {
2199 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2200 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2201 NewClass->setAccess(PrevClassTemplate->getAccess());
2202 }
2203
2204 NewTemplate->setObjectOfFriendDecl();
2205
2206 // Friend templates are visible in fairly strange ways.
2208 DeclContext *DC = SemanticContext->getRedeclContext();
2209 DC->makeDeclVisibleInContext(NewTemplate);
2210 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2211 PushOnScopeChains(NewTemplate, EnclosingScope,
2212 /* AddToContext = */ false);
2213 }
2214
2216 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2217 Friend->setAccess(AS_public);
2218 CurContext->addDecl(Friend);
2219 }
2220
2221 if (PrevClassTemplate)
2222 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2223
2224 if (Invalid) {
2225 NewTemplate->setInvalidDecl();
2226 NewClass->setInvalidDecl();
2227 }
2228
2229 ActOnDocumentableDecl(NewTemplate);
2230
2231 if (SkipBody && SkipBody->ShouldSkip)
2232 return SkipBody->Previous;
2233
2234 return NewTemplate;
2235}
2236
2237namespace {
2238/// Tree transform to "extract" a transformed type from a class template's
2239/// constructor to a deduction guide.
2240class ExtractTypeForDeductionGuide
2241 : public TreeTransform<ExtractTypeForDeductionGuide> {
2242 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2243
2244public:
2246 ExtractTypeForDeductionGuide(
2247 Sema &SemaRef,
2248 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2249 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2250
2251 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2252
2253 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2254 ASTContext &Context = SemaRef.getASTContext();
2255 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2256 TypedefNameDecl *Decl = OrigDecl;
2257 // Transform the underlying type of the typedef and clone the Decl only if
2258 // the typedef has a dependent context.
2259 if (OrigDecl->getDeclContext()->isDependentContext()) {
2260 TypeLocBuilder InnerTLB;
2261 QualType Transformed =
2262 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2263 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2264 if (isa<TypeAliasDecl>(OrigDecl))
2266 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2267 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2268 else {
2269 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2271 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2272 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2273 }
2274 MaterializedTypedefs.push_back(Decl);
2275 }
2276
2277 QualType TDTy = Context.getTypedefType(Decl);
2278 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2279 TypedefTL.setNameLoc(TL.getNameLoc());
2280
2281 return TDTy;
2282 }
2283};
2284
2285// Build a deduction guide with the specified parameter types.
2286FunctionTemplateDecl *buildDeductionGuide(
2287 Sema &SemaRef, TemplateDecl *OriginalTemplate,
2288 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2289 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2290 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
2291 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2292 DeclContext *DC = OriginalTemplate->getDeclContext();
2293 auto DeductionGuideName =
2295 OriginalTemplate);
2296
2297 DeclarationNameInfo Name(DeductionGuideName, Loc);
2299 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2300
2301 // Build the implicit deduction guide template.
2302 auto *Guide =
2303 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2304 TInfo->getType(), TInfo, LocEnd, Ctor);
2305 Guide->setImplicit(IsImplicit);
2306 Guide->setParams(Params);
2307
2308 for (auto *Param : Params)
2309 Param->setDeclContext(Guide);
2310 for (auto *TD : MaterializedTypedefs)
2311 TD->setDeclContext(Guide);
2312
2313 auto *GuideTemplate = FunctionTemplateDecl::Create(
2314 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2315 GuideTemplate->setImplicit(IsImplicit);
2316 Guide->setDescribedFunctionTemplate(GuideTemplate);
2317
2318 if (isa<CXXRecordDecl>(DC)) {
2319 Guide->setAccess(AS_public);
2320 GuideTemplate->setAccess(AS_public);
2321 }
2322
2323 DC->addDecl(GuideTemplate);
2324 return GuideTemplate;
2325}
2326
2327// Transform a given template type parameter `TTP`.
2329transformTemplateTypeParam(Sema &SemaRef, DeclContext *DC,
2332 unsigned NewDepth, unsigned NewIndex) {
2333 // TemplateTypeParmDecl's index cannot be changed after creation, so
2334 // substitute it directly.
2335 auto *NewTTP = TemplateTypeParmDecl::Create(
2336 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
2337 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2338 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2340 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2341 : std::nullopt);
2342 if (const auto *TC = TTP->getTypeConstraint())
2343 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2344 /*EvaluateConstraint=*/true);
2345 if (TTP->hasDefaultArgument()) {
2346 TypeSourceInfo *InstantiatedDefaultArg =
2347 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2348 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2349 if (InstantiatedDefaultArg)
2350 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2351 }
2352 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
2353 return NewTTP;
2354}
2355// Similar to above, but for non-type template or template template parameters.
2356template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
2357NonTypeTemplateOrTemplateTemplateParmDecl *
2358transformTemplateParam(Sema &SemaRef, DeclContext *DC,
2359 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
2360 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
2361 unsigned NewDepth) {
2362 // Ask the template instantiator to do the heavy lifting for us, then adjust
2363 // the index of the parameter once it's done.
2364 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
2365 SemaRef.SubstDecl(OldParam, DC, Args));
2366 NewParam->setPosition(NewIndex);
2367 NewParam->setDepth(NewDepth);
2368 return NewParam;
2369}
2370
2371/// Transform to convert portions of a constructor declaration into the
2372/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2373struct ConvertConstructorToDeductionGuideTransform {
2374 ConvertConstructorToDeductionGuideTransform(Sema &S,
2375 ClassTemplateDecl *Template)
2376 : SemaRef(S), Template(Template) {
2377 // If the template is nested, then we need to use the original
2378 // pattern to iterate over the constructors.
2379 ClassTemplateDecl *Pattern = Template;
2380 while (Pattern->getInstantiatedFromMemberTemplate()) {
2381 if (Pattern->isMemberSpecialization())
2382 break;
2383 Pattern = Pattern->getInstantiatedFromMemberTemplate();
2384 NestedPattern = Pattern;
2385 }
2386
2387 if (NestedPattern)
2388 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2389 }
2390
2391 Sema &SemaRef;
2392 ClassTemplateDecl *Template;
2393 ClassTemplateDecl *NestedPattern = nullptr;
2394
2395 DeclContext *DC = Template->getDeclContext();
2396 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2397 DeclarationName DeductionGuideName =
2399
2400 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2401
2402 // Index adjustment to apply to convert depth-1 template parameters into
2403 // depth-0 template parameters.
2404 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2405
2406 // Instantiation arguments for the outermost depth-1 templates
2407 // when the template is nested
2408 MultiLevelTemplateArgumentList OuterInstantiationArgs;
2409
2410 /// Transform a constructor declaration into a deduction guide.
2411 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2412 CXXConstructorDecl *CD) {
2414
2416
2417 // C++ [over.match.class.deduct]p1:
2418 // -- For each constructor of the class template designated by the
2419 // template-name, a function template with the following properties:
2420
2421 // -- The template parameters are the template parameters of the class
2422 // template followed by the template parameters (including default
2423 // template arguments) of the constructor, if any.
2424 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2425 if (FTD) {
2426 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2429 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2430 AllParams.insert(AllParams.begin(),
2431 TemplateParams->begin(), TemplateParams->end());
2432 SubstArgs.reserve(InnerParams->size());
2433 Depth1Args.reserve(InnerParams->size());
2434
2435 // Later template parameters could refer to earlier ones, so build up
2436 // a list of substituted template arguments as we go.
2437 for (NamedDecl *Param : *InnerParams) {
2439 Args.setKind(TemplateSubstitutionKind::Rewrite);
2440 Args.addOuterTemplateArguments(Depth1Args);
2441 Args.addOuterRetainedLevel();
2442 if (NestedPattern)
2443 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2444 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2445 if (!NewParam)
2446 return nullptr;
2447 // Constraints require that we substitute depth-1 arguments
2448 // to match depths when substituted for evaluation later
2449 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2450 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2451
2452 if (NestedPattern) {
2453 TemplateDeclInstantiator Instantiator(SemaRef, DC,
2454 OuterInstantiationArgs);
2455 Instantiator.setEvaluateConstraints(false);
2456 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2457 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2458 });
2459 }
2460
2461 assert(NewParam->getTemplateDepth() == 0 &&
2462 "Unexpected template parameter depth");
2463
2464 AllParams.push_back(NewParam);
2465 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2466 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2467 }
2468
2469 // Substitute new template parameters into requires-clause if present.
2470 Expr *RequiresClause = nullptr;
2471 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2473 Args.setKind(TemplateSubstitutionKind::Rewrite);
2474 Args.addOuterTemplateArguments(Depth1Args);
2475 Args.addOuterRetainedLevel();
2476 if (NestedPattern)
2477 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2478 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2479 if (E.isInvalid())
2480 return nullptr;
2481 RequiresClause = E.getAs<Expr>();
2482 }
2483
2484 TemplateParams = TemplateParameterList::Create(
2485 SemaRef.Context, InnerParams->getTemplateLoc(),
2486 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2487 RequiresClause);
2488 }
2489
2490 // If we built a new template-parameter-list, track that we need to
2491 // substitute references to the old parameters into references to the
2492 // new ones.
2494 Args.setKind(TemplateSubstitutionKind::Rewrite);
2495 if (FTD) {
2496 Args.addOuterTemplateArguments(SubstArgs);
2497 Args.addOuterRetainedLevel();
2498 }
2499
2500 if (NestedPattern)
2501 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2502
2505 assert(FPTL && "no prototype for constructor declaration");
2506
2507 // Transform the type of the function, adjusting the return type and
2508 // replacing references to the old parameters with references to the
2509 // new ones.
2510 TypeLocBuilder TLB;
2512 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2513 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2514 MaterializedTypedefs);
2515 if (NewType.isNull())
2516 return nullptr;
2517 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2518
2519 return buildDeductionGuide(
2520 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
2521 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
2522 /*IsImplicit=*/true, MaterializedTypedefs);
2523 }
2524
2525 /// Build a deduction guide with the specified parameter types.
2526 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2527 SourceLocation Loc = Template->getLocation();
2528
2529 // Build the requested type.
2531 EPI.HasTrailingReturn = true;
2532 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2533 DeductionGuideName, EPI);
2534 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2535 if (NestedPattern)
2536 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2537 DeductionGuideName);
2538
2541
2542 // Build the parameters, needed during deduction / substitution.
2544 for (auto T : ParamTypes) {
2545 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2546 if (NestedPattern)
2547 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2548 DeclarationName());
2549 ParmVarDecl *NewParam =
2550 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
2551 TSI->getType(), TSI, SC_None, nullptr);
2552 NewParam->setScopeInfo(0, Params.size());
2553 FPTL.setParam(Params.size(), NewParam);
2554 Params.push_back(NewParam);
2555 }
2556
2557 return buildDeductionGuide(
2558 SemaRef, Template, GetTemplateParameterList(Template), nullptr,
2559 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
2560 }
2561
2562private:
2563 /// Transform a constructor template parameter into a deduction guide template
2564 /// parameter, rebuilding any internal references to earlier parameters and
2565 /// renumbering as we go.
2566 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2568 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2569 return transformTemplateTypeParam(
2570 SemaRef, DC, TTP, Args, TTP->getDepth() - 1,
2571 Depth1IndexAdjustment + TTP->getIndex());
2572 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2573 return transformTemplateParam(SemaRef, DC, TTP, Args,
2574 Depth1IndexAdjustment + TTP->getIndex(),
2575 TTP->getDepth() - 1);
2576 auto *NTTP = cast<NonTypeTemplateParmDecl>(TemplateParam);
2577 return transformTemplateParam(SemaRef, DC, NTTP, Args,
2578 Depth1IndexAdjustment + NTTP->getIndex(),
2579 NTTP->getDepth() - 1);
2580 }
2581
2582 QualType transformFunctionProtoType(
2586 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2587 SmallVector<QualType, 4> ParamTypes;
2588 const FunctionProtoType *T = TL.getTypePtr();
2589
2590 // -- The types of the function parameters are those of the constructor.
2591 for (auto *OldParam : TL.getParams()) {
2592 ParmVarDecl *NewParam =
2593 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2594 if (NestedPattern && NewParam)
2595 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2596 MaterializedTypedefs);
2597 if (!NewParam)
2598 return QualType();
2599 ParamTypes.push_back(NewParam->getType());
2600 Params.push_back(NewParam);
2601 }
2602
2603 // -- The return type is the class template specialization designated by
2604 // the template-name and template arguments corresponding to the
2605 // template parameters obtained from the class template.
2606 //
2607 // We use the injected-class-name type of the primary template instead.
2608 // This has the convenient property that it is different from any type that
2609 // the user can write in a deduction-guide (because they cannot enter the
2610 // context of the template), so implicit deduction guides can never collide
2611 // with explicit ones.
2612 QualType ReturnType = DeducedType;
2613 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2614
2615 // Resolving a wording defect, we also inherit the variadicness of the
2616 // constructor.
2618 EPI.Variadic = T->isVariadic();
2619 EPI.HasTrailingReturn = true;
2620
2621 QualType Result = SemaRef.BuildFunctionType(
2622 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2623 if (Result.isNull())
2624 return QualType();
2625
2626 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2628 NewTL.setLParenLoc(TL.getLParenLoc());
2629 NewTL.setRParenLoc(TL.getRParenLoc());
2632 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2633 NewTL.setParam(I, Params[I]);
2634
2635 return Result;
2636 }
2637
2638 ParmVarDecl *transformFunctionTypeParam(
2640 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2641 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2642 TypeSourceInfo *NewDI;
2643 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2644 // Expand out the one and only element in each inner pack.
2645 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2646 NewDI =
2647 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2648 OldParam->getLocation(), OldParam->getDeclName());
2649 if (!NewDI) return nullptr;
2650 NewDI =
2651 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2652 PackTL.getTypePtr()->getNumExpansions());
2653 } else
2654 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2655 OldParam->getDeclName());
2656 if (!NewDI)
2657 return nullptr;
2658
2659 // Extract the type. This (for instance) replaces references to typedef
2660 // members of the current instantiations with the definitions of those
2661 // typedefs, avoiding triggering instantiation of the deduced type during
2662 // deduction.
2663 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2664 .transform(NewDI);
2665
2666 // Resolving a wording defect, we also inherit default arguments from the
2667 // constructor.
2668 ExprResult NewDefArg;
2669 if (OldParam->hasDefaultArg()) {
2670 // We don't care what the value is (we won't use it); just create a
2671 // placeholder to indicate there is a default argument.
2672 QualType ParamTy = NewDI->getType();
2673 NewDefArg = new (SemaRef.Context)
2675 ParamTy.getNonLValueExprType(SemaRef.Context),
2676 ParamTy->isLValueReferenceType() ? VK_LValue
2677 : ParamTy->isRValueReferenceType() ? VK_XValue
2678 : VK_PRValue);
2679 }
2680 // Handle arrays and functions decay.
2681 auto NewType = NewDI->getType();
2682 if (NewType->isArrayType() || NewType->isFunctionType())
2683 NewType = SemaRef.Context.getDecayedType(NewType);
2684
2685 ParmVarDecl *NewParam = ParmVarDecl::Create(
2686 SemaRef.Context, DC, OldParam->getInnerLocStart(),
2687 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2688 OldParam->getStorageClass(), NewDefArg.get());
2689 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2690 OldParam->getFunctionScopeIndex());
2691 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2692 return NewParam;
2693 }
2694};
2695
2696// Find all template parameters that appear in the given DeducedArgs.
2697// Return the indices of the template parameters in the TemplateParams.
2698SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
2699 ArrayRef<NamedDecl *> TemplateParams,
2700 ArrayRef<TemplateArgument> DeducedArgs) {
2701 struct TemplateParamsReferencedFinder
2702 : public RecursiveASTVisitor<TemplateParamsReferencedFinder> {
2703 llvm::DenseSet<NamedDecl *> TemplateParams;
2704 llvm::DenseSet<const NamedDecl *> ReferencedTemplateParams;
2705
2706 TemplateParamsReferencedFinder(ArrayRef<NamedDecl *> TemplateParams)
2707 : TemplateParams(TemplateParams.begin(), TemplateParams.end()) {}
2708
2709 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) {
2710 MarkAppeared(TTP->getDecl());
2711 return true;
2712 }
2713 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
2714 MarkAppeared(DRE->getFoundDecl());
2715 return true;
2716 }
2717
2718 bool TraverseTemplateName(TemplateName Template) {
2719 if (auto *TD = Template.getAsTemplateDecl())
2720 MarkAppeared(TD);
2722 }
2723
2724 void MarkAppeared(NamedDecl *ND) {
2725 if (TemplateParams.contains(ND))
2726 ReferencedTemplateParams.insert(ND);
2727 }
2728 };
2729 TemplateParamsReferencedFinder Finder(TemplateParams);
2730 Finder.TraverseTemplateArguments(DeducedArgs);
2731
2732 SmallVector<unsigned> Results;
2733 for (unsigned Index = 0; Index < TemplateParams.size(); ++Index) {
2734 if (Finder.ReferencedTemplateParams.contains(TemplateParams[Index]))
2735 Results.push_back(Index);
2736 }
2737 return Results;
2738}
2739
2740bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
2741 // Check whether we've already declared deduction guides for this template.
2742 // FIXME: Consider storing a flag on the template to indicate this.
2743 assert(Name.getNameKind() ==
2745 "name must be a deduction guide name");
2746 auto Existing = DC->lookup(Name);
2747 for (auto *D : Existing)
2748 if (D->isImplicit())
2749 return true;
2750 return false;
2751}
2752
2753NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
2756 unsigned NewIndex) {
2757 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
2758 return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
2759 NewIndex);
2760 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2761 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
2762 TTP->getDepth());
2763 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
2764 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
2765 NTTP->getDepth());
2766 llvm_unreachable("Unhandled template parameter types");
2767}
2768
2769Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
2770 llvm::ArrayRef<TemplateArgument> TransformedArgs) {
2772 if (!RC)
2773 return nullptr;
2776 Args.addOuterTemplateArguments(TransformedArgs);
2777 ExprResult E = SemaRef.SubstExpr(RC, Args);
2778 if (E.isInvalid())
2779 return nullptr;
2780 return E.getAs<Expr>();
2781}
2782
2783std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
2784getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
2785 // Unwrap the sugared ElaboratedType.
2786 auto RhsType = AliasTemplate->getTemplatedDecl()
2787 ->getUnderlyingType()
2788 .getSingleStepDesugaredType(SemaRef.Context);
2789 TemplateDecl *Template = nullptr;
2790 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
2791 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
2792 // Cases where the RHS of the alias is dependent. e.g.
2793 // template<typename T>
2794 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
2795 Template = TST->getTemplateName().getAsTemplateDecl();
2796 AliasRhsTemplateArgs = TST->template_arguments();
2797 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
2798 // Cases where template arguments in the RHS of the alias are not
2799 // dependent. e.g.
2800 // using AliasFoo = Foo<bool>;
2801 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
2802 RT->getAsCXXRecordDecl())) {
2803 Template = CTSD->getSpecializedTemplate();
2804 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
2805 }
2806 } else {
2807 assert(false && "unhandled RHS type of the alias");
2808 }
2809 return {Template, AliasRhsTemplateArgs};
2810}
2811
2812// Build deduction guides for a type alias template.
2813void DeclareImplicitDeductionGuidesForTypeAlias(
2815 if (AliasTemplate->isInvalidDecl())
2816 return;
2817 auto &Context = SemaRef.Context;
2818 // FIXME: if there is an explicit deduction guide after the first use of the
2819 // type alias usage, we will not cover this explicit deduction guide. fix this
2820 // case.
2821 if (hasDeclaredDeductionGuides(
2823 AliasTemplate->getDeclContext()))
2824 return;
2825 auto [Template, AliasRhsTemplateArgs] =
2826 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
2827 if (!Template)
2828 return;
2829 DeclarationNameInfo NameInfo(
2830 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
2831 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
2832 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
2833 Guides.suppressDiagnostics();
2834
2835 for (auto *G : Guides) {
2836 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
2837 if (!F)
2838 continue;
2839 // The **aggregate** deduction guides are handled in a different code path
2840 // (DeclareImplicitDeductionGuideFromInitList), which involves the tricky
2841 // cache.
2842 if (cast<CXXDeductionGuideDecl>(F->getTemplatedDecl())
2843 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
2844 continue;
2845
2846 auto RType = F->getTemplatedDecl()->getReturnType();
2847 // The (trailing) return type of the deduction guide.
2848 const TemplateSpecializationType *FReturnType =
2850 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
2851 // implicitly-generated deduction guide.
2852 FReturnType = InjectedCNT->getInjectedTST();
2853 else if (const auto *ET = RType->getAs<ElaboratedType>())
2854 // explicit deduction guide.
2855 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
2856 assert(FReturnType && "expected to see a return type");
2857 // Deduce template arguments of the deduction guide f from the RHS of
2858 // the alias.
2859 //
2860 // C++ [over.match.class.deduct]p3: ...For each function or function
2861 // template f in the guides of the template named by the
2862 // simple-template-id of the defining-type-id, the template arguments
2863 // of the return type of f are deduced from the defining-type-id of A
2864 // according to the process in [temp.deduct.type] with the exception
2865 // that deduction does not fail if not all template arguments are
2866 // deduced.
2867 //
2868 //
2869 // template<typename X, typename Y>
2870 // f(X, Y) -> f<Y, X>;
2871 //
2872 // template<typename U>
2873 // using alias = f<int, U>;
2874 //
2875 // The RHS of alias is f<int, U>, we deduced the template arguments of
2876 // the return type of the deduction guide from it: Y->int, X->U
2877 sema::TemplateDeductionInfo TDeduceInfo(Loc);
2878 // Must initialize n elements, this is required by DeduceTemplateArguments.
2880 F->getTemplateParameters()->size());
2881
2882 // FIXME: DeduceTemplateArguments stops immediately at the first
2883 // non-deducible template argument. However, this doesn't seem to casue
2884 // issues for practice cases, we probably need to extend it to continue
2885 // performing deduction for rest of arguments to align with the C++
2886 // standard.
2888 F->getTemplateParameters(), FReturnType->template_arguments(),
2889 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
2890 /*NumberOfArgumentsMustMatch=*/false);
2891
2893 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
2894 // !!NOTE: DeduceResults respects the sequence of template parameters of
2895 // the deduction guide f.
2896 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2897 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
2898 DeducedArgs.push_back(D);
2899 else
2900 NonDeducedTemplateParamsInFIndex.push_back(Index);
2901 }
2902 auto DeducedAliasTemplateParams =
2903 TemplateParamsReferencedInTemplateArgumentList(
2904 AliasTemplate->getTemplateParameters()->asArray(), DeducedArgs);
2905 // All template arguments null by default.
2906 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
2907 F->getTemplateParameters()->size());
2908
2909 Sema::InstantiatingTemplate BuildingDeductionGuides(
2910 SemaRef, AliasTemplate->getLocation(), F,
2912 if (BuildingDeductionGuides.isInvalid())
2913 return;
2915
2916 // Create a template parameter list for the synthesized deduction guide f'.
2917 //
2918 // C++ [over.match.class.deduct]p3.2:
2919 // If f is a function template, f' is a function template whose template
2920 // parameter list consists of all the template parameters of A
2921 // (including their default template arguments) that appear in the above
2922 // deductions or (recursively) in their default template arguments
2923 SmallVector<NamedDecl *> FPrimeTemplateParams;
2924 // Store template arguments that refer to the newly-created template
2925 // parameters, used for building `TemplateArgsForBuildingFPrime`.
2926 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
2927 AliasTemplate->getTemplateParameters()->size());
2928
2929 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
2930 auto *TP = AliasTemplate->getTemplateParameters()->getParam(
2931 AliasTemplateParamIdx);
2932 // Rebuild any internal references to earlier parameters and reindex as
2933 // we go.
2936 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
2937 NamedDecl *NewParam = transformTemplateParameter(
2938 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
2939 /*NewIndex*/ FPrimeTemplateParams.size());
2940 FPrimeTemplateParams.push_back(NewParam);
2941
2942 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
2943 Context.getInjectedTemplateArg(NewParam));
2944 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
2945 }
2946 // ...followed by the template parameters of f that were not deduced
2947 // (including their default template arguments)
2948 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
2949 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
2952 // We take a shortcut here, it is ok to reuse the
2953 // TemplateArgsForBuildingFPrime.
2954 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
2955 NamedDecl *NewParam = transformTemplateParameter(
2956 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size());
2957 FPrimeTemplateParams.push_back(NewParam);
2958
2959 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
2960 "The argument must be null before setting");
2961 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
2963 Context.getInjectedTemplateArg(NewParam));
2964 }
2965
2966 // To form a deduction guide f' from f, we leverage clang's instantiation
2967 // mechanism, we construct a template argument list where the template
2968 // arguments refer to the newly-created template parameters of f', and
2969 // then apply instantiation on this template argument list to instantiate
2970 // f, this ensures all template parameter occurrences are updated
2971 // correctly.
2972 //
2973 // The template argument list is formed from the `DeducedArgs`, two parts:
2974 // 1) appeared template parameters of alias: transfrom the deduced
2975 // template argument;
2976 // 2) non-deduced template parameters of f: rebuild a
2977 // template argument;
2978 //
2979 // 2) has been built already (when rebuilding the new template
2980 // parameters), we now perform 1).
2983 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
2984 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2985 const auto &D = DeduceResults[Index];
2986 if (D.isNull()) {
2987 // 2): Non-deduced template parameter has been built already.
2988 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
2989 "template arguments for non-deduced template parameters should "
2990 "be been set!");
2991 continue;
2992 }
2994 D, QualType(), SourceLocation{});
2995 TemplateArgumentLoc Output;
2996 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
2997 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
2998 "InstantiatedArgs must be null before setting");
2999 TemplateArgsForBuildingFPrime[Index] = (Output.getArgument());
3000 }
3001 }
3002
3003 auto *TemplateArgListForBuildingFPrime = TemplateArgumentList::CreateCopy(
3004 Context, TemplateArgsForBuildingFPrime);
3005 // Form the f' by substituting the template arguments into f.
3006 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
3007 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
3009 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
3010 // Substitute new template parameters into requires-clause if present.
3011 Expr *RequiresClause =
3012 transformRequireClause(SemaRef, F, TemplateArgsForBuildingFPrime);
3013 // FIXME: implement the is_deducible constraint per C++
3014 // [over.match.class.deduct]p3.3:
3015 // ... and a constraint that is satisfied if and only if the arguments
3016 // of A are deducible (see below) from the return type.
3017 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
3018 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
3019 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
3020 FPrimeTemplateParams,
3021 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
3022 /*RequiresClause=*/RequiresClause);
3023
3024 buildDeductionGuide(SemaRef, AliasTemplate, FPrimeTemplateParamList,
3025 GG->getCorrespondingConstructor(),
3026 GG->getExplicitSpecifier(), GG->getTypeSourceInfo(),
3027 AliasTemplate->getBeginLoc(),
3028 AliasTemplate->getLocation(),
3029 AliasTemplate->getEndLoc(), F->isImplicit());
3030 }
3031 }
3032}
3033
3034// Build an aggregate deduction guide for a type alias template.
3035FunctionTemplateDecl *DeclareAggregateDeductionGuideForTypeAlias(
3037 MutableArrayRef<QualType> ParamTypes, SourceLocation Loc) {
3038 TemplateDecl *RHSTemplate =
3039 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
3040 if (!RHSTemplate)
3041 return nullptr;
3042 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
3043 RHSTemplate, ParamTypes, Loc);
3044 if (!RHSDeductionGuide)
3045 return nullptr;
3046
3048 Sema::InstantiatingTemplate BuildingDeductionGuides(
3049 SemaRef, AliasTemplate->getLocation(), RHSDeductionGuide,
3051 if (BuildingDeductionGuides.isInvalid())
3052 return nullptr;
3053
3054 // Build a new template parameter list for the synthesized aggregate deduction
3055 // guide by transforming the one from RHSDeductionGuide.
3056 SmallVector<NamedDecl *> TransformedTemplateParams;
3057 // Template args that refer to the rebuilt template parameters.
3058 // All template arguments must be initialized in advance.
3059 SmallVector<TemplateArgument> TransformedTemplateArgs(
3060 RHSDeductionGuide->getTemplateParameters()->size());
3061 for (auto *TP : *RHSDeductionGuide->getTemplateParameters()) {
3062 // Rebuild any internal references to earlier parameters and reindex as
3063 // we go.
3066 Args.addOuterTemplateArguments(TransformedTemplateArgs);
3067 NamedDecl *NewParam = transformTemplateParameter(
3068 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
3069 /*NewIndex=*/TransformedTemplateParams.size());
3070
3071 TransformedTemplateArgs[TransformedTemplateParams.size()] =
3073 SemaRef.Context.getInjectedTemplateArg(NewParam));
3074 TransformedTemplateParams.push_back(NewParam);
3075 }
3076 // FIXME: implement the is_deducible constraint per C++
3077 // [over.match.class.deduct]p3.3.
3078 Expr *TransformedRequiresClause = transformRequireClause(
3079 SemaRef, RHSDeductionGuide, TransformedTemplateArgs);
3080 auto *TransformedTemplateParameterList = TemplateParameterList::Create(
3081 SemaRef.Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
3082 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
3083 TransformedTemplateParams,
3084 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
3085 TransformedRequiresClause);
3086 auto *TransformedTemplateArgList = TemplateArgumentList::CreateCopy(
3087 SemaRef.Context, TransformedTemplateArgs);
3088
3089 if (auto *TransformedDeductionGuide = SemaRef.InstantiateFunctionDeclaration(
3090 RHSDeductionGuide, TransformedTemplateArgList,
3091 AliasTemplate->getLocation(),
3093 auto *GD =
3094 llvm::dyn_cast<clang::CXXDeductionGuideDecl>(TransformedDeductionGuide);
3095 FunctionTemplateDecl *Result = buildDeductionGuide(
3096 SemaRef, AliasTemplate, TransformedTemplateParameterList,
3097 GD->getCorrespondingConstructor(), GD->getExplicitSpecifier(),
3098 GD->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
3099 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
3100 GD->isImplicit());
3101 cast<CXXDeductionGuideDecl>(Result->getTemplatedDecl())
3102 ->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3103 return Result;
3104 }
3105 return nullptr;
3106}
3107
3108} // namespace
3109
3111 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
3112 SourceLocation Loc) {
3113 llvm::FoldingSetNodeID ID;
3114 ID.AddPointer(Template);
3115 for (auto &T : ParamTypes)
3116 T.getCanonicalType().Profile(ID);
3117 unsigned Hash = ID.ComputeHash();
3118
3119 auto Found = AggregateDeductionCandidates.find(Hash);
3120 if (Found != AggregateDeductionCandidates.end()) {
3121 CXXDeductionGuideDecl *GD = Found->getSecond();
3122 return GD->getDescribedFunctionTemplate();
3123 }
3124
3125 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
3126 if (auto *FTD = DeclareAggregateDeductionGuideForTypeAlias(
3127 *this, AliasTemplate, ParamTypes, Loc)) {
3128 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
3129 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3131 return FTD;
3132 }
3133 }
3134
3135 if (CXXRecordDecl *DefRecord =
3136 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
3137 if (TemplateDecl *DescribedTemplate =
3138 DefRecord->getDescribedClassTemplate())
3139 Template = DescribedTemplate;
3140 }
3141
3142 DeclContext *DC = Template->getDeclContext();
3143 if (DC->isDependentContext())
3144 return nullptr;
3145
3146 ConvertConstructorToDeductionGuideTransform Transform(
3147 *this, cast<ClassTemplateDecl>(Template));
3148 if (!isCompleteType(Loc, Transform.DeducedType))
3149 return nullptr;
3150
3151 // In case we were expanding a pack when we attempted to declare deduction
3152 // guides, turn off pack expansion for everything we're about to do.
3153 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
3154 /*NewSubstitutionIndex=*/-1);
3155 // Create a template instantiation record to track the "instantiation" of
3156 // constructors into deduction guides.
3157 InstantiatingTemplate BuildingDeductionGuides(
3158 *this, Loc, Template,
3160 if (BuildingDeductionGuides.isInvalid())
3161 return nullptr;
3162
3163 ClassTemplateDecl *Pattern =
3164 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3165 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3166
3167 auto *FTD = cast<FunctionTemplateDecl>(
3168 Transform.buildSimpleDeductionGuide(ParamTypes));
3169 SavedContext.pop();
3170 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
3171 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3173 return FTD;
3174}
3175
3177 SourceLocation Loc) {
3178 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
3179 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
3180 return;
3181 }
3182 if (CXXRecordDecl *DefRecord =
3183 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
3184 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
3185 Template = DescribedTemplate;
3186 }
3187
3188 DeclContext *DC = Template->getDeclContext();
3189 if (DC->isDependentContext())
3190 return;
3191
3192 ConvertConstructorToDeductionGuideTransform Transform(
3193 *this, cast<ClassTemplateDecl>(Template));
3194 if (!isCompleteType(Loc, Transform.DeducedType))
3195 return;
3196
3197 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
3198 return;
3199
3200 // In case we were expanding a pack when we attempted to declare deduction
3201 // guides, turn off pack expansion for everything we're about to do.
3202 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3203 // Create a template instantiation record to track the "instantiation" of
3204 // constructors into deduction guides.
3205 InstantiatingTemplate BuildingDeductionGuides(
3206 *this, Loc, Template,
3208 if (BuildingDeductionGuides.isInvalid())
3209 return;
3210
3211 // Convert declared constructors into deduction guide templates.
3212 // FIXME: Skip constructors for which deduction must necessarily fail (those
3213 // for which some class template parameter without a default argument never
3214 // appears in a deduced context).
3215 ClassTemplateDecl *Pattern =
3216 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3217 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3218 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
3219 bool AddedAny = false;
3220 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
3221 D = D->getUnderlyingDecl();
3222 if (D->isInvalidDecl() || D->isImplicit())
3223 continue;
3224
3225 D = cast<NamedDecl>(D->getCanonicalDecl());
3226
3227 // Within C++20 modules, we may have multiple same constructors in
3228 // multiple same RecordDecls. And it doesn't make sense to create
3229 // duplicated deduction guides for the duplicated constructors.
3230 if (ProcessedCtors.count(D))
3231 continue;
3232
3233 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
3234 auto *CD =
3235 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
3236 // Class-scope explicit specializations (MS extension) do not result in
3237 // deduction guides.
3238 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
3239 continue;
3240
3241 // Cannot make a deduction guide when unparsed arguments are present.
3242 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
3243 return !P || P->hasUnparsedDefaultArg();
3244 }))
3245 continue;
3246
3247 ProcessedCtors.insert(D);
3248 Transform.transformConstructor(FTD, CD);
3249 AddedAny = true;
3250 }
3251
3252 // C++17 [over.match.class.deduct]
3253 // -- If C is not defined or does not declare any constructors, an
3254 // additional function template derived as above from a hypothetical
3255 // constructor C().
3256 if (!AddedAny)
3257 Transform.buildSimpleDeductionGuide(std::nullopt);
3258
3259 // -- An additional function template derived as above from a hypothetical
3260 // constructor C(C), called the copy deduction candidate.
3261 cast<CXXDeductionGuideDecl>(
3262 cast<FunctionTemplateDecl>(
3263 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
3264 ->getTemplatedDecl())
3265 ->setDeductionCandidateKind(DeductionCandidate::Copy);
3266
3267 SavedContext.pop();
3268}
3269
3270/// Diagnose the presence of a default template argument on a
3271/// template parameter, which is ill-formed in certain contexts.
3272///
3273/// \returns true if the default template argument should be dropped.
3276 SourceLocation ParamLoc,
3277 SourceRange DefArgRange) {
3278 switch (TPC) {
3282 return false;
3283
3286 // C++ [temp.param]p9:
3287 // A default template-argument shall not be specified in a
3288 // function template declaration or a function template
3289 // definition [...]
3290 // If a friend function template declaration specifies a default
3291 // template-argument, that declaration shall be a definition and shall be
3292 // the only declaration of the function template in the translation unit.
3293 // (C++98/03 doesn't have this wording; see DR226).
3294 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
3295 diag::warn_cxx98_compat_template_parameter_default_in_function_template
3296 : diag::ext_template_parameter_default_in_function_template)
3297 << DefArgRange;
3298 return false;
3299
3301 // C++0x [temp.param]p9:
3302 // A default template-argument shall not be specified in the
3303 // template-parameter-lists of the definition of a member of a
3304 // class template that appears outside of the member's class.
3305 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
3306 << DefArgRange;
3307 return true;
3308
3311 // C++ [temp.param]p9:
3312 // A default template-argument shall not be specified in a
3313 // friend template declaration.
3314 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
3315 << DefArgRange;
3316 return true;
3317
3318 // FIXME: C++0x [temp.param]p9 allows default template-arguments
3319 // for friend function templates if there is only a single
3320 // declaration (and it is a definition). Strange!
3321 }
3322
3323 llvm_unreachable("Invalid TemplateParamListContext!");
3324}
3325
3326/// Check for unexpanded parameter packs within the template parameters
3327/// of a template template parameter, recursively.
3330 // A template template parameter which is a parameter pack is also a pack
3331 // expansion.
3332 if (TTP->isParameterPack())
3333 return false;
3334
3336 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3337 NamedDecl *P = Params->getParam(I);
3338 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
3339 if (!TTP->isParameterPack())
3340 if (const TypeConstraint *TC = TTP->getTypeConstraint())
3341 if (TC->hasExplicitTemplateArgs())
3342 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3345 return true;
3346 continue;
3347 }
3348
3349 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
3350 if (!NTTP->isParameterPack() &&
3351 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
3352 NTTP->getTypeSourceInfo(),
3354 return true;
3355
3356 continue;
3357 }
3358
3359 if (TemplateTemplateParmDecl *InnerTTP
3360 = dyn_cast<TemplateTemplateParmDecl>(P))
3361 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
3362 return true;
3363 }
3364
3365 return false;
3366}
3367
3368/// Checks the validity of a template parameter list, possibly
3369/// considering the template parameter list from a previous
3370/// declaration.
3371///
3372/// If an "old" template parameter list is provided, it must be
3373/// equivalent (per TemplateParameterListsAreEqual) to the "new"
3374/// template parameter list.
3375///
3376/// \param NewParams Template parameter list for a new template
3377/// declaration. This template parameter list will be updated with any
3378/// default arguments that are carried through from the previous
3379/// template parameter list.
3380///
3381/// \param OldParams If provided, template parameter list from a
3382/// previous declaration of the same template. Default template
3383/// arguments will be merged from the old template parameter list to
3384/// the new template parameter list.
3385///
3386/// \param TPC Describes the context in which we are checking the given
3387/// template parameter list.
3388///
3389/// \param SkipBody If we might have already made a prior merged definition
3390/// of this template visible, the corresponding body-skipping information.
3391/// Default argument redefinition is not an error when skipping such a body,
3392/// because (under the ODR) we can assume the default arguments are the same
3393/// as the prior merged definition.
3394///
3395/// \returns true if an error occurred, false otherwise.
3397 TemplateParameterList *OldParams,
3399 SkipBodyInfo *SkipBody) {
3400 bool Invalid = false;
3401
3402 // C++ [temp.param]p10:
3403 // The set of default template-arguments available for use with a
3404 // template declaration or definition is obtained by merging the
3405 // default arguments from the definition (if in scope) and all
3406 // declarations in scope in the same way default function
3407 // arguments are (8.3.6).
3408 bool SawDefaultArgument = false;
3409 SourceLocation PreviousDefaultArgLoc;
3410
3411 // Dummy initialization to avoid warnings.
3412 TemplateParameterList::iterator OldParam = NewParams->end();
3413 if (OldParams)
3414 OldParam = OldParams->begin();
3415
3416 bool RemoveDefaultArguments = false;
3417 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3418 NewParamEnd = NewParams->end();
3419 NewParam != NewParamEnd; ++NewParam) {
3420 // Whether we've seen a duplicate default argument in the same translation
3421 // unit.
3422 bool RedundantDefaultArg = false;
3423 // Whether we've found inconsis inconsitent default arguments in different
3424 // translation unit.
3425 bool InconsistentDefaultArg = false;
3426 // The name of the module which contains the inconsistent default argument.
3427 std::string PrevModuleName;
3428
3429 SourceLocation OldDefaultLoc;
3430 SourceLocation NewDefaultLoc;
3431
3432 // Variable used to diagnose missing default arguments
3433 bool MissingDefaultArg = false;
3434
3435 // Variable used to diagnose non-final parameter packs
3436 bool SawParameterPack = false;
3437
3438 if (TemplateTypeParmDecl *NewTypeParm
3439 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
3440 // Check the presence of a default argument here.
3441 if (NewTypeParm->hasDefaultArgument() &&
3443 NewTypeParm->getLocation(),
3444 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
3445 .getSourceRange()))
3446 NewTypeParm->removeDefaultArgument();
3447
3448 // Merge default arguments for template type parameters.
3449 TemplateTypeParmDecl *OldTypeParm
3450 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
3451 if (NewTypeParm->isParameterPack()) {
3452 assert(!NewTypeParm->hasDefaultArgument() &&
3453 "Parameter packs can't have a default argument!");
3454 SawParameterPack = true;
3455 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
3456 NewTypeParm->hasDefaultArgument() &&
3457 (!SkipBody || !SkipBody->ShouldSkip)) {
3458 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
3459 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
3460 SawDefaultArgument = true;
3461
3462 if (!OldTypeParm->getOwningModule())
3463 RedundantDefaultArg = true;
3464 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
3465 NewTypeParm)) {
3466 InconsistentDefaultArg = true;
3467 PrevModuleName =
3469 }
3470 PreviousDefaultArgLoc = NewDefaultLoc;
3471 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
3472 // Merge the default argument from the old declaration to the
3473 // new declaration.
3474 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
3475 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
3476 } else if (NewTypeParm->hasDefaultArgument()) {
3477 SawDefaultArgument = true;
3478 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
3479 } else if (SawDefaultArgument)
3480 MissingDefaultArg = true;
3481 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3482 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
3483 // Check for unexpanded parameter packs.
3484 if (!NewNonTypeParm->isParameterPack() &&
3485 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3486 NewNonTypeParm->getTypeSourceInfo(),
3488 Invalid = true;
3489 continue;
3490 }
3491
3492 // Check the presence of a default argument here.
3493 if (NewNonTypeParm->hasDefaultArgument() &&
3495 NewNonTypeParm->getLocation(),
3496 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3497 NewNonTypeParm->removeDefaultArgument();
3498 }
3499
3500 // Merge default arguments for non-type template parameters
3501 NonTypeTemplateParmDecl *OldNonTypeParm
3502 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3503 if (NewNonTypeParm->isParameterPack()) {
3504 assert(!NewNonTypeParm->hasDefaultArgument() &&
3505 "Parameter packs can't have a default argument!");
3506 if (!NewNonTypeParm->isPackExpansion())
3507 SawParameterPack = true;
3508 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3509 NewNonTypeParm->hasDefaultArgument() &&
3510 (!SkipBody || !SkipBody->ShouldSkip)) {
3511 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3512 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3513 SawDefaultArgument = true;
3514 if (!OldNonTypeParm->getOwningModule())
3515 RedundantDefaultArg = true;
3516 else if (!getASTContext().isSameDefaultTemplateArgument(
3517 OldNonTypeParm, NewNonTypeParm)) {
3518 InconsistentDefaultArg = true;
3519 PrevModuleName =
3520 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3521 }
3522 PreviousDefaultArgLoc = NewDefaultLoc;
3523 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3524 // Merge the default argument from the old declaration to the
3525 // new declaration.
3526 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3527 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3528 } else if (NewNonTypeParm->hasDefaultArgument()) {
3529 SawDefaultArgument = true;
3530 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3531 } else if (SawDefaultArgument)
3532 MissingDefaultArg = true;
3533 } else {
3534 TemplateTemplateParmDecl *NewTemplateParm
3535 = cast<TemplateTemplateParmDecl>(*NewParam);
3536
3537 // Check for unexpanded parameter packs, recursively.
3538 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3539 Invalid = true;
3540 continue;
3541 }
3542
3543 // Check the presence of a default argument here.
3544 if (NewTemplateParm->hasDefaultArgument() &&
3546 NewTemplateParm->getLocation(),
3547 NewTemplateParm->getDefaultArgument().getSourceRange()))
3548 NewTemplateParm->removeDefaultArgument();
3549
3550 // Merge default arguments for template template parameters
3551 TemplateTemplateParmDecl *OldTemplateParm
3552 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3553 if (NewTemplateParm->isParameterPack()) {
3554 assert(!NewTemplateParm->hasDefaultArgument() &&
3555 "Parameter packs can't have a default argument!");
3556 if (!NewTemplateParm->isPackExpansion())
3557 SawParameterPack = true;
3558 } else if (OldTemplateParm &&
3559 hasVisibleDefaultArgument(OldTemplateParm) &&
3560 NewTemplateParm->hasDefaultArgument() &&
3561 (!SkipBody || !SkipBody->ShouldSkip)) {
3562 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3563 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3564 SawDefaultArgument = true;
3565 if (!OldTemplateParm->getOwningModule())
3566 RedundantDefaultArg = true;
3567 else if (!getASTContext().isSameDefaultTemplateArgument(
3568 OldTemplateParm, NewTemplateParm)) {
3569 InconsistentDefaultArg = true;
3570 PrevModuleName =
3571 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3572 }
3573 PreviousDefaultArgLoc = NewDefaultLoc;
3574 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3575 // Merge the default argument from the old declaration to the
3576 // new declaration.
3577 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3578 PreviousDefaultArgLoc
3579 = OldTemplateParm->getDefaultArgument().getLocation();
3580 } else if (NewTemplateParm->hasDefaultArgument()) {
3581 SawDefaultArgument = true;
3582 PreviousDefaultArgLoc
3583 = NewTemplateParm->getDefaultArgument().getLocation();
3584 } else if (SawDefaultArgument)
3585 MissingDefaultArg = true;
3586 }
3587
3588 // C++11 [temp.param]p11:
3589 // If a template parameter of a primary class template or alias template
3590 // is a template parameter pack, it shall be the last template parameter.
3591 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3592 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3593 TPC == TPC_TypeAliasTemplate)) {
3594 Diag((*NewParam)->getLocation(),
3595 diag::err_template_param_pack_must_be_last_template_parameter);
3596 Invalid = true;
3597 }
3598
3599 // [basic.def.odr]/13:
3600 // There can be more than one definition of a
3601 // ...
3602 // default template argument
3603 // ...
3604 // in a program provided that each definition appears in a different
3605 // translation unit and the definitions satisfy the [same-meaning
3606 // criteria of the ODR].
3607 //
3608 // Simply, the design of modules allows the definition of template default
3609 // argument to be repeated across translation unit. Note that the ODR is
3610 // checked elsewhere. But it is still not allowed to repeat template default
3611 // argument in the same translation unit.
3612 if (RedundantDefaultArg) {
3613 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3614 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3615 Invalid = true;
3616 } else if (InconsistentDefaultArg) {
3617 // We could only diagnose about the case that the OldParam is imported.
3618 // The case NewParam is imported should be handled in ASTReader.
3619 Diag(NewDefaultLoc,
3620 diag::err_template_param_default_arg_inconsistent_redefinition);
3621 Diag(OldDefaultLoc,
3622 diag::note_template_param_prev_default_arg_in_other_module)
3623 << PrevModuleName;
3624 Invalid = true;
3625 } else if (MissingDefaultArg &&
3626 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
3627 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
3628 // C++ 23[temp.param]p14:
3629 // If a template-parameter of a class template, variable template, or
3630 // alias template has a default template argument, each subsequent
3631 // template-parameter shall either have a default template argument
3632 // supplied or be a template parameter pack.
3633 Diag((*NewParam)->getLocation(),
3634 diag::err_template_param_default_arg_missing);
3635 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3636 Invalid = true;
3637 RemoveDefaultArguments = true;
3638 }
3639
3640 // If we have an old template parameter list that we're merging
3641 // in, move on to the next parameter.
3642 if (OldParams)
3643 ++OldParam;
3644 }
3645
3646 // We were missing some default arguments at the end of the list, so remove
3647 // all of the default arguments.
3648 if (RemoveDefaultArguments) {
3649 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3650 NewParamEnd = NewParams->end();
3651 NewParam != NewParamEnd; ++NewParam) {
3652 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3653 TTP->removeDefaultArgument();
3654 else if (NonTypeTemplateParmDecl *NTTP
3655 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3656 NTTP->removeDefaultArgument();
3657 else
3658 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3659 }
3660 }
3661
3662 return Invalid;
3663}
3664
3665namespace {
3666
3667/// A class which looks for a use of a certain level of template
3668/// parameter.
3669struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3671
3672 unsigned Depth;
3673
3674 // Whether we're looking for a use of a template parameter that makes the
3675 // overall construct type-dependent / a dependent type. This is strictly
3676 // best-effort for now; we may fail to match at all for a dependent type
3677 // in some cases if this is set.
3678 bool IgnoreNonTypeDependent;
3679
3680 bool Match;
3681 SourceLocation MatchLoc;
3682
3683 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3684 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3685 Match(false) {}
3686
3687 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3688 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3689 NamedDecl *ND = Params->getParam(0);
3690 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3691 Depth = PD->getDepth();
3692 } else if (NonTypeTemplateParmDecl *PD =
3693 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3694 Depth = PD->getDepth();
3695 } else {
3696 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3697 }
3698 }
3699
3700 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3701 if (ParmDepth >= Depth) {
3702 Match = true;
3703 MatchLoc = Loc;
3704 return true;
3705 }
3706 return false;
3707 }
3708
3709 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3710 // Prune out non-type-dependent expressions if requested. This can
3711 // sometimes result in us failing to find a template parameter reference
3712 // (if a value-dependent expression creates a dependent type), but this
3713 // mode is best-effort only.
3714 if (auto *E = dyn_cast_or_null<Expr>(S))
3715 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3716 return true;
3717 return super::TraverseStmt(S, Q);
3718 }
3719
3720 bool TraverseTypeLoc(TypeLoc TL) {
3721 if (IgnoreNonTypeDependent && !TL.isNull() &&
3722 !TL.getType()->isDependentType())
3723 return true;
3724 return super::TraverseTypeLoc(TL);
3725 }
3726
3727 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3728 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3729 }
3730
3731 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3732 // For a best-effort search, keep looking until we find a location.
3733 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3734 }
3735
3736 bool TraverseTemplateName(TemplateName N) {
3737 if (TemplateTemplateParmDecl *PD =
3738 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3739 if (Matches(PD->getDepth()))
3740 return false;
3741 return super::TraverseTemplateName(N);
3742 }
3743
3744 bool VisitDeclRefExpr(DeclRefExpr *E) {
3745 if (NonTypeTemplateParmDecl *PD =
3746 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3747 if (Matches(PD->getDepth(), E->getExprLoc()))
3748 return false;
3749 return super::VisitDeclRefExpr(E);
3750 }
3751
3752 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3753 return TraverseType(T->getReplacementType());
3754 }
3755
3756 bool
3757 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3758 return TraverseTemplateArgument(T->getArgumentPack());
3759 }
3760
3761 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3762 return TraverseType(T->getInjectedSpecializationType());
3763 }
3764};
3765} // end anonymous namespace
3766
3767/// Determines whether a given type depends on the given parameter
3768/// list.
3769static bool
3771 if (!Params->size())
3772 return false;
3773
3774 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3775 Checker.TraverseType(T);
3776 return Checker.Match;
3777}
3778
3779// Find the source range corresponding to the named type in the given
3780// nested-name-specifier, if any.
3782 QualType T,
3783 const CXXScopeSpec &SS) {
3785 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3786 if (const Type *CurType = NNS->getAsType()) {
3787 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3788 return NNSLoc.getTypeLoc().getSourceRange();
3789 } else
3790 break;
3791
3792 NNSLoc = NNSLoc.getPrefix();
3793 }
3794
3795 return SourceRange();
3796}
3797
3798/// Match the given template parameter lists to the given scope
3799/// specifier, returning the template parameter list that applies to the
3800/// name.
3801///
3802/// \param DeclStartLoc the start of the declaration that has a scope
3803/// specifier or a template parameter list.
3804///
3805/// \param DeclLoc The location of the declaration itself.
3806///
3807/// \param SS the scope specifier that will be matched to the given template
3808/// parameter lists. This scope specifier precedes a qualified name that is
3809/// being declared.
3810///
3811/// \param TemplateId The template-id following the scope specifier, if there
3812/// is one. Used to check for a missing 'template<>'.
3813///
3814/// \param ParamLists the template parameter lists, from the outermost to the
3815/// innermost template parameter lists.
3816///
3817/// \param IsFriend Whether to apply the slightly different rules for
3818/// matching template parameters to scope specifiers in friend
3819/// declarations.
3820///
3821/// \param IsMemberSpecialization will be set true if the scope specifier
3822/// denotes a fully-specialized type, and therefore this is a declaration of
3823/// a member specialization.
3824///
3825/// \returns the template parameter list, if any, that corresponds to the
3826/// name that is preceded by the scope specifier @p SS. This template
3827/// parameter list may have template parameters (if we're declaring a
3828/// template) or may have no template parameters (if we're declaring a
3829/// template specialization), or may be NULL (if what we're declaring isn't
3830/// itself a template).
3832 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3833 TemplateIdAnnotation *TemplateId,
3834 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3835 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3836 IsMemberSpecialization = false;
3837 Invalid = false;
3838
3839 // The sequence of nested types to which we will match up the template
3840 // parameter lists. We first build this list by starting with the type named
3841 // by the nested-name-specifier and walking out until we run out of types.
3842 SmallVector<QualType, 4> NestedTypes;
3843 QualType T;
3844 if (SS.getScopeRep()) {
3846 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3848 else
3849 T = QualType(SS.getScopeRep()->getAsType(), 0);
3850 }
3851
3852 // If we found an explicit specialization that prevents us from needing
3853 // 'template<>' headers, this will be set to the location of that
3854 // explicit specialization.
3855 SourceLocation ExplicitSpecLoc;
3856
3857 while (!T.isNull()) {
3858 NestedTypes.push_back(T);
3859
3860 // Retrieve the parent of a record type.
3862 // If this type is an explicit specialization, we're done.
3864 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3865 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3866 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3867 ExplicitSpecLoc = Spec->getLocation();
3868 break;
3869 }
3870 } else if (Record->getTemplateSpecializationKind()
3872 ExplicitSpecLoc = Record->getLocation();
3873 break;
3874 }
3875
3876 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3878 else
3879 T = QualType();
3880 continue;
3881 }
3882
3883 if (const TemplateSpecializationType *TST
3885 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3886 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3888 else
3889 T = QualType();
3890 continue;
3891 }
3892 }
3893
3894 // Look one step prior in a dependent template specialization type.
3895 if (const DependentTemplateSpecializationType *DependentTST
3897 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3898 T = QualType(NNS->getAsType(), 0);
3899 else
3900 T = QualType();
3901 continue;
3902 }
3903
3904 // Look one step prior in a dependent name type.
3905 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3906 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3907 T = QualType(NNS->getAsType(), 0);
3908 else
3909 T = QualType();
3910 continue;
3911 }
3912
3913 // Retrieve the parent of an enumeration type.
3914 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3915 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3916 // check here.
3917 EnumDecl *Enum = EnumT->getDecl();
3918
3919 // Get to the parent type.
3920 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3922 else
3923 T = QualType();
3924 continue;
3925 }
3926
3927 T = QualType();
3928 }
3929 // Reverse the nested types list, since we want to traverse from the outermost
3930 // to the innermost while checking template-parameter-lists.
3931 std::reverse(NestedTypes.begin(), NestedTypes.end());
3932
3933 // C++0x [temp.expl.spec]p17:
3934 // A member or a member template may be nested within many
3935 // enclosing class templates. In an explicit specialization for
3936 // such a member, the member declaration shall be preceded by a
3937 // template<> for each enclosing class template that is
3938 // explicitly specialized.
3939 bool SawNonEmptyTemplateParameterList = false;
3940
3941 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3942 if (SawNonEmptyTemplateParameterList) {
3943 if (!SuppressDiagnostic)
3944 Diag(DeclLoc, diag::err_specialize_member_of_template)
3945 << !Recovery << Range;
3946 Invalid = true;
3947 IsMemberSpecialization = false;
3948 return true;
3949 }
3950
3951 return false;
3952 };
3953
3954 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3955 // Check that we can have an explicit specialization here.
3956 if (CheckExplicitSpecialization(Range, true))
3957 return true;
3958
3959 // We don't have a template header, but we should.
3960 SourceLocation ExpectedTemplateLoc;
3961 if (!ParamLists.empty())
3962 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3963 else
3964 ExpectedTemplateLoc = DeclStartLoc;
3965
3966 if (!SuppressDiagnostic)
3967 Diag(DeclLoc, diag::err_template_spec_needs_header)
3968 << Range
3969 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3970 return false;
3971 };
3972
3973 unsigned ParamIdx = 0;
3974 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3975 ++TypeIdx) {
3976 T = NestedTypes[TypeIdx];
3977
3978 // Whether we expect a 'template<>' header.
3979 bool NeedEmptyTemplateHeader = false;
3980
3981 // Whether we expect a template header with parameters.
3982 bool NeedNonemptyTemplateHeader = false;
3983
3984 // For a dependent type, the set of template parameters that we
3985 // expect to see.
3986 TemplateParameterList *ExpectedTemplateParams = nullptr;
3987
3988 // C++0x [temp.expl.spec]p15:
3989 // A member or a member template may be nested within many enclosing
3990 // class templates. In an explicit specialization for such a member, the
3991 // member declaration shall be preceded by a template<> for each
3992 // enclosing class template that is explicitly specialized.
3995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3996 ExpectedTemplateParams = Partial->getTemplateParameters();
3997 NeedNonemptyTemplateHeader = true;
3998 } else if (Record->isDependentType()) {
3999 if (Record->getDescribedClassTemplate()) {
4000 ExpectedTemplateParams = Record->getDescribedClassTemplate()
4001 ->getTemplateParameters();
4002 NeedNonemptyTemplateHeader = true;
4003 }
4004 } else if (ClassTemplateSpecializationDecl *Spec
4005 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
4006 // C++0x [temp.expl.spec]p4:
4007 // Members of an explicitly specialized class template are defined
4008 // in the same manner as members of normal classes, and not using
4009 // the template<> syntax.
4010 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
4011 NeedEmptyTemplateHeader = true;
4012 else
4013 continue;
4014 } else if (Record->getTemplateSpecializationKind()) {
4015 if (Record->getTemplateSpecializationKind()
4017 TypeIdx == NumTypes - 1)
4018 IsMemberSpecialization = true;
4019
4020 continue;
4021 }
4022 } else if (const TemplateSpecializationType *TST
4024 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
4025 ExpectedTemplateParams = Template->getTemplateParameters();
4026 NeedNonemptyTemplateHeader = true;
4027 }
4029 // FIXME: We actually could/should check the template arguments here
4030 // against the corresponding template parameter list.
4031 NeedNonemptyTemplateHeader = false;
4032 }
4033
4034 // C++ [temp.expl.spec]p16:
4035 // In an explicit specialization declaration for a member of a class
4036 // template or a member template that ap- pears in namespace scope, the
4037 // member template and some of its enclosing class templates may remain
4038 // unspecialized, except that the declaration shall not explicitly
4039 // specialize a class member template if its en- closing class templates
4040 // are not explicitly specialized as well.
4041 if (ParamIdx < ParamLists.size()) {
4042 if (ParamLists[ParamIdx]->size() == 0) {
4043 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4044 false))
4045 return nullptr;
4046 } else
4047 SawNonEmptyTemplateParameterList = true;
4048 }
4049
4050 if (NeedEmptyTemplateHeader) {
4051 // If we're on the last of the types, and we need a 'template<>' header
4052 // here, then it's a member specialization.
4053 if (TypeIdx == NumTypes - 1)
4054 IsMemberSpecialization = true;
4055
4056 if (ParamIdx < ParamLists.size()) {
4057 if (ParamLists[ParamIdx]->size() > 0) {
4058 // The header has template parameters when it shouldn't. Complain.
4059 if (!SuppressDiagnostic)
4060 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4061 diag::err_template_param_list_matches_nontemplate)
4062 << T
4063 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
4064 ParamLists[ParamIdx]->getRAngleLoc())
4066 Invalid = true;
4067 return nullptr;
4068 }
4069
4070 // Consume this template header.
4071 ++ParamIdx;
4072 continue;
4073 }
4074
4075 if (!IsFriend)
4076 if (DiagnoseMissingExplicitSpecialization(
4078 return nullptr;
4079
4080 continue;
4081 }
4082
4083 if (NeedNonemptyTemplateHeader) {
4084 // In friend declarations we can have template-ids which don't
4085 // depend on the corresponding template parameter lists. But
4086 // assume that empty parameter lists are supposed to match this
4087 // template-id.
4088 if (IsFriend && T->isDependentType()) {
4089 if (ParamIdx < ParamLists.size() &&
4091 ExpectedTemplateParams = nullptr;
4092 else
4093 continue;
4094 }
4095
4096 if (ParamIdx < ParamLists.size()) {
4097 // Check the template parameter list, if we can.
4098 if (ExpectedTemplateParams &&
4100 ExpectedTemplateParams,
4101 !SuppressDiagnostic, TPL_TemplateMatch))
4102 Invalid = true;
4103
4104 if (!Invalid &&
4105 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
4107 Invalid = true;
4108
4109 ++ParamIdx;
4110 continue;
4111 }
4112
4113 if (!SuppressDiagnostic)
4114 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
4115 << T
4117 Invalid = true;
4118 continue;
4119 }
4120 }
4121
4122 // If there were at least as many template-ids as there were template
4123 // parameter lists, then there are no template parameter lists remaining for
4124 // the declaration itself.
4125 if (ParamIdx >= ParamLists.size()) {
4126 if (TemplateId && !IsFriend) {
4127 // We don't have a template header for the declaration itself, but we
4128 // should.
4129 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
4130 TemplateId->RAngleLoc));
4131
4132 // Fabricate an empty template parameter list for the invented header.
4134 SourceLocation(), std::nullopt,
4135 SourceLocation(), nullptr);
4136 }
4137
4138 return nullptr;
4139 }
4140
4141 // If there were too many template parameter lists, complain about that now.
4142 if (ParamIdx < ParamLists.size() - 1) {
4143 bool HasAnyExplicitSpecHeader = false;
4144 bool AllExplicitSpecHeaders = true;
4145 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
4146 if (ParamLists[I]->size() == 0)
4147 HasAnyExplicitSpecHeader = true;
4148 else
4149 AllExplicitSpecHeaders = false;
4150 }
4151
4152 if (!SuppressDiagnostic)
4153 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4154 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
4155 : diag::err_template_spec_extra_headers)
4156 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
4157 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
4158
4159 // If there was a specialization somewhere, such that 'template<>' is
4160 // not required, and there were any 'template<>' headers, note where the
4161 // specialization occurred.
4162 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
4163 !SuppressDiagnostic)
4164 Diag(ExplicitSpecLoc,
4165 diag::note_explicit_template_spec_does_not_need_header)
4166 << NestedTypes.back();
4167
4168 // We have a template parameter list with no corresponding scope, which
4169 // means that the resulting template declaration can't be instantiated
4170 // properly (we'll end up with dependent nodes when we shouldn't).
4171 if (!AllExplicitSpecHeaders)
4172 Invalid = true;
4173 }
4174
4175 // C++ [temp.expl.spec]p16:
4176 // In an explicit specialization declaration for a member of a class
4177 // template or a member template that ap- pears in namespace scope, the
4178 // member template and some of its enclosing class templates may remain
4179 // unspecialized, except that the declaration shall not explicitly
4180 // specialize a class member template if its en- closing class templates
4181 // are not explicitly specialized as well.
4182 if (ParamLists.back()->size() == 0 &&
4183 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4184 false))
4185 return nullptr;
4186
4187 // Return the last template parameter list, which corresponds to the
4188 // entity being declared.
4189 return ParamLists.back();
4190}
4191
4193 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4194 Diag(Template->getLocation(), diag::note_template_declared_here)
4195 << (isa<FunctionTemplateDecl>(Template)
4196 ? 0
4197 : isa<ClassTemplateDecl>(Template)
4198 ? 1
4199 : isa<VarTemplateDecl>(Template)
4200 ? 2
4201 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
4202 << Template->getDeclName();
4203 return;
4204 }
4205
4206 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
4207 for (OverloadedTemplateStorage::iterator I = OST->begin(),
4208 IEnd = OST->end();
4209 I != IEnd; ++I)
4210 Diag((*I)->getLocation(), diag::note_template_declared_here)
4211 << 0 << (*I)->getDeclName();
4212
4213 return;
4214 }
4215}
4216
4217static QualType
4220 SourceLocation TemplateLoc,
4221 TemplateArgumentListInfo &TemplateArgs) {
4222 ASTContext &Context = SemaRef.getASTContext();
4223
4224 switch (BTD->getBuiltinTemplateKind()) {
4225 case BTK__make_integer_seq: {
4226 // Specializations of __make_integer_seq<S, T, N> are treated like
4227 // S<T, 0, ..., N-1>.
4228
4229 QualType OrigType = Converted[1].getAsType();
4230 // C++14 [inteseq.intseq]p1:
4231 // T shall be an integer type.
4232 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
4233 SemaRef.Diag(TemplateArgs[1].getLocation(),
4234 diag::err_integer_sequence_integral_element_type);
4235 return QualType();
4236 }
4237
4238 TemplateArgument NumArgsArg = Converted[2];
4239 if (NumArgsArg.isDependent())
4241 Converted);
4242
4243 TemplateArgumentListInfo SyntheticTemplateArgs;
4244 // The type argument, wrapped in substitution sugar, gets reused as the
4245 // first template argument in the synthetic template argument list.
4246 SyntheticTemplateArgs.addArgument(
4249 OrigType, TemplateArgs[1].getLocation())));
4250
4251 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
4252 // Expand N into 0 ... N-1.
4253 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
4254 I < NumArgs; ++I) {
4255 TemplateArgument TA(Context, I, OrigType);
4256 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
4257 TA, OrigType, TemplateArgs[2].getLocation()));
4258 }
4259 } else {
4260 // C++14 [inteseq.make]p1:
4261 // If N is negative the program is ill-formed.
4262 SemaRef.Diag(TemplateArgs[2].getLocation(),
4263 diag::err_integer_sequence_negative_length);
4264 return QualType();
4265 }
4266
4267 // The first template argument will be reused as the template decl that
4268 // our synthetic template arguments will be applied to.
4269 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
4270 TemplateLoc, SyntheticTemplateArgs);
4271 }
4272
4274 // Specializations of
4275 // __type_pack_element<Index, T_1, ..., T_N>
4276 // are treated like T_Index.
4277 assert(Converted.size() == 2 &&
4278 "__type_pack_element should be given an index and a parameter pack");
4279
4280 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
4281 if (IndexArg.isDependent() || Ts.isDependent())
4283 Converted);
4284
4285 llvm::APSInt Index = IndexArg.getAsIntegral();
4286 assert(Index >= 0 && "the index used with __type_pack_element should be of "
4287 "type std::size_t, and hence be non-negative");
4288 // If the Index is out of bounds, the program is ill-formed.
4289 if (Index >= Ts.pack_size()) {
4290 SemaRef.Diag(TemplateArgs[0].getLocation(),
4291 diag::err_type_pack_element_out_of_bounds);
4292 return QualType();
4293 }
4294
4295 // We simply return the type at index `Index`.
4296 int64_t N = Index.getExtValue();
4297 return Ts.getPackAsArray()[N].getAsType();
4298 }
4299 llvm_unreachable("unexpected BuiltinTemplateDecl!");
4300}
4301
4302/// Determine whether this alias template is "enable_if_t".
4303/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
4305 return AliasTemplate->getName().equals("enable_if_t") ||
4306 AliasTemplate->getName().equals("__enable_if_t");
4307}
4308
4309/// Collect all of the separable terms in the given condition, which
4310/// might be a conjunction.
4311///
4312/// FIXME: The right answer is to convert the logical expression into
4313/// disjunctive normal form, so we can find the first failed term
4314/// within each possible clause.
4315static void collectConjunctionTerms(Expr *Clause,
4316 SmallVectorImpl<Expr *> &Terms) {
4317 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
4318 if (BinOp->getOpcode() == BO_LAnd) {
4319 collectConjunctionTerms(BinOp->getLHS(), Terms);
4320 collectConjunctionTerms(BinOp->getRHS(), Terms);
4321 return;
4322 }
4323 }
4324
4325 Terms.push_back(Clause);
4326}
4327
4328// The ranges-v3 library uses an odd pattern of a top-level "||" with
4329// a left-hand side that is value-dependent but never true. Identify
4330// the idiom and ignore that term.
4332 // Top-level '||'.
4333 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
4334 if (!BinOp) return Cond;
4335
4336 if (BinOp->getOpcode() != BO_LOr) return Cond;
4337
4338 // With an inner '==' that has a literal on the right-hand side.
4339 Expr *LHS = BinOp->getLHS();
4340 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
4341 if (!InnerBinOp) return Cond;
4342
4343 if (InnerBinOp->getOpcode() != BO_EQ ||
4344 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
4345 return Cond;
4346
4347 // If the inner binary operation came from a macro expansion named
4348 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
4349 // of the '||', which is the real, user-provided condition.
4350 SourceLocation Loc = InnerBinOp->getExprLoc();
4351 if (!Loc.isMacroID()) return Cond;
4352
4353 StringRef MacroName = PP.getImmediateMacroName(Loc);
4354 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
4355 return BinOp->getRHS();
4356
4357 return Cond;
4358}
4359
4360namespace {
4361
4362// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
4363// within failing boolean expression, such as substituting template parameters
4364// for actual types.
4365class FailedBooleanConditionPrinterHelper : public PrinterHelper {
4366public:
4367 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
4368 : Policy(P) {}
4369
4370 bool handledStmt(Stmt *E, raw_ostream &OS) override {
4371 const auto *DR = dyn_cast<DeclRefExpr>(E);
4372 if (DR && DR->getQualifier()) {
4373 // If this is a qualified name, expand the template arguments in nested
4374 // qualifiers.
4375 DR->getQualifier()->print(OS, Policy, true);
4376 // Then print the decl itself.
4377 const ValueDecl *VD = DR->getDecl();
4378 OS << VD->getName();
4379 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
4380 // This is a template variable, print the expanded template arguments.
4382 OS, IV->getTemplateArgs().asArray(), Policy,
4383 IV->getSpecializedTemplate()->getTemplateParameters());
4384 }
4385 return true;
4386 }
4387 return false;
4388 }
4389
4390private:
4391 const PrintingPolicy Policy;
4392};
4393
4394} // end anonymous namespace
4395
4396std::pair<Expr *, std::string>
4398 Cond = lookThroughRangesV3Condition(PP, Cond);
4399
4400 // Separate out all of the terms in a conjunction.
4402 collectConjunctionTerms(Cond, Terms);
4403
4404 // Determine which term failed.
4405 Expr *FailedCond = nullptr;
4406 for (Expr *Term : Terms) {
4407 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
4408
4409 // Literals are uninteresting.
4410 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
4411 isa<IntegerLiteral>(TermAsWritten))
4412 continue;
4413
4414 // The initialization of the parameter from the argument is
4415 // a constant-evaluated context.
4418
4419 bool Succeeded;
4420 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
4421 !Succeeded) {
4422 FailedCond = TermAsWritten;
4423 break;
4424 }
4425 }
4426 if (!FailedCond)
4427 FailedCond = Cond->IgnoreParenImpCasts();
4428
4429 std::string Description;
4430 {
4431 llvm::raw_string_ostream Out(Description);
4433 Policy.PrintCanonicalTypes = true;
4434 FailedBooleanConditionPrinterHelper Helper(Policy);
4435 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
4436 }
4437 return { FailedCond, Description };
4438}
4439
4441 SourceLocation TemplateLoc,
4442 TemplateArgumentListInfo &TemplateArgs) {
4444 = Name.getUnderlying().getAsDependentTemplateName();
4445 if (DTN && DTN->isIdentifier())
4446 // When building a template-id where the template-name is dependent,
4447 // assume the template is a type template. Either our assumption is
4448 // correct, or the code is ill-formed and will be diagnosed when the
4449 // dependent name is substituted.
4452 TemplateArgs.arguments());
4453
4454 if (Name.getAsAssumedTemplateName() &&
4455 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
4456 return QualType();
4457
4458 TemplateDecl *Template = Name.getAsTemplateDecl();
4459 if (!Template || isa<FunctionTemplateDecl>(Template) ||
4460 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
4461 // We might have a substituted template template parameter pack. If so,
4462 // build a template specialization type for it.
4463 if (Name.getAsSubstTemplateTemplateParmPack())
4465 TemplateArgs.arguments());
4466
4467 Diag(TemplateLoc, diag::err_template_id_not_a_type)
4468 << Name;
4470 return QualType();
4471 }
4472
4473 // Check that the template argument list is well-formed for this
4474 // template.
4475 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4476 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
4477 SugaredConverted, CanonicalConverted,
4478 /*UpdateArgsWithConversions=*/true))
4479 return QualType();
4480
4481 QualType CanonType;
4482
4484 dyn_cast<TypeAliasTemplateDecl>(Template)) {
4485
4486 // Find the canonical type for this type alias template specialization.
4487 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4488 if (Pattern->isInvalidDecl())
4489 return QualType();
4490
4491 // Only substitute for the innermost template argument list.
4492 MultiLevelTemplateArgumentList TemplateArgLists;
4493 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4494 /*Final=*/false);
4495 TemplateArgLists.addOuterRetainedLevels(
4496 AliasTemplate->getTemplateParameters()->getDepth());
4497
4500 *this, /*PointOfInstantiation=*/TemplateLoc,
4501 /*Entity=*/AliasTemplate,
4502 /*TemplateArgs=*/TemplateArgLists.getInnermost());
4503 if (Inst.isInvalid())
4504 return QualType();
4505
4506 std::optional<ContextRAII> SavedContext;
4507 if (!AliasTemplate->getDeclContext()->isFileContext())
4508 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
4509
4510 CanonType =
4511 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
4512 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
4513 if (CanonType.isNull()) {
4514 // If this was enable_if and we failed to find the nested type
4515 // within enable_if in a SFINAE context, dig out the specific
4516 // enable_if condition that failed and present that instead.
4518 if (auto DeductionInfo = isSFINAEContext()) {
4519 if (*DeductionInfo &&
4520 (*DeductionInfo)->hasSFINAEDiagnostic() &&
4521 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4522 diag::err_typename_nested_not_found_enable_if &&
4523 TemplateArgs[0].getArgument().getKind()
4525 Expr *FailedCond;
4526 std::string FailedDescription;
4527 std::tie(FailedCond, FailedDescription) =
4528 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4529
4530 // Remove the old SFINAE diagnostic.
4531 PartialDiagnosticAt OldDiag =
4533 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4534
4535 // Add a new SFINAE diagnostic specifying which condition
4536 // failed.
4537 (*DeductionInfo)->addSFINAEDiagnostic(
4538 OldDiag.first,
4539 PDiag(diag::err_typename_nested_not_found_requirement)
4540 << FailedDescription
4541 << FailedCond->getSourceRange());
4542 }
4543 }
4544 }
4545
4546 return QualType();
4547 }
4548 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4549 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4550 TemplateLoc, TemplateArgs);
4551 } else if (Name.isDependent() ||
4553 TemplateArgs, CanonicalConverted)) {
4554 // This class template specialization is a dependent
4555 // type. Therefore, its canonical type is another class template
4556 // specialization type that contains all of the converted
4557 // arguments in canonical form. This ensures that, e.g., A<T> and
4558 // A<T, T> have identical types when A is declared as:
4559 //
4560 // template<typename T, typename U = T> struct A;
4562 Name, CanonicalConverted);
4563
4564 // This might work out to be a current instantiation, in which
4565 // case the canonical type needs to be the InjectedClassNameType.
4566 //
4567 // TODO: in theory this could be a simple hashtable lookup; most
4568 // changes to CurContext don't change the set of current
4569 // instantiations.
4570 if (isa<ClassTemplateDecl>(Template)) {
4571 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4572 // If we get out to a namespace, we're done.
4573 if (Ctx->isFileContext()) break;
4574
4575 // If this isn't a record, keep looking.
4576 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4577 if (!Record) continue;
4578
4579 // Look for one of the two cases with InjectedClassNameTypes
4580 // and check whether it's the same template.
4581 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4582 !Record->getDescribedClassTemplate())
4583 continue;
4584
4585 // Fetch the injected class name type and check whether its
4586 // injected type is equal to the type we just built.
4588 QualType Injected = cast<InjectedClassNameType>(ICNT)
4589 ->getInjectedSpecializationType();
4590
4591 if (CanonType != Injected->getCanonicalTypeInternal())
4592 continue;
4593
4594 // If so, the canonical type of this TST is the injected
4595 // class name type of the record we just found.
4596 assert(ICNT.isCanonical());
4597 CanonType = ICNT;
4598 break;
4599 }
4600 }
4601 } else if (ClassTemplateDecl *ClassTemplate =
4602 dyn_cast<ClassTemplateDecl>(Template)) {
4603 // Find the class template specialization declaration that
4604 // corresponds to these arguments.
4605 void *InsertPos = nullptr;
4607 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4608 if (!Decl) {
4609 // This is the first time we have referenced this class template
4610 // specialization. Create the canonical declaration and add it to
4611 // the set of specializations.
4613 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4614 ClassTemplate->getDeclContext(),
4615 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4616 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4617 nullptr);
4618 ClassTemplate->AddSpecialization(Decl, InsertPos);
4619 if (ClassTemplate->isOutOfLine())
4620 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4621 }
4622
4623 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4624 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4625 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4626 if (!Inst.isInvalid()) {
4627 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4628 CanonicalConverted,
4629 /*Final=*/false);
4630 InstantiateAttrsForDecl(TemplateArgLists,
4631 ClassTemplate->getTemplatedDecl(), Decl);
4632 }
4633 }
4634
4635 // Diagnose uses of this specialization.
4636 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4637
4638 CanonType = Context.getTypeDeclType(Decl);
4639 assert(isa<RecordType>(CanonType) &&
4640 "type of non-dependent specialization is not a RecordType");
4641 } else {
4642 llvm_unreachable("Unhandled template kind");
4643 }
4644
4645 // Build the fully-sugared type for this class template
4646 // specialization, which refers back to the class template
4647 // specialization we created or found.
4648 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4649 CanonType);
4650}
4651
4653 TemplateNameKind &TNK,
4654 SourceLocation NameLoc,
4655 IdentifierInfo *&II) {
4656 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4657
4658 TemplateName Name = ParsedName.get();
4659 auto *ATN = Name.getAsAssumedTemplateName();
4660 assert(ATN && "not an assumed template name");
4661 II = ATN->getDeclName().getAsIdentifierInfo();
4662
4663 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4664 // Resolved to a type template name.
4665 ParsedName = TemplateTy::make(Name);
4666 TNK = TNK_Type_template;
4667 }
4668}
4669
4671 SourceLocation NameLoc,
4672 bool Diagnose) {
4673 // We assumed this undeclared identifier to be an (ADL-only) function
4674 // template name, but it was used in a context where a type was required.
4675 // Try to typo-correct it now.
4676 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4677 assert(ATN && "not an assumed template name");
4678
4679 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4680 struct CandidateCallback : CorrectionCandidateCallback {
4681 bool ValidateCandidate(const TypoCorrection &TC) override {
4682 return TC.getCorrectionDecl() &&
4684 }
4685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4686 return std::make_unique<CandidateCallback>(*this);
4687 }
4688 } FilterCCC;
4689
4690 TypoCorrection Corrected =
4691 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4692 FilterCCC, CTK_ErrorRecovery);
4693 if (Corrected && Corrected.getFoundDecl()) {
4694 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4695 << ATN->getDeclName());
4696 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4697 return false;
4698 }
4699
4700 if (Diagnose)
4701 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4702 return true;
4703}
4704
4706 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4707 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
4708 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4709 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4710 bool IsCtorOrDtorName, bool IsClassName,
4711 ImplicitTypenameContext AllowImplicitTypename) {
4712 if (SS.isInvalid())
4713 return true;
4714
4715 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4716 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4717
4718 // C++ [temp.res]p3:
4719 // A qualified-id that refers to a type and in which the
4720 // nested-name-specifier depends on a template-parameter (14.6.2)
4721 // shall be prefixed by the keyword typename to indicate that the
4722 // qualified-id denotes a type, forming an
4723 // elaborated-type-specifier (7.1.5.3).
4724 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4725 // C++2a relaxes some of those restrictions in [temp.res]p5.
4726 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4728 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4729 else
4730 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4731 << SS.getScopeRep() << TemplateII->getName()
4732 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4733 } else
4734 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4735 << SS.getScopeRep() << TemplateII->getName();
4736
4737 // FIXME: This is not quite correct recovery as we don't transform SS
4738 // into the corresponding dependent form (and we don't diagnose missing
4739 // 'template' keywords within SS as a result).
4740 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4741 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4742 TemplateArgsIn, RAngleLoc);
4743 }
4744
4745 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4746 // it's not actually allowed to be used as a type in most cases. Because
4747 // we annotate it before we know whether it's valid, we have to check for
4748 // this case here.
4749 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4750 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4751 Diag(TemplateIILoc,
4752 TemplateKWLoc.isInvalid()
4753 ? diag::err_out_of_line_qualified_id_type_names_constructor
4754 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4755 << TemplateII << 0 /*injected-class-name used as template name*/
4756 << 1 /*if any keyword was present, it was 'template'*/;
4757 }
4758 }
4759
4760 TemplateName Template = TemplateD.get();
4761 if (Template.getAsAssumedTemplateName() &&
4762 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4763 return true;
4764
4765 // Translate the parser's template argument list in our AST format.
4766 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4767 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4768
4769 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4770 assert(SS.getScopeRep() == DTN->getQualifier());
4772 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4773 TemplateArgs.arguments());
4774 // Build type-source information.
4775 TypeLocBuilder TLB;
4780 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4781 SpecTL.setTemplateNameLoc(TemplateIILoc);
4782 SpecTL.setLAngleLoc(LAngleLoc);
4783 SpecTL.setRAngleLoc(RAngleLoc);
4784 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4785 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4787 }
4788
4789 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4790 if (SpecTy.isNull())
4791 return true;
4792
4793 // Build type-source information.
4794 TypeLocBuilder TLB;
4797 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4798 SpecTL.setTemplateNameLoc(TemplateIILoc);
4799 SpecTL.setLAngleLoc(LAngleLoc);
4800 SpecTL.setRAngleLoc(RAngleLoc);
4801 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4802 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4803
4804 // Create an elaborated-type-specifier containing the nested-name-specifier.
4805 QualType ElTy =
4807 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4808 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4810 if (!ElabTL.isEmpty())
4812 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4813}
4814
4816 TypeSpecifierType TagSpec,
4817 SourceLocation TagLoc,
4818 CXXScopeSpec &SS,
4819 SourceLocation TemplateKWLoc,
4820 TemplateTy TemplateD,
4821 SourceLocation TemplateLoc,
4822 SourceLocation LAngleLoc,
4823 ASTTemplateArgsPtr TemplateArgsIn,
4824 SourceLocation RAngleLoc) {
4825 if (SS.isInvalid())
4826 return TypeResult(true);
4827
4828 TemplateName Template = TemplateD.get();
4829
4830 // Translate the parser's template argument list in our AST format.
4831 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4832 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4833
4834 // Determine the tag kind
4836 ElaboratedTypeKeyword Keyword
4838
4839 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4840 assert(SS.getScopeRep() == DTN->getQualifier());
4842 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4843 TemplateArgs.arguments());
4844
4845 // Build type-source information.
4846 TypeLocBuilder TLB;
4849 SpecTL.setElaboratedKeywordLoc(TagLoc);
4851 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4852 SpecTL.setTemplateNameLoc(TemplateLoc);
4853 SpecTL.setLAngleLoc(LAngleLoc);
4854 SpecTL.setRAngleLoc(RAngleLoc);
4855 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4856 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4858 }
4859
4860 if (TypeAliasTemplateDecl *TAT =
4861 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4862 // C++0x [dcl.type.elab]p2:
4863 // If the identifier resolves to a typedef-name or the simple-template-id
4864 // resolves to an alias template specialization, the
4865 // elaborated-type-specifier is ill-formed.
4866 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4867 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4868 Diag(TAT->getLocation(), diag::note_declared_at);
4869 }
4870
4871 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4872 if (Result.isNull())
4873 return TypeResult(true);
4874
4875 // Check the tag kind
4876 if (const RecordType *RT = Result->getAs<RecordType>()) {
4877 RecordDecl *D = RT->getDecl();
4878
4880 assert(Id && "templated class must have an identifier");
4881
4882 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4883 TagLoc, Id)) {
4884 Diag(TagLoc, diag::err_use_with_wrong_tag)
4885 << Result
4887 Diag(D->getLocation(), diag::note_previous_use);
4888 }
4889 }
4890
4891 // Provide source-location information for the template specialization.
4892 TypeLocBuilder TLB;
4895 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4896 SpecTL.setTemplateNameLoc(TemplateLoc);
4897 SpecTL.setLAngleLoc(LAngleLoc);
4898 SpecTL.setRAngleLoc(RAngleLoc);
4899 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4900 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4901
4902 // Construct an elaborated type containing the nested-name-specifier (if any)
4903 // and tag keyword.
4906 ElabTL.setElaboratedKeywordLoc(TagLoc);
4909}
4910
4911static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4912 NamedDecl *PrevDecl,
4913 SourceLocation Loc,
4915
4917
4919 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4920 switch (Arg.getKind()) {
4928 return false;
4929
4931 QualType Type = Arg.getAsType();
4932 const TemplateTypeParmType *TPT =
4934 return TPT && !Type.hasQualifiers() &&
4935 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4936 }
4937
4939 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4940 if (!DRE || !DRE->getDecl())
4941 return false;
4942 const NonTypeTemplateParmDecl *NTTP =
4943 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4944 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4945 }
4946
4948 const TemplateTemplateParmDecl *TTP =
4949 dyn_cast_or_null<TemplateTemplateParmDecl>(
4951 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4952 }
4953 llvm_unreachable("unexpected kind of template argument");
4954}
4955
4958 if (Params->size() != Args.size())
4959 return false;
4960
4961 unsigned Depth = Params->getDepth();
4962
4963 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4964 TemplateArgument Arg = Args[I];
4965
4966 // If the parameter is a pack expansion, the argument must be a pack
4967 // whose only element is a pack expansion.
4968 if (Params->getParam(I)->isParameterPack()) {
4969 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4970 !Arg.pack_begin()->isPackExpansion())
4971 return false;
4972 Arg = Arg.pack_begin()->getPackExpansionPattern();
4973 }
4974
4975 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4976 return false;
4977 }
4978
4979 return true;
4980}
4981
4982template<typename PartialSpecDecl>
4983static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4984 if (Partial->getDeclContext()->isDependentContext())
4985 return;
4986
4987 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4988 // for non-substitution-failure issues?
4989 TemplateDeductionInfo Info(Partial->getLocation());
4990 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4991 return;
4992
4993 auto *Template = Partial->getSpecializedTemplate();
4994 S.Diag(Partial->getLocation(),
4995 diag::ext_partial_spec_not_more_specialized_than_primary)
4996 << isa<VarTemplateDecl>(Template);
4997
4998 if (Info.hasSFINAEDiagnostic()) {
5002 SmallString<128> SFINAEArgString;
5003 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
5004 S.Diag(Diag.first,
5005 diag::note_partial_spec_not_more_specialized_than_primary)
5006 << SFINAEArgString;
5007 }
5008
5009 S.NoteTemplateLocation(*Template);
5010 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
5011 Template->getAssociatedConstraints(TemplateAC);
5012 Partial->getAssociatedConstraints(PartialAC);
5013 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
5014 TemplateAC);
5015}
5016
5017static void
5019 const llvm::SmallBitVector &DeducibleParams) {
5020 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5021 if (!DeducibleParams[I]) {
5022 NamedDecl *Param = TemplateParams->getParam(I);
5023 if (Param->getDeclName())
5024 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5025 << Param->getDeclName();
5026 else
5027 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5028 << "(anonymous)";
5029 }
5030 }
5031}
5032
5033
5034template<typename PartialSpecDecl>
5036 PartialSpecDecl *Partial) {
5037 // C++1z [temp.class.spec]p8: (DR1495)
5038 // - The specialization shall be more specialized than the primary
5039 // template (14.5.5.2).
5041
5042 // C++ [temp.class.spec]p8: (DR1315)
5043 // - Each template-parameter shall appear at least once in the
5044 // template-id outside a non-deduced context.
5045 // C++1z [temp.class.spec.match]p3 (P0127R2)
5046 // If the template arguments of a partial specialization cannot be
5047 // deduced because of the structure of its template-parameter-list
5048 // and the template-id, the program is ill-formed.
5049 auto *TemplateParams = Partial->getTemplateParameters();
5050 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5051 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5052 TemplateParams->getDepth(), DeducibleParams);
5053
5054 if (!DeducibleParams.all()) {
5055 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5056 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
5057 << isa<VarTemplatePartialSpecializationDecl>(Partial)
5058 << (NumNonDeducible > 1)
5059 << SourceRange(Partial->getLocation(),
5060 Partial->getTemplateArgsAsWritten()->RAngleLoc);
5061 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
5062 }
5063}
5064
5067 checkTemplatePartialSpecialization(*this, Partial);
5068}
5069
5072 checkTemplatePartialSpecialization(*this, Partial);
5073}
5074
5076 // C++1z [temp.param]p11:
5077 // A template parameter of a deduction guide template that does not have a
5078 // default-argument shall be deducible from the parameter-type-list of the
5079 // deduction guide template.
5080 auto *TemplateParams = TD->getTemplateParameters();
5081 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5082 MarkDeducedTemplateParameters(TD, DeducibleParams);
5083 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
5084 // A parameter pack is deducible (to an empty pack).
5085 auto *Param = TemplateParams->getParam(I);
5086 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
5087 DeducibleParams[I] = true;
5088 }
5089
5090 if (!DeducibleParams.all()) {
5091 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5092 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
5093 << (NumNonDeducible > 1);
5094 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
5095 }
5096}
5097
5100 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5102 // D must be variable template id.
5104 "Variable template specialization is declared with a template id.");
5105
5106 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5107 TemplateArgumentListInfo TemplateArgs =
5108 makeTemplateArgumentListInfo(*this, *TemplateId);
5109 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
5110 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
5111 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
5112
5113 TemplateName Name = TemplateId->Template.get();
5114
5115 // The template-id must name a variable template.
5117 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
5118 if (!VarTemplate) {
5119 NamedDecl *FnTemplate;
5120 if (auto *OTS = Name.getAsOverloadedTemplate())
5121 FnTemplate = *OTS->begin();
5122 else
5123 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
5124 if (FnTemplate)
5125 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
5126 << FnTemplate->getDeclName();
5127 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5129 }
5130
5131 // Check for unexpanded parameter packs in any of the template arguments.
5132 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5133 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5137 return true;
5138
5139 // Check that the template argument list is well-formed for this
5140 // template.
5141 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5142 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
5143 false, SugaredConverted, CanonicalConverted,
5144 /*UpdateArgsWithConversions=*/true))
5145 return true;
5146
5147 // Find the variable template (partial) specialization declaration that
5148 // corresponds to these arguments.
5151 TemplateArgs.size(),
5152 CanonicalConverted))
5153 return true;
5154
5155 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
5156 // also do them during instantiation.
5157 if (!Name.isDependent() &&
5159 TemplateArgs, CanonicalConverted)) {
5160 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5161 << VarTemplate->getDeclName();
5163 }
5164
5165 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
5166 CanonicalConverted) &&
5167 (!Context.getLangOpts().CPlusPlus20 ||
5168 !TemplateParams->hasAssociatedConstraints())) {
5169 // C++ [temp.class.spec]p9b3:
5170 //
5171 // -- The argument list of the specialization shall not be identical
5172 // to the implicit argument list of the primary template.
5173 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5174 << /*variable template*/ 1
5175 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
5176 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5177 // FIXME: Recover from this by treating the declaration as a redeclaration
5178 // of the primary template.
5179 return true;
5180 }
5181 }
5182
5183 void *InsertPos = nullptr;
5184 VarTemplateSpecializationDecl *PrevDecl = nullptr;
5185
5187 PrevDecl = VarTemplate->findPartialSpecialization(
5188 CanonicalConverted, TemplateParams, InsertPos);
5189 else
5190 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
5191
5193
5194 // Check whether we can declare a variable template specialization in
5195 // the current scope.
5196 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
5197 TemplateNameLoc,
5199 return true;
5200
5201 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
5202 // Since the only prior variable template specialization with these
5203 // arguments was referenced but not declared, reuse that
5204 // declaration node as our own, updating its source location and
5205 // the list of outer template parameters to reflect our new declaration.
5206 Specialization = PrevDecl;
5207 Specialization->setLocation(TemplateNameLoc);
5208 PrevDecl = nullptr;
5209 } else if (IsPartialSpecialization) {
5210 // Create a new class template partial specialization declaration node.
5212 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
5215 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
5216 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
5217 CanonicalConverted, TemplateArgs);
5218
5219 if (!PrevPartial)
5220 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
5221 Specialization = Partial;
5222
5223 // If we are providing an explicit specialization of a member variable
5224 // template specialization, make a note of that.
5225 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5226 PrevPartial->setMemberSpecialization();
5227
5229 } else {
5230 // Create a new class template specialization declaration node for
5231 // this explicit specialization or friend declaration.
5233 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
5234 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
5235 Specialization->setTemplateArgsInfo(TemplateArgs);
5236
5237 if (!PrevDecl)
5238 VarTemplate->AddSpecialization(Specialization, InsertPos);
5239 }
5240
5241 // C++ [temp.expl.spec]p6:
5242 // If a template, a member template or the member of a class template is
5243 // explicitly specialized then that specialization shall be declared
5244 // before the first use of that specialization that would cause an implicit
5245 // instantiation to take place, in every translation unit in which such a
5246 // use occurs; no diagnostic is required.
5247 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5248 bool Okay = false;
5249 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5250 // Is there any previous explicit specialization declaration?
5252 Okay = true;
5253 break;
5254 }
5255 }
5256
5257 if (!Okay) {
5258 SourceRange Range(TemplateNameLoc, RAngleLoc);
5259 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5260 << Name << Range;
5261
5262 Diag(PrevDecl->getPointOfInstantiation(),
5263 diag::note_instantiation_required_here)
5264 << (PrevDecl->getTemplateSpecializationKind() !=
5266 return true;
5267 }
5268 }
5269
5270 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5271 Specialization->setLexicalDeclContext(CurContext);
5272
5273 // Add the specialization into its lexical context, so that it can
5274 // be seen when iterating through the list of declarations in that
5275 // context. However, specializations are not found by name lookup.
5277
5278 // Note that this is an explicit specialization.
5279 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5280
5281 Previous.clear();
5282 if (PrevDecl)
5283 Previous.addDecl(PrevDecl);
5284 else if (Specialization->isStaticDataMember() &&
5285 Specialization->isOutOfLine())
5286 Specialization->setAccess(VarTemplate->getAccess());
5287
5288 return Specialization;
5289}
5290
5291namespace {
5292/// A partial specialization whose template arguments have matched
5293/// a given template-id.
5294struct PartialSpecMatchResult {
5297};
5298} // end anonymous namespace
5299
5302 SourceLocation TemplateNameLoc,
5303 const TemplateArgumentListInfo &TemplateArgs) {
5304 assert(Template && "A variable template id without template?");
5305
5306 // Check that the template argument list is well-formed for this template.
5307 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5309 Template, TemplateNameLoc,
5310 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
5311 SugaredConverted, CanonicalConverted,
5312 /*UpdateArgsWithConversions=*/true))
5313 return true;
5314
5315 // Produce a placeholder value if the specialization is dependent.
5316 if (Template->getDeclContext()->isDependentContext() ||
5318 TemplateArgs, CanonicalConverted))
5319 return DeclResult();
5320
5321 // Find the variable template specialization declaration that
5322 // corresponds to these arguments.
5323 void *InsertPos = nullptr;
5325 Template->findSpecialization(CanonicalConverted, InsertPos)) {
5326 checkSpecializationReachability(TemplateNameLoc, Spec);
5327 // If we already have a variable template specialization, return it.
5328 return Spec;
5329 }
5330
5331 // This is the first time we have referenced this variable template
5332 // specialization. Create the canonical declaration and add it to
5333 // the set of specializations, based on the closest partial specialization
5334 // that it represents. That is,
5335 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
5336 const TemplateArgumentList *PartialSpecArgs = nullptr;
5337 bool AmbiguousPartialSpec = false;
5338 typedef PartialSpecMatchResult MatchResult;
5340 SourceLocation PointOfInstantiation = TemplateNameLoc;
5341 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
5342 /*ForTakingAddress=*/false);
5343
5344 // 1. Attempt to find the closest partial specialization that this
5345 // specializes, if any.
5346 // TODO: Unify with InstantiateClassTemplateSpecialization()?
5347 // Perhaps better after unification of DeduceTemplateArguments() and
5348 // getMoreSpecializedPartialSpecialization().
5350 Template->getPartialSpecializations(PartialSpecs);
5351
5352 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
5353 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
5354 TemplateDeductionInfo Info(FailedCandidates.getLocation());
5355
5357 DeduceTemplateArguments(Partial, CanonicalConverted, Info);
5359 // Store the failed-deduction information for use in diagnostics, later.
5360 // TODO: Actually use the failed-deduction info?
5361 FailedCandidates.addCandidate().set(
5362 DeclAccessPair::make(Template, AS_public), Partial,
5364 (void)Result;
5365 } else {
5366 Matched.push_back(PartialSpecMatchResult());
5367 Matched.back().Partial = Partial;
5368 Matched.back().Args = Info.takeCanonical();
5369 }
5370 }
5371
5372 if (Matched.size() >= 1) {
5373 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
5374 if (Matched.size() == 1) {
5375 // -- If exactly one matching specialization is found, the
5376 // instantiation is generated from that specialization.
5377 // We don't need to do anything for this.
5378 } else {
5379 // -- If more than one matching specialization is found, the
5380 // partial order rules (14.5.4.2) are used to determine
5381 // whether one of the specializations is more specialized
5382 // than the others. If none of the specializations is more
5383 // specialized than all of the other matching
5384 // specializations, then the use of the variable template is
5385 // ambiguous and the program is ill-formed.
5387 PEnd = Matched.end();
5388 P != PEnd; ++P) {
5389 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
5390 PointOfInstantiation) ==
5391 P->Partial)
5392 Best = P;
5393 }
5394
5395 // Determine if the best partial specialization is more specialized than
5396 // the others.
5397 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
5398 PEnd = Matched.end();
5399 P != PEnd; ++P) {
5401 P->Partial, Best->Partial,
5402 PointOfInstantiation) != Best->Partial) {
5403 AmbiguousPartialSpec = true;
5404 break;
5405 }
5406 }
5407 }
5408
5409 // Instantiate using the best variable template partial specialization.
5410 InstantiationPattern = Best->Partial;
5411 PartialSpecArgs = Best->Args;
5412 } else {
5413 // -- If no match is found, the instantiation is generated
5414 // from the primary template.
5415 // InstantiationPattern = Template->getTemplatedDecl();
5416 }
5417
5418 // 2. Create the canonical declaration.
5419 // Note that we do not instantiate a definition until we see an odr-use
5420 // in DoMarkVarDeclReferenced().
5421 // FIXME: LateAttrs et al.?
5423 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
5424 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
5425 if (!Decl)
5426 return true;
5427
5428 if (AmbiguousPartialSpec) {
5429 // Partial ordering did not produce a clear winner. Complain.
5431 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
5432 << Decl;
5433
5434 // Print the matching partial specializations.
5435 for (MatchResult P : Matched)
5436 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
5437 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
5438 *P.Args);
5439 return true;
5440 }
5441
5443 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
5444 Decl->setInstantiationOf(D, PartialSpecArgs);
5445
5446 checkSpecializationReachability(TemplateNameLoc, Decl);
5447
5448 assert(Decl && "No variable template specialization?");
5449 return Decl;
5450}
5451
5453 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
5454 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
5455 const TemplateArgumentListInfo *TemplateArgs) {
5456
5457 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
5458 *TemplateArgs);
5459 if (Decl.isInvalid())
5460 return ExprError();
5461
5462 if (!Decl.get())
5463 return ExprResult();
5464
5465 VarDecl *Var = cast<VarDecl>(Decl.get());
5468 NameInfo.getLoc());
5469
5470 // Build an ordinary singleton decl ref.
5471 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
5472}
5473
5475 SourceLocation Loc) {
5476 Diag(Loc, diag::err_template_missing_args)
5477 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
5478 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
5479 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
5480 }
5481}
5482
5485 SourceLocation TemplateKWLoc,
5486 const DeclarationNameInfo &ConceptNameInfo,
5487 NamedDecl *FoundDecl,
5488 ConceptDecl *NamedConcept,
5489 const TemplateArgumentListInfo *TemplateArgs) {
5490 assert(NamedConcept && "A concept template id without a template?");
5491
5492 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5494 NamedConcept, ConceptNameInfo.getLoc(),
5495 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5496 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5497 /*UpdateArgsWithConversions=*/false))
5498 return ExprError();
5499
5501 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5502 CanonicalConverted);
5503 ConstraintSatisfaction Satisfaction;
5504 bool AreArgsDependent =
5506 *TemplateArgs, CanonicalConverted);
5507 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5508 /*Final=*/false);
5510
5513
5514 if (!AreArgsDependent &&
5516 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5517 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5518 TemplateArgs->getRAngleLoc()),
5519 Satisfaction))
5520 return ExprError();
5521 auto *CL = ConceptReference::Create(
5522 Context,
5524 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5527 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5528}
5529
5531 SourceLocation TemplateKWLoc,
5532 LookupResult &R,
5533 bool RequiresADL,
5534 const TemplateArgumentListInfo *TemplateArgs) {
5535 // FIXME: Can we do any checking at this point? I guess we could check the
5536 // template arguments that we have against the template name, if the template
5537 // name refers to a single template. That's not a terribly common case,
5538 // though.
5539 // foo<int> could identify a single function unambiguously
5540 // This approach does NOT work, since f<int>(1);
5541 // gets resolved prior to resorting to overload resolution
5542 // i.e., template<class T> void f(double);
5543 // vs template<class T, class U> void f(U);
5544
5545 // These should be filtered out by our callers.
5546 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5547
5548 // Non-function templates require a template argument list.
5549 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5550 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5552 return ExprError();
5553 }
5554 }
5555 bool KnownDependent = false;
5556 // In C++1y, check variable template ids.
5557 if (R.getAsSingle<VarTemplateDecl>()) {
5560 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5561 if (Res.isInvalid() || Res.isUsable())
5562 return Res;
5563 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5564 KnownDependent = true;
5565 }
5566
5567 if (R.getAsSingle<ConceptDecl>()) {
5568 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5570 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5571 }
5572
5573 // We don't want lookup warnings at this point.
5575
5578 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5579 R.begin(), R.end(), KnownDependent);
5580
5581 return ULE;
5582}
5583
5584// We actually only call this from template instantiation.
5587 SourceLocation TemplateKWLoc,
5588 const DeclarationNameInfo &NameInfo,
5589 const TemplateArgumentListInfo *TemplateArgs) {
5590
5591 assert(TemplateArgs || TemplateKWLoc.isValid());
5592 DeclContext *DC;
5593 if (!(DC = computeDeclContext(SS, false)) ||
5594 DC->isDependentContext() ||
5596 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5597
5598 bool MemberOfUnknownSpecialization;
5599 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5600 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5601 /*Entering*/false, MemberOfUnknownSpecialization,
5602 TemplateKWLoc))
5603 return ExprError();
5604
5605 if (R.isAmbiguous())
5606 return ExprError();
5607
5608 if (R.empty()) {
5609 Diag(NameInfo.getLoc(), diag::err_no_member)
5610 << NameInfo.getName() << DC << SS.getRange();
5611 return ExprError();
5612 }
5613
5614 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5615 bool isTypeAliasTemplateDecl) {
5616 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5617 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5618 << isTypeAliasTemplateDecl;
5619 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5620 return ExprError();
5621 };
5622
5624 return DiagnoseTypeTemplateDecl(Temp, false);
5625
5627 return DiagnoseTypeTemplateDecl(Temp, true);
5628
5629 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5630}
5631
5632/// Form a template name from a name that is syntactically required to name a
5633/// template, either due to use of the 'template' keyword or because a name in
5634/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5635///
5636/// This action forms a template name given the name of the template and its
5637/// optional scope specifier. This is used when the 'template' keyword is used
5638/// or when the parsing context unambiguously treats a following '<' as
5639/// introducing a template argument list. Note that this may produce a
5640/// non-dependent template name if we can perform the lookup now and identify
5641/// the named template.
5642///
5643/// For example, given "x.MetaFun::template apply", the scope specifier
5644/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5645/// of the "template" keyword, and "apply" is the \p Name.
5647 CXXScopeSpec &SS,
5648 SourceLocation TemplateKWLoc,
5649 const UnqualifiedId &Name,
5650 ParsedType ObjectType,
5651 bool EnteringContext,
5653 bool AllowInjectedClassName) {
5654 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5655 Diag(TemplateKWLoc,
5657 diag::warn_cxx98_compat_template_outside_of_template :
5658 diag::ext_template_outside_of_template)
5659 << FixItHint::CreateRemoval(TemplateKWLoc);
5660
5661 if (SS.isInvalid())
5662 return TNK_Non_template;
5663
5664 // Figure out where isTemplateName is going to look.
5665 DeclContext *LookupCtx = nullptr;
5666 if (SS.isNotEmpty())
5667 LookupCtx = computeDeclContext(SS, EnteringContext);
5668 else if (ObjectType)
5669 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5670
5671 // C++0x [temp.names]p5:
5672 // If a name prefixed by the keyword template is not the name of
5673 // a template, the program is ill-formed. [Note: the keyword
5674 // template may not be applied to non-template members of class
5675 // templates. -end note ] [ Note: as is the case with the
5676 // typename prefix, the template prefix is allowed in cases
5677 // where it is not strictly necessary; i.e., when the
5678 // nested-name-specifier or the expression on the left of the ->
5679 // or . is not dependent on a template-parameter, or the use
5680 // does not appear in the scope of a template. -end note]
5681 //
5682 // Note: C++03 was more strict here, because it banned the use of
5683 // the "template" keyword prior to a template-name that was not a
5684 // dependent name. C++ DR468 relaxed this requirement (the
5685 // "template" keyword is now permitted). We follow the C++0x
5686 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5687 bool MemberOfUnknownSpecialization;
5688 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5689 ObjectType, EnteringContext, Result,
5690 MemberOfUnknownSpecialization);
5691 if (TNK != TNK_Non_template) {
5692 // We resolved this to a (non-dependent) template name. Return it.
5693 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5694 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5695 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5696 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5697 // C++14 [class.qual]p2:
5698 // In a lookup in which function names are not ignored and the
5699 // nested-name-specifier nominates a class C, if the name specified
5700 // [...] is the injected-class-name of C, [...] the name is instead
5701 // considered to name the constructor
5702 //
5703 // We don't get here if naming the constructor would be valid, so we
5704 // just reject immediately and recover by treating the
5705 // injected-class-name as naming the template.
5706 Diag(Name.getBeginLoc(),
5707 diag::ext_out_of_line_qualified_id_type_names_constructor)
5708 << Name.Identifier
5709 << 0 /*injected-class-name used as template name*/
5710 << TemplateKWLoc.isValid();
5711 }
5712 return TNK;
5713 }
5714
5715 if (!MemberOfUnknownSpecialization) {
5716 // Didn't find a template name, and the lookup wasn't dependent.
5717 // Do the lookup again to determine if this is a "nothing found" case or
5718 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5719 // need to do this.
5721 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5723 bool MOUS;
5724 // Tell LookupTemplateName that we require a template so that it diagnoses
5725 // cases where it finds a non-template.
5726 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5727 ? RequiredTemplateKind(TemplateKWLoc)
5729 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5730 RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5731 !R.isAmbiguous()) {
5732 if (LookupCtx)
5733 Diag(Name.getBeginLoc(), diag::err_no_member)
5734 << DNI.getName() << LookupCtx << SS.getRange();
5735 else
5736 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5737 << DNI.getName() << SS.getRange();
5738 }
5739 return TNK_Non_template;
5740 }
5741
5742 NestedNameSpecifier *Qualifier = SS.getScopeRep();
5743
5744 switch (Name.getKind()) {
5747 Context.getDependentTemplateName(Qualifier, Name.Identifier));
5749
5752 Qualifier, Name.OperatorFunctionId.Operator));
5753 return TNK_Function_template;
5754
5756 // This is a kind of template name, but can never occur in a dependent
5757 // scope (literal operators can only be declared at namespace scope).
5758 break;
5759
5760 default:
5761 break;
5762 }
5763
5764 // This name cannot possibly name a dependent template. Diagnose this now
5765 // rather than building a dependent template name that can never be valid.
5766 Diag(Name.getBeginLoc(),
5767 diag::err_template_kw_refers_to_dependent_non_template)
5768 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5769 << TemplateKWLoc.isValid() << TemplateKWLoc;
5770 return TNK_Non_template;
5771}
5772
5775 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5776 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5777 const TemplateArgument &Arg = AL.getArgument();
5778 QualType ArgType;
5779 TypeSourceInfo *TSI = nullptr;
5780
5781 // Check template type parameter.
5782 switch(Arg.getKind()) {
5784 // C++ [temp.arg.type]p1:
5785 // A template-argument for a template-parameter which is a
5786 // type shall be a type-id.
5787 ArgType = Arg.getAsType();
5788 TSI = AL.getTypeSourceInfo();
5789 break;
5792 // We have a template type parameter but the template argument
5793 // is a template without any arguments.
5794 SourceRange SR = AL.getSourceRange();
5797 return true;
5798 }
5800 // We have a template type parameter but the template argument is an
5801 // expression; see if maybe it is missing the "typename" keyword.
5802 CXXScopeSpec SS;
5803 DeclarationNameInfo NameInfo;
5804
5805 if (DependentScopeDeclRefExpr *ArgExpr =
5806 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5807 SS.Adopt(ArgExpr->getQualifierLoc());
5808 NameInfo = ArgExpr->getNameInfo();
5809 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5810 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5811 if (ArgExpr->isImplicitAccess()) {
5812 SS.Adopt(ArgExpr->getQualifierLoc());
5813 NameInfo = ArgExpr->getMemberNameInfo();
5814 }
5815 }
5816
5817 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5818 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5819 LookupParsedName(Result, CurScope, &SS);
5820
5821 if (Result.getAsSingle<TypeDecl>() ||
5822 Result.getResultKind() ==
5824 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5825 // Suggest that the user add 'typename' before the NNS.
5827 Diag(Loc, getLangOpts().MSVCCompat
5828 ? diag::ext_ms_template_type_arg_missing_typename
5829 : diag::err_template_arg_must_be_type_suggest)
5830 << FixItHint::CreateInsertion(Loc, "typename ");
5832
5833 // Recover by synthesizing a type using the location information that we
5834 // already have.
5836 SS.getScopeRep(), II);
5837 TypeLocBuilder TLB;
5839 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5841 TL.setNameLoc(NameInfo.getLoc());
5842 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5843
5844 // Overwrite our input TemplateArgumentLoc so that we can recover
5845 // properly.
5848
5849 break;
5850 }
5851 }
5852 // fallthrough
5853 [[fallthrough]];
5854 }
5855 default: {
5856 // We allow instantiateing a template with template argument packs when
5857 // building deduction guides.
5858 if (Arg.getKind() == TemplateArgument::Pack &&
5859 CodeSynthesisContexts.back().Kind ==
5861 SugaredConverted.push_back(Arg);
5862 CanonicalConverted.push_back(Arg);
5863 return false;
5864 }
5865 // We have a template type parameter but the template argument
5866 // is not a type.
5867 SourceRange SR = AL.getSourceRange();
5868 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5870
5871 return true;
5872 }
5873 }
5874
5875 if (CheckTemplateArgument(TSI))
5876 return true;
5877
5878 // Objective-C ARC:
5879 // If an explicitly-specified template argument type is a lifetime type
5880 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5881 if (getLangOpts().ObjCAutoRefCount &&
5882 ArgType->isObjCLifetimeType() &&
5883 !ArgType.getObjCLifetime()) {
5884 Qualifiers Qs;
5886 ArgType = Context.getQualifiedType(ArgType, Qs);
5887 }
5888
5889 SugaredConverted.push_back(TemplateArgument(ArgType));
5890 CanonicalConverted.push_back(
5892 return false;
5893}
5894
5895/// Substitute template arguments into the default template argument for
5896/// the given template type parameter.
5897///
5898/// \param SemaRef the semantic analysis object for which we are performing
5899/// the substitution.
5900///
5901/// \param Template the template that we are synthesizing template arguments
5902/// for.
5903///
5904/// \param TemplateLoc the location of the template name that started the
5905/// template-id we are checking.
5906///
5907/// \param RAngleLoc the location of the right angle bracket ('>') that
5908/// terminates the template-id.
5909///
5910/// \param Param the template template parameter whose default we are
5911/// substituting into.
5912///
5913/// \param Converted the list of template arguments provided for template
5914/// parameters that precede \p Param in the template parameter list.
5915/// \returns the substituted template argument, or NULL if an error occurred.
5917 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5918 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5919 ArrayRef<TemplateArgument> SugaredConverted,
5920 ArrayRef<TemplateArgument> CanonicalConverted) {
5921 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5922
5923 // If the argument type is dependent, instantiate it now based
5924 // on the previously-computed template arguments.
5925 if (ArgType->getType()->isInstantiationDependentType()) {
5926 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5927 SugaredConverted,
5928 SourceRange(TemplateLoc, RAngleLoc));
5929 if (Inst.isInvalid())
5930 return nullptr;
5931
5932 // Only substitute for the innermost template argument list.
5933 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5934 /*Final=*/true);
5935 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5936 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5937
5938 bool ForLambdaCallOperator = false;
5939 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5940 ForLambdaCallOperator = Rec->isLambda();
5941 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5942 !ForLambdaCallOperator);
5943 ArgType =
5944 SemaRef.SubstType(ArgType, TemplateArgLists,
5945 Param->getDefaultArgumentLoc(), Param->getDeclName());
5946 }
5947
5948 return ArgType;
5949}
5950
5951/// Substitute template arguments into the default template argument for
5952/// the given non-type template parameter.
5953///
5954/// \param SemaRef the semantic analysis object for which we are performing
5955/// the substitution.
5956///
5957/// \param Template the template that we are synthesizing template arguments
5958/// for.
5959///
5960/// \param TemplateLoc the location of the template name that started the
5961/// template-id we are checking.
5962///
5963/// \param RAngleLoc the location of the right angle bracket ('>') that
5964/// terminates the template-id.
5965///
5966/// \param Param the non-type template parameter whose default we are
5967/// substituting into.
5968///
5969/// \param Converted the list of template arguments provided for template
5970/// parameters that precede \p Param in the template parameter list.
5971///
5972/// \returns the substituted template argument, or NULL if an error occurred.
5974 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5975 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5976 ArrayRef<TemplateArgument> SugaredConverted,
5977 ArrayRef<TemplateArgument> CanonicalConverted) {
5978 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5979 SugaredConverted,
5980 SourceRange(TemplateLoc, RAngleLoc));
5981 if (Inst.isInvalid())
5982 return ExprError();
5983
5984 // Only substitute for the innermost template argument list.
5985 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5986 /*Final=*/true);
5987 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5988 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5989
5990 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5991 EnterExpressionEvaluationContext ConstantEvaluated(
5993 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5994}
5995
5996/// Substitute template arguments into the default template argument for
5997/// the given template template parameter.
5998///
5999/// \param SemaRef the semantic analysis object for which we are performing
6000/// the substitution.
6001///
6002/// \param Template the template that we are synthesizing template arguments
6003/// for.
6004///
6005/// \param TemplateLoc the location of the template name that started the
6006/// template-id we are checking.
6007///
6008/// \param RAngleLoc the location of the right angle bracket ('>') that
6009/// terminates the template-id.
6010///
6011/// \param Param the template template parameter whose default we are
6012/// substituting into.
6013///
6014/// \param Converted the list of template arguments provided for template
6015/// parameters that precede \p Param in the template parameter list.
6016///
6017/// \param QualifierLoc Will be set to the nested-name-specifier (with
6018/// source-location information) that precedes the template name.
6019///
6020/// \returns the substituted template argument, or NULL if an error occurred.
6022 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
6023 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
6024 ArrayRef<TemplateArgument> SugaredConverted,
6025 ArrayRef<TemplateArgument> CanonicalConverted,
6026 NestedNameSpecifierLoc &QualifierLoc) {
6028 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
6029 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
6030 if (Inst.isInvalid())
6031 return TemplateName();
6032
6033 // Only substitute for the innermost template argument list.
6034 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
6035 /*Final=*/true);
6036 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
6037 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
6038
6039 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
6040 // Substitute into the nested-name-specifier first,
6041 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
6042 if (QualifierLoc) {
6043 QualifierLoc =
6044 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
6045 if (!QualifierLoc)
6046 return TemplateName();
6047 }
6048
6049 return SemaRef.SubstTemplateName(
6050 QualifierLoc,
6053 TemplateArgLists);
6054}
6055
6056/// If the given template parameter has a default template
6057/// argument, substitute into that default template argument and
6058/// return the corresponding template argument.
6060 TemplateDecl *Template, SourceLocation TemplateLoc,
6061 SourceLocation RAngleLoc, Decl *Param,
6062 ArrayRef<TemplateArgument> SugaredConverted,
6063 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
6064 HasDefaultArg = false;
6065
6066 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
6067 if (!hasReachableDefaultArgument(TypeParm))
6068 return TemplateArgumentLoc();
6069
6070 HasDefaultArg = true;
6072 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
6073 CanonicalConverted);
6074 if (DI)
6075 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
6076
6077 return TemplateArgumentLoc();
6078 }
6079
6080 if (NonTypeTemplateParmDecl *NonTypeParm
6081 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6082 if (!hasReachableDefaultArgument(NonTypeParm))
6083 return TemplateArgumentLoc();
6084
6085 HasDefaultArg = true;
6087 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
6088 CanonicalConverted);
6089 if (Arg.isInvalid())
6090 return TemplateArgumentLoc();
6091
6092 Expr *ArgE = Arg.getAs<Expr>();
6093 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
6094 }
6095
6096 TemplateTemplateParmDecl *TempTempParm
6097 = cast<TemplateTemplateParmDecl>(Param);
6098 if (!hasReachableDefaultArgument(TempTempParm))
6099 return TemplateArgumentLoc();
6100
6101 HasDefaultArg = true;
6102 NestedNameSpecifierLoc QualifierLoc;
6104 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
6105 CanonicalConverted, QualifierLoc);
6106 if (TName.isNull())
6107 return TemplateArgumentLoc();
6108
6109 return TemplateArgumentLoc(
6110 Context, TemplateArgument(TName),
6112 TempTempParm->getDefaultArgument().getTemplateNameLoc());
6113}
6114
6115/// Convert a template-argument that we parsed as a type into a template, if
6116/// possible. C++ permits injected-class-names to perform dual service as
6117/// template template arguments and as template type arguments.
6120 // Extract and step over any surrounding nested-name-specifier.
6121 NestedNameSpecifierLoc QualLoc;
6122 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
6123 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
6124 return TemplateArgumentLoc();
6125
6126 QualLoc = ETLoc.getQualifierLoc();
6127 TLoc = ETLoc.getNamedTypeLoc();
6128 }
6129 // If this type was written as an injected-class-name, it can be used as a
6130 // template template argument.
6131 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
6132 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
6133 QualLoc, InjLoc.getNameLoc());
6134
6135 // If this type was written as an injected-class-name, it may have been
6136 // converted to a RecordType during instantiation. If the RecordType is
6137 // *not* wrapped in a TemplateSpecializationType and denotes a class
6138 // template specialization, it must have come from an injected-class-name.
6139 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
6140 if (auto *CTSD =
6141 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
6142 return TemplateArgumentLoc(Context,
6143 TemplateName(CTSD->getSpecializedTemplate()),
6144 QualLoc, RecLoc.getNameLoc());
6145
6146 return TemplateArgumentLoc();
6147}
6148
6149/// Check that the given template argument corresponds to the given
6150/// template parameter.
6151///
6152/// \param Param The template parameter against which the argument will be
6153/// checked.
6154///
6155/// \param Arg The template argument, which may be updated due to conversions.
6156///
6157/// \param Template The template in which the template argument resides.
6158///
6159/// \param TemplateLoc The location of the template name for the template
6160/// whose argument list we're matching.
6161///
6162/// \param RAngleLoc The location of the right angle bracket ('>') that closes
6163/// the template argument list.
6164///
6165/// \param ArgumentPackIndex The index into the argument pack where this
6166/// argument will be placed. Only valid if the parameter is a parameter pack.
6167///
6168/// \param Converted The checked, converted argument will be added to the
6169/// end of this small vector.
6170///
6171/// \param CTAK Describes how we arrived at this particular template argument:
6172/// explicitly written, deduced, etc.
6173///
6174/// \returns true on error, false otherwise.
6176 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
6177 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
6178 unsigned ArgumentPackIndex,
6179 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6180 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6182 // Check template type parameters.
6183 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
6184 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
6185 CanonicalConverted);
6186
6187 // Check non-type template parameters.
6188 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6189 // Do substitution on the type of the non-type template parameter
6190 // with the template arguments we've seen thus far. But if the
6191 // template has a dependent context then we cannot substitute yet.
6192 QualType NTTPType = NTTP->getType();
6193 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
6194 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
6195
6196 if (NTTPType->isInstantiationDependentType() &&
6197 !isa<TemplateTemplateParmDecl>(Template) &&
6198 !Template->getDeclContext()->isDependentContext()) {
6199 // Do substitution on the type of the non-type template parameter.
6200 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
6201 SugaredConverted,
6202 SourceRange(TemplateLoc, RAngleLoc));
6203 if (Inst.isInvalid())
6204 return true;
6205
6206 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
6207 /*Final=*/true);
6208 // If the parameter is a pack expansion, expand this slice of the pack.
6209 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
6211 ArgumentPackIndex);
6212 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
6213 NTTP->getDeclName());
6214 } else {
6215 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
6216 NTTP->getDeclName());
6217 }
6218
6219 // If that worked, check the non-type template parameter type
6220 // for validity.
6221 if (!NTTPType.isNull())
6222 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
6223 NTTP->getLocation());
6224 if (NTTPType.isNull())
6225 return true;
6226 }
6227
6228 switch (Arg.getArgument().getKind()) {
6230 llvm_unreachable("Should never see a NULL template argument here");
6231
6233 Expr *E = Arg.getArgument().getAsExpr();
6234 TemplateArgument SugaredResult, CanonicalResult;
6235 unsigned CurSFINAEErrors = NumSFINAEErrors;
6236 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
6237 CanonicalResult, CTAK);
6238 if (Res.isInvalid())
6239 return true;
6240 // If the current template argument causes an error, give up now.
6241 if (CurSFINAEErrors < NumSFINAEErrors)
6242 return true;
6243
6244 // If the resulting expression is new, then use it in place of the
6245 // old expression in the template argument.
6246 if (Res.get() != E) {
6247 TemplateArgument TA(Res.get());
6248 Arg = TemplateArgumentLoc(TA, Res.get());
6249 }
6250
6251 SugaredConverted.push_back(SugaredResult);
6252 CanonicalConverted.push_back(CanonicalResult);
6253 break;
6254 }
6255
6260 // We've already checked this template argument, so just copy
6261 // it to the list of converted arguments.
6262 SugaredConverted.push_back(Arg.getArgument());
6263 CanonicalConverted.push_back(
6265 break;
6266
6269 // We were given a template template argument. It may not be ill-formed;
6270 // see below.
6271 if (DependentTemplateName *DTN
6274 // We have a template argument such as \c T::template X, which we
6275 // parsed as a template template argument. However, since we now
6276 // know that we need a non-type template argument, convert this
6277 // template name into an expression.
6278
6279 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
6280 Arg.getTemplateNameLoc());
6281
6282 CXXScopeSpec SS;
6284 // FIXME: the template-template arg was a DependentTemplateName,
6285 // so it was provided with a template keyword. However, its source
6286 // location is not stored in the template argument structure.
6287 SourceLocation TemplateKWLoc;
6289 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
6290 nullptr);
6291
6292 // If we parsed the template argument as a pack expansion, create a
6293 // pack expansion expression.
6296 if (E.isInvalid())
6297 return true;
6298 }
6299
6300 TemplateArgument SugaredResult, CanonicalResult;
6301 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
6302 CanonicalResult, CTAK_Specified);
6303 if (E.isInvalid())
6304 return true;
6305
6306 SugaredConverted.push_back(SugaredResult);
6307 CanonicalConverted.push_back(CanonicalResult);
6308 break;
6309 }
6310
6311 // We have a template argument that actually does refer to a class
6312 // template, alias template, or template template parameter, and
6313 // therefore cannot be a non-type template argument.
6314 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
6315 << Arg.getSourceRange();
6317
6318 return true;
6319
6321 // We have a non-type template parameter but the template
6322 // argument is a type.
6323
6324 // C++ [temp.arg]p2:
6325 // In a template-argument, an ambiguity between a type-id and
6326 // an expression is resolved to a type-id, regardless of the
6327 // form of the corresponding template-parameter.
6328 //
6329 // We warn specifically about this case, since it can be rather
6330 // confusing for users.
6331 QualType T = Arg.getArgument().getAsType();
6332 SourceRange SR = Arg.getSourceRange();
6333 if (T->isFunctionType())
6334 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
6335 else
6336 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
6338 return true;
6339 }
6340
6342 llvm_unreachable("Caller must expand template argument packs");
6343 }
6344
6345 return false;
6346 }
6347
6348
6349 // Check template template parameters.
6350 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
6351
6352 TemplateParameterList *Params = TempParm->getTemplateParameters();
6353 if (TempParm->isExpandedParameterPack())
6354 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
6355
6356 // Substitute into the template parameter list of the template
6357 // template parameter, since previously-supplied template arguments
6358 // may appear within the template template parameter.
6359 //
6360 // FIXME: Skip this if the parameters aren't instantiation-dependent.
6361 {
6362 // Set up a template instantiation context.
6364 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
6365 SugaredConverted,
6366 SourceRange(TemplateLoc, RAngleLoc));
6367 if (Inst.isInvalid())
6368 return true;
6369
6370 Params =
6373 Template, SugaredConverted, /*Final=*/true),
6374 /*EvaluateConstraints=*/false);
6375 if (!Params)
6376 return true;
6377 }
6378
6379 // C++1z [temp.local]p1: (DR1004)
6380 // When [the injected-class-name] is used [...] as a template-argument for
6381 // a template template-parameter [...] it refers to the class template
6382 // itself.
6386 if (!ConvertedArg.getArgument().isNull())
6387 Arg = ConvertedArg;
6388 }
6389
6390 switch (Arg.getArgument().getKind()) {
6392 llvm_unreachable("Should never see a NULL template argument here");
6393
6396 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
6397 return true;
6398
6399 SugaredConverted.push_back(Arg.getArgument());
6400 CanonicalConverted.push_back(
6402 break;
6403
6406 // We have a template template parameter but the template
6407 // argument does not refer to a template.
6408 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
6409 << getLangOpts().CPlusPlus11;
6410 return true;
6411
6416 llvm_unreachable("non-type argument with template template parameter");
6417
6419 llvm_unreachable("Caller must expand template argument packs");
6420 }
6421
6422 return false;
6423}
6424
6425/// Diagnose a missing template argument.
6426template<typename TemplateParmDecl>
6428 TemplateDecl *TD,
6429 const TemplateParmDecl *D,
6431 // Dig out the most recent declaration of the template parameter; there may be
6432 // declarations of the template that are more recent than TD.
6433 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
6434 ->getTemplateParameters()
6435 ->getParam(D->getIndex()));
6436
6437 // If there's a default argument that's not reachable, diagnose that we're
6438 // missing a module import.
6440 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
6441 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
6442 D->getDefaultArgumentLoc(), Modules,
6444 /*Recover*/true);
6445 return true;
6446 }
6447
6448 // FIXME: If there's a more recent default argument that *is* visible,
6449 // diagnose that it was declared too late.
6450
6452
6453 S.Diag(Loc, diag::err_template_arg_list_different_arity)
6454 << /*not enough args*/0
6456 << TD;
6457 S.NoteTemplateLocation(*TD, Params->getSourceRange());
6458 return true;
6459}
6460
6461/// Check that the given template argument list is well-formed
6462/// for specializing the given template.
6464 TemplateDecl *Template, SourceLocation TemplateLoc,
6465 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
6466 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6467 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6468 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
6469
6471 *ConstraintsNotSatisfied = false;
6472
6473 // Make a copy of the template arguments for processing. Only make the
6474 // changes at the end when successful in matching the arguments to the
6475 // template.
6476 TemplateArgumentListInfo NewArgs = TemplateArgs;
6477
6479
6480 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
6481
6482 // C++ [temp.arg]p1:
6483 // [...] The type and form of each template-argument specified in
6484 // a template-id shall match the type and form specified for the
6485 // corresponding parameter declared by the template in its
6486 // template-parameter-list.
6487 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
6488 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
6489 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
6490 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
6491 LocalInstantiationScope InstScope(*this, true);
6492 for (TemplateParameterList::iterator Param = Params->begin(),
6493 ParamEnd = Params->end();
6494 Param != ParamEnd; /* increment in loop */) {
6495 // If we have an expanded parameter pack, make sure we don't have too
6496 // many arguments.
6497 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
6498 if (*Expansions == SugaredArgumentPack.size()) {
6499 // We're done with this parameter pack. Pack up its arguments and add
6500 // them to the list.
6501 SugaredConverted.push_back(
6502 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6503 SugaredArgumentPack.clear();
6504
6505 CanonicalConverted.push_back(
6506 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6507 CanonicalArgumentPack.clear();
6508
6509 // This argument is assigned to the next parameter.
6510 ++Param;
6511 continue;
6512 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6513 // Not enough arguments for this parameter pack.
6514 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6515 << /*not enough args*/0
6517 << Template;
6518 NoteTemplateLocation(*Template, Params->getSourceRange());
6519 return true;
6520 }
6521 }
6522
6523 if (ArgIdx < NumArgs) {
6524 // Check the template argument we were given.
6525 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6526 RAngleLoc, SugaredArgumentPack.size(),
6527 SugaredConverted, CanonicalConverted,
6529 return true;
6530
6531 CanonicalConverted.back().setIsDefaulted(
6533 Context, NewArgs[ArgIdx].getArgument(), *Param,
6534 CanonicalConverted, Params->getDepth()));
6535
6536 bool PackExpansionIntoNonPack =
6537 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6538 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
6539 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
6540 isa<ConceptDecl>(Template))) {
6541 // Core issue 1430: we have a pack expansion as an argument to an
6542 // alias template, and it's not part of a parameter pack. This
6543 // can't be canonicalized, so reject it now.
6544 // As for concepts - we cannot normalize constraints where this
6545 // situation exists.
6546 Diag(NewArgs[ArgIdx].getLocation(),
6547 diag::err_template_expansion_into_fixed_list)
6548 << (isa<ConceptDecl>(Template) ? 1 : 0)
6549 << NewArgs[ArgIdx].getSourceRange();
6551 return true;
6552 }
6553
6554 // We're now done with this argument.
6555 ++ArgIdx;
6556
6557 if ((*Param)->isTemplateParameterPack()) {
6558 // The template parameter was a template parameter pack, so take the
6559 // deduced argument and place it on the argument pack. Note that we
6560 // stay on the same template parameter so that we can deduce more
6561 // arguments.
6562 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
6563 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
6564 } else {
6565 // Move to the next template parameter.
6566 ++Param;
6567 }
6568
6569 // If we just saw a pack expansion into a non-pack, then directly convert
6570 // the remaining arguments, because we don't know what parameters they'll
6571 // match up with.
6572 if (PackExpansionIntoNonPack) {
6573 if (!SugaredArgumentPack.empty()) {
6574 // If we were part way through filling in an expanded parameter pack,
6575 // fall back to just producing individual arguments.
6576 SugaredConverted.insert(SugaredConverted.end(),
6577 SugaredArgumentPack.begin(),
6578 SugaredArgumentPack.end());
6579 SugaredArgumentPack.clear();
6580
6581 CanonicalConverted.insert(CanonicalConverted.end(),
6582 CanonicalArgumentPack.begin(),
6583 CanonicalArgumentPack.end());
6584 CanonicalArgumentPack.clear();
6585 }
6586
6587 while (ArgIdx < NumArgs) {
6588 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6589 SugaredConverted.push_back(Arg);
6590 CanonicalConverted.push_back(
6592 ++ArgIdx;
6593 }
6594
6595 return false;
6596 }
6597
6598 continue;
6599 }
6600
6601 // If we're checking a partial template argument list, we're done.
6602 if (PartialTemplateArgs) {
6603 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6604 SugaredConverted.push_back(
6605 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6606 CanonicalConverted.push_back(
6607 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6608 }
6609 return false;
6610 }
6611
6612 // If we have a template parameter pack with no more corresponding
6613 // arguments, just break out now and we'll fill in the argument pack below.
6614 if ((*Param)->isTemplateParameterPack()) {
6615 assert(!getExpandedPackSize(*Param) &&
6616 "Should have dealt with this already");
6617
6618 // A non-expanded parameter pack before the end of the parameter list
6619 // only occurs for an ill-formed template parameter list, unless we've
6620 // got a partial argument list for a function template, so just bail out.
6621 if (Param + 1 != ParamEnd) {
6622 assert(
6623 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6624 "Concept templates must have parameter packs at the end.");
6625 return true;
6626 }
6627
6628 SugaredConverted.push_back(
6629 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6630 SugaredArgumentPack.clear();
6631
6632 CanonicalConverted.push_back(
6633 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6634 CanonicalArgumentPack.clear();
6635
6636 ++Param;
6637 continue;
6638 }
6639
6640 // Check whether we have a default argument.
6642
6643 // Retrieve the default template argument from the template
6644 // parameter. For each kind of template parameter, we substitute the
6645 // template arguments provided thus far and any "outer" template arguments
6646 // (when the template parameter was part of a nested template) into
6647 // the default argument.
6648 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6650 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6651 NewArgs);
6652
6654 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6655 CanonicalConverted);
6656 if (!ArgType)
6657 return true;
6658
6660 ArgType);
6661 } else if (NonTypeTemplateParmDecl *NTTP
6662 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6663 if (!hasReachableDefaultArgument(NTTP))
6664 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6665 NewArgs);
6666
6668 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6669 CanonicalConverted);
6670 if (E.isInvalid())
6671 return true;
6672
6673 Expr *Ex = E.getAs<Expr>();
6675 } else {
6676 TemplateTemplateParmDecl *TempParm
6677 = cast<TemplateTemplateParmDecl>(*Param);
6678
6679 if (!hasReachableDefaultArgument(TempParm))
6680 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6681 NewArgs);
6682
6683 NestedNameSpecifierLoc QualifierLoc;
6685 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6686 CanonicalConverted, QualifierLoc);
6687 if (Name.isNull())
6688 return true;
6689
6690 Arg = TemplateArgumentLoc(
6691 Context, TemplateArgument(Name), QualifierLoc,
6693 }
6694
6695 // Introduce an instantiation record that describes where we are using
6696 // the default template argument. We're not actually instantiating a
6697 // template here, we just create this object to put a note into the
6698 // context stack.
6699 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6700 SugaredConverted,
6701 SourceRange(TemplateLoc, RAngleLoc));
6702 if (Inst.isInvalid())
6703 return true;
6704
6705 // Check the default template argument.
6706 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6707 SugaredConverted, CanonicalConverted,
6709 return true;
6710
6711 CanonicalConverted.back().setIsDefaulted(true);
6712
6713 // Core issue 150 (assumed resolution): if this is a template template
6714 // parameter, keep track of the default template arguments from the
6715 // template definition.
6716 if (isTemplateTemplateParameter)
6717 NewArgs.addArgument(Arg);
6718
6719 // Move to the next template parameter and argument.
6720 ++Param;
6721 ++ArgIdx;
6722 }
6723
6724 // If we're performing a partial argument substitution, allow any trailing
6725 // pack expansions; they might be empty. This can happen even if
6726 // PartialTemplateArgs is false (the list of arguments is complete but
6727 // still dependent).
6728 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6730 while (ArgIdx < NumArgs &&
6731 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6732 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6733 SugaredConverted.push_back(Arg);
6734 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6735 }
6736 }
6737
6738 // If we have any leftover arguments, then there were too many arguments.
6739 // Complain and fail.
6740 if (ArgIdx < NumArgs) {
6741 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6742 << /*too many args*/1
6744 << Template
6745 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6746 NoteTemplateLocation(*Template, Params->getSourceRange());
6747 return true;
6748 }
6749
6750 // No problems found with the new argument list, propagate changes back
6751 // to caller.
6752 if (UpdateArgsWithConversions)
6753 TemplateArgs = std::move(NewArgs);
6754
6755 if (!PartialTemplateArgs) {
6756 // Setup the context/ThisScope for the case where we are needing to
6757 // re-instantiate constraints outside of normal instantiation.
6758 DeclContext *NewContext = Template->getDeclContext();
6759
6760 // If this template is in a template, make sure we extract the templated
6761 // decl.
6762 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6763 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6764 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6765
6766 Qualifiers ThisQuals;
6767 if (const auto *Method =
6768 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6769 ThisQuals = Method->getMethodQualifiers();
6770
6771 ContextRAII Context(*this, NewContext);
6772 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6773
6775 Template, NewContext, /*Final=*/false, CanonicalConverted,
6776 /*RelativeToPrimary=*/true,
6777 /*Pattern=*/nullptr,
6778 /*ForConceptInstantiation=*/true);
6780 Template, MLTAL,
6781 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6784 return true;
6785 }
6786 }
6787
6788 return false;
6789}
6790
6791namespace {
6792 class UnnamedLocalNoLinkageFinder
6793 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6794 {
6795 Sema &S;
6796 SourceRange SR;
6797
6799
6800 public:
6801 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6802
6803 bool Visit(QualType T) {
6804 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6805 }
6806
6807#define TYPE(Class, Parent) \
6808 bool Visit##Class##Type(const Class##Type *);
6809#define ABSTRACT_TYPE(Class, Parent) \
6810 bool Visit##Class##Type(const Class##Type *) { return false; }
6811#define NON_CANONICAL_TYPE(Class, Parent) \
6812 bool Visit##Class##Type(const Class##Type *) { return false; }
6813#include "clang/AST/TypeNodes.inc"
6814
6815 bool VisitTagDecl(const TagDecl *Tag);
6816 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6817 };
6818} // end anonymous namespace
6819
6820bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6821 return false;
6822}
6823
6824bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6825 return Visit(T->getElementType());
6826}
6827
6828bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6829 return Visit(T->getPointeeType());
6830}
6831
6832bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6833 const BlockPointerType* T) {
6834 return Visit(T->getPointeeType());
6835}
6836
6837bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6838 const LValueReferenceType* T) {
6839 return Visit(T->getPointeeType());
6840}
6841
6842bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6843 const RValueReferenceType* T) {
6844 return Visit(T->getPointeeType());
6845}
6846
6847bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6848 const MemberPointerType* T) {
6849 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6850}
6851
6852bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6853 const ConstantArrayType* T) {
6854 return Visit(T->getElementType());
6855}
6856
6857bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6858 const IncompleteArrayType* T) {
6859 return Visit(T->getElementType());
6860}
6861
6862bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6863 const VariableArrayType* T) {
6864 return Visit(T->getElementType());
6865}
6866
6867bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6868 const DependentSizedArrayType* T) {
6869 return Visit(T->getElementType());
6870}
6871
6872bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6874 return Visit(T->getElementType());
6875}
6876
6877bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6878 const DependentSizedMatrixType *T) {
6879 return Visit(T->getElementType());
6880}
6881
6882bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6884 return Visit(T->getPointeeType());
6885}
6886
6887bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6888 return Visit(T->getElementType());
6889}
6890
6891bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6892 const DependentVectorType *T) {
6893 return Visit(T->getElementType());
6894}
6895
6896bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6897 return Visit(T->getElementType());
6898}
6899
6900bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6901 const ConstantMatrixType *T) {
6902 return Visit(T->getElementType());
6903}
6904
6905bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6906 const FunctionProtoType* T) {
6907 for (const auto &A : T->param_types()) {
6908 if (Visit(A))
6909 return true;
6910 }
6911
6912 return Visit(T->getReturnType());
6913}
6914
6915bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6916 const FunctionNoProtoType* T) {
6917 return Visit(T->getReturnType());
6918}
6919
6920bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6921 const UnresolvedUsingType*) {
6922 return false;
6923}
6924
6925bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6926 return false;
6927}
6928
6929bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6930 return Visit(T->getUnmodifiedType());
6931}
6932
6933bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6934 return false;
6935}
6936
6937bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6938 const PackIndexingType *) {
6939 return false;
6940}
6941
6942bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6943 const UnaryTransformType*) {
6944 return false;
6945}
6946
6947bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6948 return Visit(T->getDeducedType());
6949}
6950
6951bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6953 return Visit(T->getDeducedType());
6954}
6955
6956bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6957 return VisitTagDecl(T->getDecl());
6958}
6959
6960bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6961 return VisitTagDecl(T->getDecl());
6962}
6963
6964bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6965 const TemplateTypeParmType*) {
6966 return false;
6967}
6968
6969bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6971 return false;
6972}
6973
6974bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6976 return false;
6977}
6978
6979bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6980 const InjectedClassNameType* T) {
6981 return VisitTagDecl(T->getDecl());
6982}
6983
6984bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6985 const DependentNameType* T) {
6986 return VisitNestedNameSpecifier(T->getQualifier());
6987}
6988
6989bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6991 if (auto *Q = T->getQualifier())
6992 return VisitNestedNameSpecifier(Q);
6993 return false;
6994}
6995
6996bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6997 const PackExpansionType* T) {
6998 return Visit(T->getPattern());
6999}
7000
7001bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
7002 return false;
7003}
7004
7005bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
7006 const ObjCInterfaceType *) {
7007 return false;
7008}
7009
7010bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
7011 const ObjCObjectPointerType *) {
7012 return false;
7013}
7014
7015bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
7016 return Visit(T->getValueType());
7017}
7018
7019bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
7020 return false;
7021}
7022
7023bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
7024 return false;
7025}
7026
7027bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
7028 const ArrayParameterType *T) {
7029 return VisitConstantArrayType(T);
7030}
7031
7032bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
7033 const DependentBitIntType *T) {
7034 return false;
7035}
7036
7037bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
7038 if (Tag->getDeclContext()->isFunctionOrMethod()) {
7039 S.Diag(SR.getBegin(),
7040 S.getLangOpts().CPlusPlus11 ?
7041 diag::warn_cxx98_compat_template_arg_local_type :
7042 diag::ext_template_arg_local_type)
7043 << S.Context.getTypeDeclType(Tag) << SR;
7044 return true;
7045 }
7046
7047 if (!Tag->hasNameForLinkage()) {
7048 S.Diag(SR.getBegin(),
7049 S.getLangOpts().CPlusPlus11 ?
7050 diag::warn_cxx98_compat_template_arg_unnamed_type :
7051 diag::ext_template_arg_unnamed_type) << SR;
7052 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
7053 return true;
7054 }
7055
7056 return false;
7057}
7058
7059bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
7060 NestedNameSpecifier *NNS) {
7061 assert(NNS);
7062 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
7063 return true;
7064
7065 switch (NNS->getKind()) {
7071 return false;
7072
7075 return Visit(QualType(NNS->getAsType(), 0));
7076 }
7077 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7078}
7079
7080/// Check a template argument against its corresponding
7081/// template type parameter.
7082///
7083/// This routine implements the semantics of C++ [temp.arg.type]. It
7084/// returns true if an error occurred, and false otherwise.
7086 assert(ArgInfo && "invalid TypeSourceInfo");
7087 QualType Arg = ArgInfo->getType();
7088 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
7089 QualType CanonArg = Context.getCanonicalType(Arg);
7090
7091 if (CanonArg->isVariablyModifiedType()) {
7092 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
7094 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
7095 }
7096
7097 // C++03 [temp.arg.type]p2:
7098 // A local type, a type with no linkage, an unnamed type or a type
7099 // compounded from any of these types shall not be used as a
7100 // template-argument for a template type-parameter.
7101 //
7102 // C++11 allows these, and even in C++03 we allow them as an extension with
7103 // a warning.
7104 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
7105 UnnamedLocalNoLinkageFinder Finder(*this, SR);
7106 (void)Finder.Visit(CanonArg);
7107 }
7108
7109 return false;
7110}
7111
7115 NPV_Error
7117
7118/// Determine whether the given template argument is a null pointer
7119/// value of the appropriate type.
7122 QualType ParamType, Expr *Arg,
7123 Decl *Entity = nullptr) {
7124 if (Arg->isValueDependent() || Arg->isTypeDependent())
7125 return NPV_NotNullPointer;
7126
7127 // dllimport'd entities aren't constant but are available inside of template
7128 // arguments.
7129 if (Entity && Entity->hasAttr<DLLImportAttr>())
7130 return NPV_NotNullPointer;
7131
7132 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
7133 llvm_unreachable(
7134 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
7135
7136 if (!S.getLangOpts().CPlusPlus11)
7137 return NPV_NotNullPointer;
7138
7139 // Determine whether we have a constant expression.
7141 if (ArgRV.isInvalid())
7142 return NPV_Error;
7143 Arg = ArgRV.get();
7144
7145 Expr::EvalResult EvalResult;
7147 EvalResult.Diag = &Notes;
7148 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
7149 EvalResult.HasSideEffects) {
7150 SourceLocation DiagLoc = Arg->getExprLoc();
7151
7152 // If our only note is the usual "invalid subexpression" note, just point
7153 // the caret at its location rather than producing an essentially
7154 // redundant note.
7155 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7156 diag::note_invalid_subexpr_in_const_expr) {
7157 DiagLoc = Notes[0].first;
7158 Notes.clear();
7159 }
7160
7161 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
7162 << Arg->getType() << Arg->getSourceRange();
7163 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7164 S.Diag(Notes[I].first, Notes[I].second);
7165
7167 return NPV_Error;
7168 }
7169
7170 // C++11 [temp.arg.nontype]p1:
7171 // - an address constant expression of type std::nullptr_t
7172 if (Arg->getType()->isNullPtrType())
7173 return NPV_NullPointer;
7174
7175 // - a constant expression that evaluates to a null pointer value (4.10); or
7176 // - a constant expression that evaluates to a null member pointer value
7177 // (4.11); or
7178 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
7179 (EvalResult.Val.isMemberPointer() &&
7180 !EvalResult.Val.getMemberPointerDecl())) {
7181 // If our expression has an appropriate type, we've succeeded.
7182 bool ObjCLifetimeConversion;
7183 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
7184 S.IsQualificationConversion(Arg->getType(), ParamType, false,
7185 ObjCLifetimeConversion))
7186 return NPV_NullPointer;
7187
7188 // The types didn't match, but we know we got a null pointer; complain,
7189 // then recover as if the types were correct.
7190 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
7191 << Arg->getType() << ParamType << Arg->getSourceRange();
7193 return NPV_NullPointer;
7194 }
7195
7196 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
7197 // We found a pointer that isn't null, but doesn't refer to an object.
7198 // We could just return NPV_NotNullPointer, but we can print a better
7199 // message with the information we have here.
7200 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
7201 << EvalResult.Val.getAsString(S.Context, ParamType);
7203 return NPV_Error;
7204 }
7205
7206 // If we don't have a null pointer value, but we do have a NULL pointer
7207 // constant, suggest a cast to the appropriate type.
7209 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
7210 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
7211 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
7213 ")");
7215 return NPV_NullPointer;
7216 }
7217
7218 // FIXME: If we ever want to support general, address-constant expressions
7219 // as non-type template arguments, we should return the ExprResult here to
7220 // be interpreted by the caller.
7221 return NPV_NotNullPointer;
7222}
7223
7224/// Checks whether the given template argument is compatible with its
7225/// template parameter.
7227 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7228 Expr *Arg, QualType ArgType) {
7229 bool ObjCLifetimeConversion;
7230 if (ParamType->isPointerType() &&
7231 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
7232 S.IsQualificationConversion(ArgType, ParamType, false,
7233 ObjCLifetimeConversion)) {
7234 // For pointer-to-object types, qualification conversions are
7235 // permitted.
7236 } else {
7237 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
7238 if (!ParamRef->getPointeeType()->isFunctionType()) {
7239 // C++ [temp.arg.nontype]p5b3:
7240 // For a non-type template-parameter of type reference to
7241 // object, no conversions apply. The type referred to by the
7242 // reference may be more cv-qualified than the (otherwise
7243 // identical) type of the template- argument. The
7244 // template-parameter is bound directly to the
7245 // template-argument, which shall be an lvalue.
7246
7247 // FIXME: Other qualifiers?
7248 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
7249 unsigned ArgQuals = ArgType.getCVRQualifiers();
7250
7251 if ((ParamQuals | ArgQuals) != ParamQuals) {
7252 S.Diag(Arg->getBeginLoc(),
7253 diag::err_template_arg_ref_bind_ignores_quals)
7254 << ParamType << Arg->getType() << Arg->getSourceRange();
7256 return true;
7257 }
7258 }
7259 }
7260
7261 // At this point, the template argument refers to an object or
7262 // function with external linkage. We now need to check whether the
7263 // argument and parameter types are compatible.
7264 if (!S.Context.hasSameUnqualifiedType(ArgType,
7265 ParamType.getNonReferenceType())) {
7266 // We can't perform this conversion or binding.
7267 if (ParamType->isReferenceType())
7268 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
7269 << ParamType << ArgIn->getType() << Arg->getSourceRange();
7270 else
7271 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7272 << ArgIn->getType() << ParamType << Arg->getSourceRange();
7274 return true;
7275 }
7276 }
7277
7278 return false;
7279}
7280
7281/// Checks whether the given template argument is the address
7282/// of an object or function according to C++ [temp.arg.nontype]p1.
7284 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7285 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7286 bool Invalid = false;
7287 Expr *Arg = ArgIn;
7288 QualType ArgType = Arg->getType();
7289
7290 bool AddressTaken = false;
7291 SourceLocation AddrOpLoc;
7292 if (S.getLangOpts().MicrosoftExt) {
7293 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
7294 // dereference and address-of operators.
7295 Arg = Arg->IgnoreParenCasts();
7296
7297 bool ExtWarnMSTemplateArg = false;
7298 UnaryOperatorKind FirstOpKind;
7299 SourceLocation FirstOpLoc;
7300 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7301 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
7302 if (UnOpKind == UO_Deref)
7303 ExtWarnMSTemplateArg = true;
7304 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
7305 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
7306 if (!AddrOpLoc.isValid()) {
7307 FirstOpKind = UnOpKind;
7308 FirstOpLoc = UnOp->getOperatorLoc();
7309 }
7310 } else
7311 break;
7312 }
7313 if (FirstOpLoc.isValid()) {
7314 if (ExtWarnMSTemplateArg)
7315 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
7316 << ArgIn->getSourceRange();
7317
7318 if (FirstOpKind == UO_AddrOf)
7319 AddressTaken = true;
7320 else if (Arg->getType()->isPointerType()) {
7321 // We cannot let pointers get dereferenced here, that is obviously not a
7322 // constant expression.
7323 assert(FirstOpKind == UO_Deref);
7324 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7325 << Arg->getSourceRange();
7326 }
7327 }
7328 } else {
7329 // See through any implicit casts we added to fix the type.
7330 Arg = Arg->IgnoreImpCasts();
7331
7332 // C++ [temp.arg.nontype]p1:
7333 //
7334 // A template-argument for a non-type, non-template
7335 // template-parameter shall be one of: [...]
7336 //
7337 // -- the address of an object or function with external
7338 // linkage, including function templates and function
7339 // template-ids but excluding non-static class members,
7340 // expressed as & id-expression where the & is optional if
7341 // the name refers to a function or array, or if the
7342 // corresponding template-parameter is a reference; or
7343
7344 // In C++98/03 mode, give an extension warning on any extra parentheses.
7345 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7346 bool ExtraParens = false;
7347 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7348 if (!Invalid && !ExtraParens) {
7349 S.Diag(Arg->getBeginLoc(),
7350 S.getLangOpts().CPlusPlus11
7351 ? diag::warn_cxx98_compat_template_arg_extra_parens
7352 : diag::ext_template_arg_extra_parens)
7353 << Arg->getSourceRange();
7354 ExtraParens = true;
7355 }
7356
7357 Arg = Parens->getSubExpr();
7358 }
7359
7360 while (SubstNonTypeTemplateParmExpr *subst =
7361 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7362 Arg = subst->getReplacement()->IgnoreImpCasts();
7363
7364 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7365 if (UnOp->getOpcode() == UO_AddrOf) {
7366 Arg = UnOp->getSubExpr();
7367 AddressTaken = true;
7368 AddrOpLoc = UnOp->getOperatorLoc();
7369 }
7370 }
7371
7372 while (SubstNonTypeTemplateParmExpr *subst =
7373 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7374 Arg = subst->getReplacement()->IgnoreImpCasts();
7375 }
7376
7377 ValueDecl *Entity = nullptr;
7378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
7379 Entity = DRE->getDecl();
7380 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
7381 Entity = CUE->getGuidDecl();
7382
7383 // If our parameter has pointer type, check for a null template value.
7384 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
7385 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
7386 Entity)) {
7387 case NPV_NullPointer:
7388 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7389 SugaredConverted = TemplateArgument(ParamType,
7390 /*isNullPtr=*/true);
7391 CanonicalConverted =
7393 /*isNullPtr=*/true);
7394 return false;
7395
7396 case NPV_Error:
7397 return true;
7398
7399 case NPV_NotNullPointer:
7400 break;
7401 }
7402 }
7403
7404 // Stop checking the precise nature of the argument if it is value dependent,
7405 // it should be checked when instantiated.
7406 if (Arg->isValueDependent()) {
7407 SugaredConverted = TemplateArgument(ArgIn);
7408 CanonicalConverted =
7409 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7410 return false;
7411 }
7412
7413 if (!Entity) {
7414 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7415 << Arg->getSourceRange();
7417 return true;
7418 }
7419
7420 // Cannot refer to non-static data members
7421 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
7422 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
7423 << Entity << Arg->getSourceRange();
7425 return true;
7426 }
7427
7428 // Cannot refer to non-static member functions
7429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
7430 if (!Method->isStatic()) {
7431 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
7432 << Method << Arg->getSourceRange();
7434 return true;
7435 }
7436 }
7437
7438 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
7439 VarDecl *Var = dyn_cast<VarDecl>(Entity);
7440 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
7441
7442 // A non-type template argument must refer to an object or function.
7443 if (!Func && !Var && !Guid) {
7444 // We found something, but we don't know specifically what it is.
7445 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
7446 << Arg->getSourceRange();
7447 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
7448 return true;
7449 }
7450
7451 // Address / reference template args must have external linkage in C++98.
7452 if (Entity->getFormalLinkage() == Linkage::Internal) {
7453 S.Diag(Arg->getBeginLoc(),
7454 S.getLangOpts().CPlusPlus11
7455 ? diag::warn_cxx98_compat_template_arg_object_internal
7456 : diag::ext_template_arg_object_internal)
7457 << !Func << Entity << Arg->getSourceRange();
7458 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7459 << !Func;
7460 } else if (!Entity->hasLinkage()) {
7461 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
7462 << !Func << Entity << Arg->getSourceRange();
7463 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7464 << !Func;
7465 return true;
7466 }
7467
7468 if (Var) {
7469 // A value of reference type is not an object.
7470 if (Var->getType()->isReferenceType()) {
7471 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
7472 << Var->getType() << Arg->getSourceRange();
7474 return true;
7475 }
7476
7477 // A template argument must have static storage duration.
7478 if (Var->getTLSKind()) {
7479 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7480 << Arg->getSourceRange();
7481 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7482 return true;
7483 }
7484 }
7485
7486 if (AddressTaken && ParamType->isReferenceType()) {
7487 // If we originally had an address-of operator, but the
7488 // parameter has reference type, complain and (if things look
7489 // like they will work) drop the address-of operator.
7490 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
7491 ParamType.getNonReferenceType())) {
7492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7493 << ParamType;
7495 return true;
7496 }
7497
7498 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7499 << ParamType
7500 << FixItHint::CreateRemoval(AddrOpLoc);
7502
7503 ArgType = Entity->getType();
7504 }
7505
7506 // If the template parameter has pointer type, either we must have taken the
7507 // address or the argument must decay to a pointer.
7508 if (!AddressTaken && ParamType->isPointerType()) {
7509 if (Func) {
7510 // Function-to-pointer decay.
7511 ArgType = S.Context.getPointerType(Func->getType());
7512 } else if (Entity->getType()->isArrayType()) {
7513 // Array-to-pointer decay.
7514 ArgType = S.Context.getArrayDecayedType(Entity->getType());
7515 } else {
7516 // If the template parameter has pointer type but the address of
7517 // this object was not taken, complain and (possibly) recover by
7518 // taking the address of the entity.
7519 ArgType = S.Context.getPointerType(Entity->getType());
7520 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
7521 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7522 << ParamType;
7524 return true;
7525 }
7526
7527 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7528 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7529
7531 }
7532 }
7533
7534 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7535 Arg, ArgType))
7536 return true;
7537
7538 // Create the template argument.
7539 SugaredConverted = TemplateArgument(Entity, ParamType);
7540 CanonicalConverted =
7541 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7542 S.Context.getCanonicalType(ParamType));
7543 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
7544 return false;
7545}
7546
7547/// Checks whether the given template argument is a pointer to
7548/// member constant according to C++ [temp.arg.nontype]p1.
7549static bool
7551 QualType ParamType, Expr *&ResultArg,
7552 TemplateArgument &SugaredConverted,
7553 TemplateArgument &CanonicalConverted) {
7554 bool Invalid = false;
7555
7556 Expr *Arg = ResultArg;
7557 bool ObjCLifetimeConversion;
7558
7559 // C++ [temp.arg.nontype]p1:
7560 //
7561 // A template-argument for a non-type, non-template
7562 // template-parameter shall be one of: [...]
7563 //
7564 // -- a pointer to member expressed as described in 5.3.1.
7565 DeclRefExpr *DRE = nullptr;
7566
7567 // In C++98/03 mode, give an extension warning on any extra parentheses.
7568 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7569 bool ExtraParens = false;
7570 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
7571 if (!Invalid && !ExtraParens) {
7572 S.Diag(Arg->getBeginLoc(),
7573 S.getLangOpts().CPlusPlus11
7574 ? diag::warn_cxx98_compat_template_arg_extra_parens
7575 : diag::ext_template_arg_extra_parens)
7576 << Arg->getSourceRange();
7577 ExtraParens = true;
7578 }
7579
7580 Arg = Parens->getSubExpr();
7581 }
7582
7583 while (SubstNonTypeTemplateParmExpr *subst =
7584 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7585 Arg = subst->getReplacement()->IgnoreImpCasts();
7586
7587 // A pointer-to-member constant written &Class::member.
7588 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7589 if (UnOp->getOpcode() == UO_AddrOf) {
7590 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7591 if (DRE && !DRE->getQualifier())
7592 DRE = nullptr;
7593 }
7594 }
7595 // A constant of pointer-to-member type.
7596 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7597 ValueDecl *VD = DRE->getDecl();
7598 if (VD->getType()->isMemberPointerType()) {
7599 if (isa<NonTypeTemplateParmDecl>(VD)) {
7600 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7601 SugaredConverted = TemplateArgument(Arg);
7602 CanonicalConverted =
7603 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7604 } else {
7605 SugaredConverted = TemplateArgument(VD, ParamType);
7606 CanonicalConverted =
7607 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7608 S.Context.getCanonicalType(ParamType));
7609 }
7610 return Invalid;
7611 }
7612 }
7613
7614 DRE = nullptr;
7615 }
7616
7617 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7618
7619 // Check for a null pointer value.
7620 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7621 Entity)) {
7622 case NPV_Error:
7623 return true;
7624 case NPV_NullPointer:
7625 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7626 SugaredConverted = TemplateArgument(ParamType,
7627 /*isNullPtr*/ true);
7628 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7629 /*isNullPtr*/ true);
7630 return false;
7631 case NPV_NotNullPointer:
7632 break;
7633 }
7634
7635 if (S.IsQualificationConversion(ResultArg->getType(),
7636 ParamType.getNonReferenceType(), false,
7637 ObjCLifetimeConversion)) {
7638 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7639 ResultArg->getValueKind())
7640 .get();
7641 } else if (!S.Context.hasSameUnqualifiedType(
7642 ResultArg->getType(), ParamType.getNonReferenceType())) {
7643 // We can't perform this conversion.
7644 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7645 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7647 return true;
7648 }
7649
7650 if (!DRE)
7651 return S.Diag(Arg->getBeginLoc(),
7652 diag::err_template_arg_not_pointer_to_member_form)
7653 << Arg->getSourceRange();
7654
7655 if (isa<FieldDecl>(DRE->getDecl()) ||
7656 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7657 isa<CXXMethodDecl>(DRE->getDecl())) {
7658 assert((isa<FieldDecl>(DRE->getDecl()) ||
7659 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7660 cast<CXXMethodDecl>(DRE->getDecl())
7661 ->isImplicitObjectMemberFunction()) &&
7662 "Only non-static member pointers can make it here");
7663
7664 // Okay: this is the address of a non-static member, and therefore
7665 // a member pointer constant.
7666 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7667 SugaredConverted = TemplateArgument(Arg);
7668 CanonicalConverted =
7669 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7670 } else {
7671 ValueDecl *D = DRE->getDecl();
7672 SugaredConverted = TemplateArgument(D, ParamType);
7673 CanonicalConverted =
7674 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7675 S.Context.getCanonicalType(ParamType));
7676 }
7677 return Invalid;
7678 }
7679
7680 // We found something else, but we don't know specifically what it is.
7681 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7682 << Arg->getSourceRange();
7683 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7684 return true;
7685}
7686
7687/// Check a template argument against its corresponding
7688/// non-type template parameter.
7689///
7690/// This routine implements the semantics of C++ [temp.arg.nontype].
7691/// If an error occurred, it returns ExprError(); otherwise, it
7692/// returns the converted template argument. \p ParamType is the
7693/// type of the non-type template parameter after it has been instantiated.
7695 QualType ParamType, Expr *Arg,
7696 TemplateArgument &SugaredConverted,
7697 TemplateArgument &CanonicalConverted,
7699 SourceLocation StartLoc = Arg->getBeginLoc();
7700
7701 // If the parameter type somehow involves auto, deduce the type now.
7702 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7703 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7704 // During template argument deduction, we allow 'decltype(auto)' to
7705 // match an arbitrary dependent argument.
7706 // FIXME: The language rules don't say what happens in this case.
7707 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7708 // expression is merely instantiation-dependent; is this enough?
7709 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7710 auto *AT = dyn_cast<AutoType>(DeducedT);
7711 if (AT && AT->isDecltypeAuto()) {
7712 SugaredConverted = TemplateArgument(Arg);
7713 CanonicalConverted = TemplateArgument(
7714 Context.getCanonicalTemplateArgument(SugaredConverted));
7715 return Arg;
7716 }
7717 }
7718
7719 // When checking a deduced template argument, deduce from its type even if
7720 // the type is dependent, in order to check the types of non-type template
7721 // arguments line up properly in partial ordering.
7722 Expr *DeductionArg = Arg;
7723 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7724 DeductionArg = PE->getPattern();
7725 TypeSourceInfo *TSI =
7726 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7727 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7728 InitializedEntity Entity =
7731 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7732 Expr *Inits[1] = {DeductionArg};
7733 ParamType =
7734 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7735 if (ParamType.isNull())
7736 return ExprError();
7737 } else {
7738 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7739 Param->getDepth() + 1);
7740 ParamType = QualType();
7742 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7743 /*DependentDeduction=*/true,
7744 // We do not check constraints right now because the
7745 // immediately-declared constraint of the auto type is
7746 // also an associated constraint, and will be checked
7747 // along with the other associated constraints after
7748 // checking the template argument list.
7749 /*IgnoreConstraints=*/true);
7751 if (ParamType.isNull())
7752 return ExprError();
7754 Diag(Arg->getExprLoc(),
7755 diag::err_non_type_template_parm_type_deduction_failure)
7756 << Param->getDeclName() << Param->getType() << Arg->getType()
7757 << Arg->getSourceRange();
7759 return ExprError();
7760 }
7761 }
7762 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7763 // an error. The error message normally references the parameter
7764 // declaration, but here we'll pass the argument location because that's
7765 // where the parameter type is deduced.
7766 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7767 if (ParamType.isNull()) {
7769 return ExprError();
7770 }
7771 }
7772
7773 // We should have already dropped all cv-qualifiers by now.
7774 assert(!ParamType.hasQualifiers() &&
7775 "non-type template parameter type cannot be qualified");
7776
7777 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7778 if (CTAK == CTAK_Deduced &&
7779 (ParamType->isReferenceType()
7781 Arg->getType())
7782 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7783 // FIXME: If either type is dependent, we skip the check. This isn't
7784 // correct, since during deduction we're supposed to have replaced each
7785 // template parameter with some unique (non-dependent) placeholder.
7786 // FIXME: If the argument type contains 'auto', we carry on and fail the
7787 // type check in order to force specific types to be more specialized than
7788 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7789 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7790 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7791 !Arg->getType()->getContainedDeducedType()) {
7792 SugaredConverted = TemplateArgument(Arg);
7793 CanonicalConverted = TemplateArgument(
7794 Context.getCanonicalTemplateArgument(SugaredConverted));
7795 return Arg;
7796 }
7797 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7798 // we should actually be checking the type of the template argument in P,
7799 // not the type of the template argument deduced from A, against the
7800 // template parameter type.
7801 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7802 << Arg->getType()
7803 << ParamType.getUnqualifiedType();
7805 return ExprError();
7806 }
7807
7808 // If either the parameter has a dependent type or the argument is
7809 // type-dependent, there's nothing we can check now.
7810 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7811 // Force the argument to the type of the parameter to maintain invariants.
7812 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7813 if (PE)
7814 Arg = PE->getPattern();
7816 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7817 ParamType->isLValueReferenceType() ? VK_LValue
7818 : ParamType->isRValueReferenceType() ? VK_XValue
7819 : VK_PRValue);
7820 if (E.isInvalid())
7821 return ExprError();
7822 if (PE) {
7823 // Recreate a pack expansion if we unwrapped one.
7824 E = new (Context)
7825 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7826 PE->getNumExpansions());
7827 }
7828 SugaredConverted = TemplateArgument(E.get());
7829 CanonicalConverted = TemplateArgument(
7830 Context.getCanonicalTemplateArgument(SugaredConverted));
7831 return E;
7832 }
7833
7834 QualType CanonParamType = Context.getCanonicalType(ParamType);
7835 // Avoid making a copy when initializing a template parameter of class type
7836 // from a template parameter object of the same type. This is going beyond
7837 // the standard, but is required for soundness: in
7838 // template<A a> struct X { X *p; X<a> *q; };
7839 // ... we need p and q to have the same type.
7840 //
7841 // Similarly, don't inject a call to a copy constructor when initializing
7842 // from a template parameter of the same type.
7843 Expr *InnerArg = Arg->IgnoreParenImpCasts();
7844 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7845 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7846 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7847 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7848
7849 SugaredConverted = TemplateArgument(TPO, ParamType);
7850 CanonicalConverted =
7851 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7852 return Arg;
7853 }
7854 if (isa<NonTypeTemplateParmDecl>(ND)) {
7855 SugaredConverted = TemplateArgument(Arg);
7856 CanonicalConverted =
7857 Context.getCanonicalTemplateArgument(SugaredConverted);
7858 return Arg;
7859 }
7860 }
7861
7862 // The initialization of the parameter from the argument is
7863 // a constant-evaluated context.
7866
7867 bool IsConvertedConstantExpression = true;
7868 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
7870 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
7871 Expr *Inits[1] = {Arg};
7872 InitializedEntity Entity =
7874 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7875 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
7876 if (Result.isInvalid() || !Result.get())
7877 return ExprError();
7879 if (Result.isInvalid() || !Result.get())
7880 return ExprError();
7881 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7882 /*DiscardedValue=*/false,
7883 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
7884 .get();
7885 IsConvertedConstantExpression = false;
7886 }
7887
7888 if (getLangOpts().CPlusPlus17) {
7889 // C++17 [temp.arg.nontype]p1:
7890 // A template-argument for a non-type template parameter shall be
7891 // a converted constant expression of the type of the template-parameter.
7892 APValue Value;
7893 ExprResult ArgResult;
7894 if (IsConvertedConstantExpression) {
7895 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
7896 CCEK_TemplateArg, Param);
7897 if (ArgResult.isInvalid())
7898 return ExprError();
7899 } else {
7900 ArgResult = Arg;
7901 }
7902
7903 // For a value-dependent argument, CheckConvertedConstantExpression is
7904 // permitted (and expected) to be unable to determine a value.
7905 if (ArgResult.get()->isValueDependent()) {
7906 SugaredConverted = TemplateArgument(ArgResult.get());
7907 CanonicalConverted =
7908 Context.getCanonicalTemplateArgument(SugaredConverted);
7909 return ArgResult;
7910 }
7911
7912 APValue PreNarrowingValue;
7914 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
7915 false, PreNarrowingValue);
7916 if (ArgResult.isInvalid())
7917 return ExprError();
7918
7919 if (Value.isLValue()) {
7920 APValue::LValueBase Base = Value.getLValueBase();
7921 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7922 // For a non-type template-parameter of pointer or reference type,
7923 // the value of the constant expression shall not refer to
7924 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7925 ParamType->isNullPtrType());
7926 // -- a temporary object
7927 // -- a string literal
7928 // -- the result of a typeid expression, or
7929 // -- a predefined __func__ variable
7930 if (Base &&
7931 (!VD ||
7932 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7933 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7934 << Arg->getSourceRange();
7935 return ExprError();
7936 }
7937
7938 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7939 VD->getType()->isArrayType() &&
7940 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7941 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7942 SugaredConverted = TemplateArgument(VD, ParamType);
7943 CanonicalConverted = TemplateArgument(
7944 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
7945 return ArgResult.get();
7946 }
7947
7948 // -- a subobject [until C++20]
7949 if (!getLangOpts().CPlusPlus20) {
7950 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7951 Value.isLValueOnePastTheEnd()) {
7952 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7953 << Value.getAsString(Context, ParamType);
7954 return ExprError();
7955 }
7956 assert((VD || !ParamType->isReferenceType()) &&
7957 "null reference should not be a constant expression");
7958 assert((!VD || !ParamType->isNullPtrType()) &&
7959 "non-null value of type nullptr_t?");
7960 }
7961 }
7962
7963 if (Value.isAddrLabelDiff())
7964 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7965
7966 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7967 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
7968 return ArgResult.get();
7969 }
7970
7971 // C++ [temp.arg.nontype]p5:
7972 // The following conversions are performed on each expression used
7973 // as a non-type template-argument. If a non-type
7974 // template-argument cannot be converted to the type of the
7975 // corresponding template-parameter then the program is
7976 // ill-formed.
7977 if (ParamType->isIntegralOrEnumerationType()) {
7978 // C++11:
7979 // -- for a non-type template-parameter of integral or
7980 // enumeration type, conversions permitted in a converted
7981 // constant expression are applied.
7982 //
7983 // C++98:
7984 // -- for a non-type template-parameter of integral or
7985 // enumeration type, integral promotions (4.5) and integral
7986 // conversions (4.7) are applied.
7987
7988 if (getLangOpts().CPlusPlus11) {
7989 // C++ [temp.arg.nontype]p1:
7990 // A template-argument for a non-type, non-template template-parameter
7991 // shall be one of:
7992 //
7993 // -- for a non-type template-parameter of integral or enumeration
7994 // type, a converted constant expression of the type of the
7995 // template-parameter; or
7996 llvm::APSInt Value;
7997 ExprResult ArgResult =
8000 if (ArgResult.isInvalid())
8001 return ExprError();
8002
8003 // We can't check arbitrary value-dependent arguments.
8004 if (ArgResult.get()->isValueDependent()) {
8005 SugaredConverted = TemplateArgument(ArgResult.get());
8006 CanonicalConverted =
8007 Context.getCanonicalTemplateArgument(SugaredConverted);
8008 return ArgResult;
8009 }
8010
8011 // Widen the argument value to sizeof(parameter type). This is almost
8012 // always a no-op, except when the parameter type is bool. In
8013 // that case, this may extend the argument from 1 bit to 8 bits.
8014 QualType IntegerType = ParamType;
8015 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
8016 IntegerType = Enum->getDecl()->getIntegerType();
8017 Value = Value.extOrTrunc(IntegerType->isBitIntType()
8018 ? Context.getIntWidth(IntegerType)
8019 : Context.getTypeSize(IntegerType));
8020
8021 SugaredConverted = TemplateArgument(Context, Value, ParamType);
8022 CanonicalConverted =
8024 return ArgResult;
8025 }
8026
8027 ExprResult ArgResult = DefaultLvalueConversion(Arg);
8028 if (ArgResult.isInvalid())
8029 return ExprError();
8030 Arg = ArgResult.get();
8031
8032 QualType ArgType = Arg->getType();
8033
8034 // C++ [temp.arg.nontype]p1:
8035 // A template-argument for a non-type, non-template
8036 // template-parameter shall be one of:
8037 //
8038 // -- an integral constant-expression of integral or enumeration
8039 // type; or
8040 // -- the name of a non-type template-parameter; or
8041 llvm::APSInt Value;
8042 if (!ArgType->isIntegralOrEnumerationType()) {
8043 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
8044 << ArgType << Arg->getSourceRange();
8046 return ExprError();
8047 } else if (!Arg->isValueDependent()) {
8048 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
8049 QualType T;
8050
8051 public:
8052 TmplArgICEDiagnoser(QualType T) : T(T) { }
8053
8054 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
8055 SourceLocation Loc) override {
8056 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
8057 }
8058 } Diagnoser(ArgType);
8059
8060 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
8061 if (!Arg)
8062 return ExprError();
8063 }
8064
8065 // From here on out, all we care about is the unqualified form
8066 // of the argument type.
8067 ArgType = ArgType.getUnqualifiedType();
8068
8069 // Try to convert the argument to the parameter's type.
8070 if (Context.hasSameType(ParamType, ArgType)) {
8071 // Okay: no conversion necessary
8072 } else if (ParamType->isBooleanType()) {
8073 // This is an integral-to-boolean conversion.
8074 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
8075 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
8076 !ParamType->isEnumeralType()) {
8077 // This is an integral promotion or conversion.
8078 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
8079 } else {
8080 // We can't perform this conversion.
8081 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
8082 << Arg->getType() << ParamType << Arg->getSourceRange();
8084 return ExprError();
8085 }
8086
8087 // Add the value of this argument to the list of converted
8088 // arguments. We use the bitwidth and signedness of the template
8089 // parameter.
8090 if (Arg->isValueDependent()) {
8091 // The argument is value-dependent. Create a new
8092 // TemplateArgument with the converted expression.
8093 SugaredConverted = TemplateArgument(Arg);
8094 CanonicalConverted =
8095 Context.getCanonicalTemplateArgument(SugaredConverted);
8096 return Arg;
8097 }
8098
8099 QualType IntegerType = ParamType;
8100 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
8101 IntegerType = Enum->getDecl()->getIntegerType();
8102 }
8103
8104 if (ParamType->isBooleanType()) {
8105 // Value must be zero or one.
8106 Value = Value != 0;
8107 unsigned AllowedBits = Context.getTypeSize(IntegerType);
8108 if (Value.getBitWidth() != AllowedBits)
8109 Value = Value.extOrTrunc(AllowedBits);
8110 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8111 } else {
8112 llvm::APSInt OldValue = Value;
8113
8114 // Coerce the template argument's value to the value it will have
8115 // based on the template parameter's type.
8116 unsigned AllowedBits = IntegerType->isBitIntType()
8117 ? Context.getIntWidth(IntegerType)
8118 : Context.getTypeSize(IntegerType);
8119 if (Value.getBitWidth() != AllowedBits)
8120 Value = Value.extOrTrunc(AllowedBits);
8121 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8122
8123 // Complain if an unsigned parameter received a negative value.
8124 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
8125 (OldValue.isSigned() && OldValue.isNegative())) {
8126 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
8127 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8128 << Arg->getSourceRange();
8130 }
8131
8132 // Complain if we overflowed the template parameter's type.
8133 unsigned RequiredBits;
8134 if (IntegerType->isUnsignedIntegerOrEnumerationType())
8135 RequiredBits = OldValue.getActiveBits();
8136 else if (OldValue.isUnsigned())
8137 RequiredBits = OldValue.getActiveBits() + 1;
8138 else
8139 RequiredBits = OldValue.getSignificantBits();
8140 if (RequiredBits > AllowedBits) {
8141 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
8142 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8143 << Arg->getSourceRange();
8145 }
8146 }
8147
8148 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
8149 SugaredConverted = TemplateArgument(Context, Value, T);
8150 CanonicalConverted =
8152 return Arg;
8153 }
8154
8155 QualType ArgType = Arg->getType();
8156 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
8157
8158 // Handle pointer-to-function, reference-to-function, and
8159 // pointer-to-member-function all in (roughly) the same way.
8160 if (// -- For a non-type template-parameter of type pointer to
8161 // function, only the function-to-pointer conversion (4.3) is
8162 // applied. If the template-argument represents a set of
8163 // overloaded functions (or a pointer to such), the matching
8164 // function is selected from the set (13.4).
8165 (ParamType->isPointerType() &&
8166 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
8167 // -- For a non-type template-parameter of type reference to
8168 // function, no conversions apply. If the template-argument
8169 // represents a set of overloaded functions, the matching
8170 // function is selected from the set (13.4).
8171 (ParamType->isReferenceType() &&
8172 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
8173 // -- For a non-type template-parameter of type pointer to
8174 // member function, no conversions apply. If the
8175 // template-argument represents a set of overloaded member
8176 // functions, the matching member function is selected from
8177 // the set (13.4).
8178 (ParamType->isMemberPointerType() &&
8179 ParamType->castAs<MemberPointerType>()->getPointeeType()
8180 ->isFunctionType())) {
8181
8182 if (Arg->getType() == Context.OverloadTy) {
8183 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
8184 true,
8185 FoundResult)) {
8186 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8187 return ExprError();
8188
8189 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8190 if (Res.isInvalid())
8191 return ExprError();
8192 Arg = Res.get();
8193 ArgType = Arg->getType();
8194 } else
8195 return ExprError();
8196 }
8197
8198 if (!ParamType->isMemberPointerType()) {
8200 *this, Param, ParamType, Arg, SugaredConverted,
8201 CanonicalConverted))
8202 return ExprError();
8203 return Arg;
8204 }
8205
8207 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8208 return ExprError();
8209 return Arg;
8210 }
8211
8212 if (ParamType->isPointerType()) {
8213 // -- for a non-type template-parameter of type pointer to
8214 // object, qualification conversions (4.4) and the
8215 // array-to-pointer conversion (4.2) are applied.
8216 // C++0x also allows a value of std::nullptr_t.
8217 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
8218 "Only object pointers allowed here");
8219
8221 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8222 return ExprError();
8223 return Arg;
8224 }
8225
8226 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
8227 // -- For a non-type template-parameter of type reference to
8228 // object, no conversions apply. The type referred to by the
8229 // reference may be more cv-qualified than the (otherwise
8230 // identical) type of the template-argument. The
8231 // template-parameter is bound directly to the
8232 // template-argument, which must be an lvalue.
8233 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
8234 "Only object references allowed here");
8235
8236 if (Arg->getType() == Context.OverloadTy) {
8238 ParamRefType->getPointeeType(),
8239 true,
8240 FoundResult)) {
8241 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
8242 return ExprError();
8243 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
8244 if (Res.isInvalid())
8245 return ExprError();
8246 Arg = Res.get();
8247 ArgType = Arg->getType();
8248 } else
8249 return ExprError();
8250 }
8251
8253 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8254 return ExprError();
8255 return Arg;
8256 }
8257
8258 // Deal with parameters of type std::nullptr_t.
8259 if (ParamType->isNullPtrType()) {
8260 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
8261 SugaredConverted = TemplateArgument(Arg);
8262 CanonicalConverted =
8263 Context.getCanonicalTemplateArgument(SugaredConverted);
8264 return Arg;
8265 }
8266
8267 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
8268 case NPV_NotNullPointer:
8269 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
8270 << Arg->getType() << ParamType;
8272 return ExprError();
8273
8274 case NPV_Error:
8275 return ExprError();
8276
8277 case NPV_NullPointer:
8278 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
8279 SugaredConverted = TemplateArgument(ParamType,
8280 /*isNullPtr=*/true);
8281 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
8282 /*isNullPtr=*/true);
8283 return Arg;
8284 }
8285 }
8286
8287 // -- For a non-type template-parameter of type pointer to data
8288 // member, qualification conversions (4.4) are applied.
8289 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
8290
8292 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
8293 return ExprError();
8294 return Arg;
8295}
8296
8300
8301/// Check a template argument against its corresponding
8302/// template template parameter.
8303///
8304/// This routine implements the semantics of C++ [temp.arg.template].
8305/// It returns true if an error occurred, and false otherwise.
8307 TemplateParameterList *Params,
8308 TemplateArgumentLoc &Arg) {
8310 TemplateDecl *Template = Name.getAsTemplateDecl();
8311 if (!Template) {
8312 // Any dependent template name is fine.
8313 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
8314 return false;
8315 }
8316
8317 if (Template->isInvalidDecl())
8318 return true;
8319
8320 // C++0x [temp.arg.template]p1:
8321 // A template-argument for a template template-parameter shall be
8322 // the name of a class template or an alias template, expressed as an
8323 // id-expression. When the template-argument names a class template, only
8324 // primary class templates are considered when matching the
8325 // template template argument with the corresponding parameter;
8326 // partial specializations are not considered even if their
8327 // parameter lists match that of the template template parameter.
8328 //
8329 // Note that we also allow template template parameters here, which
8330 // will happen when we are dealing with, e.g., class template
8331 // partial specializations.
8332 if (!isa<ClassTemplateDecl>(Template) &&
8333 !isa<TemplateTemplateParmDecl>(Template) &&
8334 !isa<TypeAliasTemplateDecl>(Template) &&
8335 !isa<BuiltinTemplateDecl>(Template)) {
8336 assert(isa<FunctionTemplateDecl>(Template) &&
8337 "Only function templates are possible here");
8338 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
8339 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
8340 << Template;
8341 }
8342
8343 // C++1z [temp.arg.template]p3: (DR 150)
8344 // A template-argument matches a template template-parameter P when P
8345 // is at least as specialized as the template-argument A.
8346 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
8347 // defect report resolution from C++17 and shouldn't be introduced by
8348 // concepts.
8349 if (getLangOpts().RelaxedTemplateTemplateArgs) {
8350 // Quick check for the common case:
8351 // If P contains a parameter pack, then A [...] matches P if each of A's
8352 // template parameters matches the corresponding template parameter in
8353 // the template-parameter-list of P.
8355 Template->getTemplateParameters(), Params, false,
8357 // If the argument has no associated constraints, then the parameter is
8358 // definitely at least as specialized as the argument.
8359 // Otherwise - we need a more thorough check.
8360 !Template->hasAssociatedConstraints())
8361 return false;
8362
8364 Arg.getLocation())) {
8365 // P2113
8366 // C++20[temp.func.order]p2
8367 // [...] If both deductions succeed, the partial ordering selects the
8368 // more constrained template (if one exists) as determined below.
8369 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
8370 Params->getAssociatedConstraints(ParamsAC);
8371 // C++2a[temp.arg.template]p3
8372 // [...] In this comparison, if P is unconstrained, the constraints on A
8373 // are not considered.
8374 if (ParamsAC.empty())
8375 return false;
8376
8377 Template->getAssociatedConstraints(TemplateAC);
8378
8379 bool IsParamAtLeastAsConstrained;
8380 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
8381 IsParamAtLeastAsConstrained))
8382 return true;
8383 if (!IsParamAtLeastAsConstrained) {
8384 Diag(Arg.getLocation(),
8385 diag::err_template_template_parameter_not_at_least_as_constrained)
8386 << Template << Param << Arg.getSourceRange();
8387 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
8388 Diag(Template->getLocation(), diag::note_entity_declared_at)
8389 << Template;
8390 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
8391 TemplateAC);
8392 return true;
8393 }
8394 return false;
8395 }
8396 // FIXME: Produce better diagnostics for deduction failures.
8397 }
8398
8400 Params,
8401 true,
8403 Arg.getLocation());
8404}
8405
8407 unsigned HereDiagID,
8408 unsigned ExternalDiagID) {
8409 if (Decl.getLocation().isValid())
8410 return S.Diag(Decl.getLocation(), HereDiagID);
8411
8412 SmallString<128> Str;
8413 llvm::raw_svector_ostream Out(Str);
8415 PP.TerseOutput = 1;
8416 Decl.print(Out, PP);
8417 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
8418}
8419
8421 std::optional<SourceRange> ParamRange) {
8423 noteLocation(*this, Decl, diag::note_template_decl_here,
8424 diag::note_template_decl_external);
8425 if (ParamRange && ParamRange->isValid()) {
8426 assert(Decl.getLocation().isValid() &&
8427 "Parameter range has location when Decl does not");
8428 DB << *ParamRange;
8429 }
8430}
8431
8433 noteLocation(*this, Decl, diag::note_template_param_here,
8434 diag::note_template_param_external);
8435}
8436
8437/// Given a non-type template argument that refers to a
8438/// declaration and the type of its corresponding non-type template
8439/// parameter, produce an expression that properly refers to that
8440/// declaration.
8443 QualType ParamType,
8444 SourceLocation Loc) {
8445 // C++ [temp.param]p8:
8446 //
8447 // A non-type template-parameter of type "array of T" or
8448 // "function returning T" is adjusted to be of type "pointer to
8449 // T" or "pointer to function returning T", respectively.
8450 if (ParamType->isArrayType())
8451 ParamType = Context.getArrayDecayedType(ParamType);
8452 else if (ParamType->isFunctionType())
8453 ParamType = Context.getPointerType(ParamType);
8454
8455 // For a NULL non-type template argument, return nullptr casted to the
8456 // parameter's type.
8457 if (Arg.getKind() == TemplateArgument::NullPtr) {
8458 return ImpCastExprToType(
8460 ParamType,
8461 ParamType->getAs<MemberPointerType>()
8462 ? CK_NullToMemberPointer
8463 : CK_NullToPointer);
8464 }
8465 assert(Arg.getKind() == TemplateArgument::Declaration &&
8466 "Only declaration template arguments permitted here");
8467
8468 ValueDecl *VD = Arg.getAsDecl();
8469
8470 CXXScopeSpec SS;
8471 if (ParamType->isMemberPointerType()) {
8472 // If this is a pointer to member, we need to use a qualified name to
8473 // form a suitable pointer-to-member constant.
8474 assert(VD->getDeclContext()->isRecord() &&
8475 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8476 isa<IndirectFieldDecl>(VD)));
8477 QualType ClassType
8478 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
8479 NestedNameSpecifier *Qualifier
8480 = NestedNameSpecifier::Create(Context, nullptr, false,
8481 ClassType.getTypePtr());
8482 SS.MakeTrivial(Context, Qualifier, Loc);
8483 }
8484
8486 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8487 if (RefExpr.isInvalid())
8488 return ExprError();
8489
8490 // For a pointer, the argument declaration is the pointee. Take its address.
8491 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8492 if (ParamType->isPointerType() && !ElemT.isNull() &&
8493 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
8494 // Decay an array argument if we want a pointer to its first element.
8495 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
8496 if (RefExpr.isInvalid())
8497 return ExprError();
8498 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8499 // For any other pointer, take the address (or form a pointer-to-member).
8500 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
8501 if (RefExpr.isInvalid())
8502 return ExprError();
8503 } else if (ParamType->isRecordType()) {
8504 assert(isa<TemplateParamObjectDecl>(VD) &&
8505 "arg for class template param not a template parameter object");
8506 // No conversions apply in this case.
8507 return RefExpr;
8508 } else {
8509 assert(ParamType->isReferenceType() &&
8510 "unexpected type for decl template argument");
8511 }
8512
8513 // At this point we should have the right value category.
8514 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8515 "value kind mismatch for non-type template argument");
8516
8517 // The type of the template parameter can differ from the type of the
8518 // argument in various ways; convert it now if necessary.
8519 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8520 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
8521 CastKind CK;
8522 QualType Ignored;
8523 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
8524 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
8525 CK = CK_NoOp;
8526 } else if (ParamType->isVoidPointerType() &&
8527 RefExpr.get()->getType()->isPointerType()) {
8528 CK = CK_BitCast;
8529 } else {
8530 // FIXME: Pointers to members can need conversion derived-to-base or
8531 // base-to-derived conversions. We currently don't retain enough
8532 // information to convert properly (we need to track a cast path or
8533 // subobject number in the template argument).
8534 llvm_unreachable(
8535 "unexpected conversion required for non-type template argument");
8536 }
8537 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
8538 RefExpr.get()->getValueKind());
8539 }
8540
8541 return RefExpr;
8542}
8543
8544/// Construct a new expression that refers to the given
8545/// integral template argument with the given source-location
8546/// information.
8547///
8548/// This routine takes care of the mapping from an integral template
8549/// argument (which may have any integral type) to the appropriate
8550/// literal value.
8552 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8553 assert(OrigT->isIntegralOrEnumerationType());
8554
8555 // If this is an enum type that we're instantiating, we need to use an integer
8556 // type the same size as the enumerator. We don't want to build an
8557 // IntegerLiteral with enum type. The integer type of an enum type can be of
8558 // any integral type with C++11 enum classes, make sure we create the right
8559 // type of literal for it.
8560 QualType T = OrigT;
8561 if (const EnumType *ET = OrigT->getAs<EnumType>())
8562 T = ET->getDecl()->getIntegerType();
8563
8564 Expr *E;
8565 if (T->isAnyCharacterType()) {
8567 if (T->isWideCharType())
8569 else if (T->isChar8Type() && S.getLangOpts().Char8)
8571 else if (T->isChar16Type())
8573 else if (T->isChar32Type())
8575 else
8577
8578 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8579 } else if (T->isBooleanType()) {
8580 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
8581 } else {
8582 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
8583 }
8584
8585 if (OrigT->isEnumeralType()) {
8586 // FIXME: This is a hack. We need a better way to handle substituted
8587 // non-type template parameters.
8588 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8589 nullptr, S.CurFPFeatureOverrides(),
8590 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
8591 Loc, Loc);
8592 }
8593
8594 return E;
8595}
8596
8598 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8599 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8600 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8601 ILE->setType(T);
8602 return ILE;
8603 };
8604
8605 switch (Val.getKind()) {
8607 // This cannot occur in a template argument at all.
8608 case APValue::Array:
8609 case APValue::Struct:
8610 case APValue::Union:
8611 // These can only occur within a template parameter object, which is
8612 // represented as a TemplateArgument::Declaration.
8613 llvm_unreachable("unexpected template argument value");
8614
8615 case APValue::Int:
8617 Loc);
8618
8619 case APValue::Float:
8620 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
8621 T, Loc);
8622
8625 S.Context, Val.getFixedPoint().getValue(), T, Loc,
8626 Val.getFixedPoint().getScale());
8627
8628 case APValue::ComplexInt: {
8629 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8631 S, ElemT, Val.getComplexIntReal(), Loc),
8633 S, ElemT, Val.getComplexIntImag(), Loc)});
8634 }
8635
8636 case APValue::ComplexFloat: {
8637 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8638 return MakeInitList(
8640 ElemT, Loc),
8642 ElemT, Loc)});
8643 }
8644
8645 case APValue::Vector: {
8646 QualType ElemT = T->castAs<VectorType>()->getElementType();
8648 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8650 S, ElemT, Val.getVectorElt(I), Loc));
8651 return MakeInitList(Elts);
8652 }
8653
8654 case APValue::None:
8656 llvm_unreachable("Unexpected APValue kind.");
8657 case APValue::LValue:
8659 // There isn't necessarily a valid equivalent source-level syntax for
8660 // these; in particular, a naive lowering might violate access control.
8661 // So for now we lower to a ConstantExpr holding the value, wrapped around
8662 // an OpaqueValueExpr.
8663 // FIXME: We should have a better representation for this.
8665 if (T->isReferenceType()) {
8666 T = T->getPointeeType();
8667 VK = VK_LValue;
8668 }
8669 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8670 return ConstantExpr::Create(S.Context, OVE, Val);
8671 }
8672 llvm_unreachable("Unhandled APValue::ValueKind enum");
8673}
8674
8677 SourceLocation Loc) {
8678 switch (Arg.getKind()) {
8684 llvm_unreachable("not a non-type template argument");
8685
8687 return Arg.getAsExpr();
8688
8692 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
8693
8696 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
8697
8700 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
8701 }
8702 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8703}
8704
8705/// Match two template parameters within template parameter lists.
8707 Sema &S, NamedDecl *New,
8708 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8709 const NamedDecl *OldInstFrom, bool Complain,
8711 // Check the actual kind (type, non-type, template).
8712 if (Old->getKind() != New->getKind()) {
8713 if (Complain) {
8714 unsigned NextDiag = diag::err_template_param_different_kind;
8715 if (TemplateArgLoc.isValid()) {
8716 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8717 NextDiag = diag::note_template_param_different_kind;
8718 }
8719 S.Diag(New->getLocation(), NextDiag)
8720 << (Kind != Sema::TPL_TemplateMatch);
8721 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8722 << (Kind != Sema::TPL_TemplateMatch);
8723 }
8724
8725 return false;
8726 }
8727
8728 // Check that both are parameter packs or neither are parameter packs.
8729 // However, if we are matching a template template argument to a
8730 // template template parameter, the template template parameter can have
8731 // a parameter pack where the template template argument does not.
8732 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8734 Old->isTemplateParameterPack())) {
8735 if (Complain) {
8736 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8737 if (TemplateArgLoc.isValid()) {
8738 S.Diag(TemplateArgLoc,
8739 diag::err_template_arg_template_params_mismatch);
8740 NextDiag = diag::note_template_parameter_pack_non_pack;
8741 }
8742
8743 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8744 : isa<NonTypeTemplateParmDecl>(New)? 1
8745 : 2;
8746 S.Diag(New->getLocation(), NextDiag)
8747 << ParamKind << New->isParameterPack();
8748 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8749 << ParamKind << Old->isParameterPack();
8750 }
8751
8752 return false;
8753 }
8754
8755 // For non-type template parameters, check the type of the parameter.
8756 if (NonTypeTemplateParmDecl *OldNTTP
8757 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8758 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8759
8760 // If we are matching a template template argument to a template
8761 // template parameter and one of the non-type template parameter types
8762 // is dependent, then we must wait until template instantiation time
8763 // to actually compare the arguments.
8765 (!OldNTTP->getType()->isDependentType() &&
8766 !NewNTTP->getType()->isDependentType())) {
8767 // C++20 [temp.over.link]p6:
8768 // Two [non-type] template-parameters are equivalent [if] they have
8769 // equivalent types ignoring the use of type-constraints for
8770 // placeholder types
8771 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8772 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8773 if (!S.Context.hasSameType(OldType, NewType)) {
8774 if (Complain) {
8775 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8776 if (TemplateArgLoc.isValid()) {
8777 S.Diag(TemplateArgLoc,
8778 diag::err_template_arg_template_params_mismatch);
8779 NextDiag = diag::note_template_nontype_parm_different_type;
8780 }
8781 S.Diag(NewNTTP->getLocation(), NextDiag)
8782 << NewNTTP->getType()
8783 << (Kind != Sema::TPL_TemplateMatch);
8784 S.Diag(OldNTTP->getLocation(),
8785 diag::note_template_nontype_parm_prev_declaration)
8786 << OldNTTP->getType();
8787 }
8788
8789 return false;
8790 }
8791 }
8792 }
8793 // For template template parameters, check the template parameter types.
8794 // The template parameter lists of template template
8795 // parameters must agree.
8796 else if (TemplateTemplateParmDecl *OldTTP =
8797 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8798 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8800 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8801 OldTTP->getTemplateParameters(), Complain,
8804 : Kind),
8805 TemplateArgLoc))
8806 return false;
8807 }
8808
8811 !isa<TemplateTemplateParmDecl>(Old)) {
8812 const Expr *NewC = nullptr, *OldC = nullptr;
8813
8814 if (isa<TemplateTypeParmDecl>(New)) {
8815 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8816 NewC = TC->getImmediatelyDeclaredConstraint();
8817 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8818 OldC = TC->getImmediatelyDeclaredConstraint();
8819 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8820 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8821 ->getPlaceholderTypeConstraint())
8822 NewC = E;
8823 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8824 ->getPlaceholderTypeConstraint())
8825 OldC = E;
8826 } else
8827 llvm_unreachable("unexpected template parameter type");
8828
8829 auto Diagnose = [&] {
8830 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8831 diag::err_template_different_type_constraint);
8832 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8833 diag::note_template_prev_declaration) << /*declaration*/0;
8834 };
8835
8836 if (!NewC != !OldC) {
8837 if (Complain)
8838 Diagnose();
8839 return false;
8840 }
8841
8842 if (NewC) {
8843 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8844 NewC)) {
8845 if (Complain)
8846 Diagnose();
8847 return false;
8848 }
8849 }
8850 }
8851
8852 return true;
8853}
8854
8855/// Diagnose a known arity mismatch when comparing template argument
8856/// lists.
8857static
8862 SourceLocation TemplateArgLoc) {
8863 unsigned NextDiag = diag::err_template_param_list_different_arity;
8864 if (TemplateArgLoc.isValid()) {
8865 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8866 NextDiag = diag::note_template_param_list_different_arity;
8867 }
8868 S.Diag(New->getTemplateLoc(), NextDiag)
8869 << (New->size() > Old->size())
8870 << (Kind != Sema::TPL_TemplateMatch)
8871 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8872 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8873 << (Kind != Sema::TPL_TemplateMatch)
8874 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8875}
8876
8877/// Determine whether the given template parameter lists are
8878/// equivalent.
8879///
8880/// \param New The new template parameter list, typically written in the
8881/// source code as part of a new template declaration.
8882///
8883/// \param Old The old template parameter list, typically found via
8884/// name lookup of the template declared with this template parameter
8885/// list.
8886///
8887/// \param Complain If true, this routine will produce a diagnostic if
8888/// the template parameter lists are not equivalent.
8889///
8890/// \param Kind describes how we are to match the template parameter lists.
8891///
8892/// \param TemplateArgLoc If this source location is valid, then we
8893/// are actually checking the template parameter list of a template
8894/// argument (New) against the template parameter list of its
8895/// corresponding template template parameter (Old). We produce
8896/// slightly different diagnostics in this scenario.
8897///
8898/// \returns True if the template parameter lists are equal, false
8899/// otherwise.
8901 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8902 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8903 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8904 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8905 if (Complain)
8906 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8907 TemplateArgLoc);
8908
8909 return false;
8910 }
8911
8912 // C++0x [temp.arg.template]p3:
8913 // A template-argument matches a template template-parameter (call it P)
8914 // when each of the template parameters in the template-parameter-list of
8915 // the template-argument's corresponding class template or alias template
8916 // (call it A) matches the corresponding template parameter in the
8917 // template-parameter-list of P. [...]
8918 TemplateParameterList::iterator NewParm = New->begin();
8919 TemplateParameterList::iterator NewParmEnd = New->end();
8920 for (TemplateParameterList::iterator OldParm = Old->begin(),
8921 OldParmEnd = Old->end();
8922 OldParm != OldParmEnd; ++OldParm) {
8924 !(*OldParm)->isTemplateParameterPack()) {
8925 if (NewParm == NewParmEnd) {
8926 if (Complain)
8927 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8928 TemplateArgLoc);
8929
8930 return false;
8931 }
8932
8933 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8934 OldInstFrom, Complain, Kind,
8935 TemplateArgLoc))
8936 return false;
8937
8938 ++NewParm;
8939 continue;
8940 }
8941
8942 // C++0x [temp.arg.template]p3:
8943 // [...] When P's template- parameter-list contains a template parameter
8944 // pack (14.5.3), the template parameter pack will match zero or more
8945 // template parameters or template parameter packs in the
8946 // template-parameter-list of A with the same type and form as the
8947 // template parameter pack in P (ignoring whether those template
8948 // parameters are template parameter packs).
8949 for (; NewParm != NewParmEnd; ++NewParm) {
8950 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8951 OldInstFrom, Complain, Kind,
8952 TemplateArgLoc))
8953 return false;
8954 }
8955 }
8956
8957 // Make sure we exhausted all of the arguments.
8958 if (NewParm != NewParmEnd) {
8959 if (Complain)
8960 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8961 TemplateArgLoc);
8962
8963 return false;
8964 }
8965
8968 const Expr *NewRC = New->getRequiresClause();
8969 const Expr *OldRC = Old->getRequiresClause();
8970
8971 auto Diagnose = [&] {
8972 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8973 diag::err_template_different_requires_clause);
8974 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8975 diag::note_template_prev_declaration) << /*declaration*/0;
8976 };
8977
8978 if (!NewRC != !OldRC) {
8979 if (Complain)
8980 Diagnose();
8981 return false;
8982 }
8983
8984 if (NewRC) {
8985 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8986 NewRC)) {
8987 if (Complain)
8988 Diagnose();
8989 return false;
8990 }
8991 }
8992 }
8993
8994 return true;
8995}
8996
8997/// Check whether a template can be declared within this scope.
8998///
8999/// If the template declaration is valid in this scope, returns
9000/// false. Otherwise, issues a diagnostic and returns true.
9001bool
9003 if (!S)
9004 return false;
9005
9006 // Find the nearest enclosing declaration scope.
9007 S = S->getDeclParent();
9008
9009 // C++ [temp.pre]p6: [P2096]
9010 // A template, explicit specialization, or partial specialization shall not
9011 // have C linkage.
9012 DeclContext *Ctx = S->getEntity();
9013 if (Ctx && Ctx->isExternCContext()) {
9014 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
9015 << TemplateParams->getSourceRange();
9016 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
9017 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
9018 return true;
9019 }
9020 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
9021
9022 // C++ [temp]p2:
9023 // A template-declaration can appear only as a namespace scope or
9024 // class scope declaration.
9025 // C++ [temp.expl.spec]p3:
9026 // An explicit specialization may be declared in any scope in which the
9027 // corresponding primary template may be defined.
9028 // C++ [temp.class.spec]p6: [P2096]
9029 // A partial specialization may be declared in any scope in which the
9030 // corresponding primary template may be defined.
9031 if (Ctx) {
9032 if (Ctx->isFileContext())
9033 return false;
9034 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
9035 // C++ [temp.mem]p2:
9036 // A local class shall not have member templates.
9037 if (RD->isLocalClass())
9038 return Diag(TemplateParams->getTemplateLoc(),
9039 diag::err_template_inside_local_class)
9040 << TemplateParams->getSourceRange();
9041 else
9042 return false;
9043 }
9044 }
9045
9046 return Diag(TemplateParams->getTemplateLoc(),
9047 diag::err_template_outside_namespace_or_class_scope)
9048 << TemplateParams->getSourceRange();
9049}
9050
9051/// Determine what kind of template specialization the given declaration
9052/// is.
9054 if (!D)
9055 return TSK_Undeclared;
9056
9057 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
9058 return Record->getTemplateSpecializationKind();
9059 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
9060 return Function->getTemplateSpecializationKind();
9061 if (VarDecl *Var = dyn_cast<VarDecl>(D))
9062 return Var->getTemplateSpecializationKind();
9063
9064 return TSK_Undeclared;
9065}
9066
9067/// Check whether a specialization is well-formed in the current
9068/// context.
9069///
9070/// This routine determines whether a template specialization can be declared
9071/// in the current context (C++ [temp.expl.spec]p2).
9072///
9073/// \param S the semantic analysis object for which this check is being
9074/// performed.
9075///
9076/// \param Specialized the entity being specialized or instantiated, which
9077/// may be a kind of template (class template, function template, etc.) or
9078/// a member of a class template (member function, static data member,
9079/// member class).
9080///
9081/// \param PrevDecl the previous declaration of this entity, if any.
9082///
9083/// \param Loc the location of the explicit specialization or instantiation of
9084/// this entity.
9085///
9086/// \param IsPartialSpecialization whether this is a partial specialization of
9087/// a class template.
9088///
9089/// \returns true if there was an error that we cannot recover from, false
9090/// otherwise.
9092 NamedDecl *Specialized,
9093 NamedDecl *PrevDecl,
9094 SourceLocation Loc,
9096 // Keep these "kind" numbers in sync with the %select statements in the
9097 // various diagnostics emitted by this routine.
9098 int EntityKind = 0;
9099 if (isa<ClassTemplateDecl>(Specialized))
9100 EntityKind = IsPartialSpecialization? 1 : 0;
9101 else if (isa<VarTemplateDecl>(Specialized))
9102 EntityKind = IsPartialSpecialization ? 3 : 2;
9103 else if (isa<FunctionTemplateDecl>(Specialized))
9104 EntityKind = 4;
9105 else if (isa<CXXMethodDecl>(Specialized))
9106 EntityKind = 5;
9107 else if (isa<VarDecl>(Specialized))
9108 EntityKind = 6;
9109 else if (isa<RecordDecl>(Specialized))
9110 EntityKind = 7;
9111 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
9112 EntityKind = 8;
9113 else {
9114 S.Diag(Loc, diag::err_template_spec_unknown_kind)
9115 << S.getLangOpts().CPlusPlus11;
9116 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9117 return true;
9118 }
9119
9120 // C++ [temp.expl.spec]p2:
9121 // An explicit specialization may be declared in any scope in which
9122 // the corresponding primary template may be defined.
9124 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
9125 << Specialized;
9126 return true;
9127 }
9128
9129 // C++ [temp.class.spec]p6:
9130 // A class template partial specialization may be declared in any
9131 // scope in which the primary template may be defined.
9132 DeclContext *SpecializedContext =
9133 Specialized->getDeclContext()->getRedeclContext();
9135
9136 // Make sure that this redeclaration (or definition) occurs in the same
9137 // scope or an enclosing namespace.
9138 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
9139 : DC->Equals(SpecializedContext))) {
9140 if (isa<TranslationUnitDecl>(SpecializedContext))
9141 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
9142 << EntityKind << Specialized;
9143 else {
9144 auto *ND = cast<NamedDecl>(SpecializedContext);
9145 int Diag = diag::err_template_spec_redecl_out_of_scope;
9146 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
9147 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
9148 S.Diag(Loc, Diag) << EntityKind << Specialized
9149 << ND << isa<CXXRecordDecl>(ND);
9150 }
9151
9152 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9153
9154 // Don't allow specializing in the wrong class during error recovery.
9155 // Otherwise, things can go horribly wrong.
9156 if (DC->isRecord())
9157 return true;
9158 }
9159
9160 return false;
9161}
9162
9164 if (!E->isTypeDependent())
9165 return SourceLocation();
9166 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9167 Checker.TraverseStmt(E);
9168 if (Checker.MatchLoc.isInvalid())
9169 return E->getSourceRange();
9170 return Checker.MatchLoc;
9171}
9172
9173static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
9174 if (!TL.getType()->isDependentType())
9175 return SourceLocation();
9176 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9177 Checker.TraverseTypeLoc(TL);
9178 if (Checker.MatchLoc.isInvalid())
9179 return TL.getSourceRange();
9180 return Checker.MatchLoc;
9181}
9182
9183/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
9184/// that checks non-type template partial specialization arguments.
9186 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
9187 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
9188 for (unsigned I = 0; I != NumArgs; ++I) {
9189 if (Args[I].getKind() == TemplateArgument::Pack) {
9191 S, TemplateNameLoc, Param, Args[I].pack_begin(),
9192 Args[I].pack_size(), IsDefaultArgument))
9193 return true;
9194
9195 continue;
9196 }
9197
9198 if (Args[I].getKind() != TemplateArgument::Expression)
9199 continue;
9200
9201 Expr *ArgExpr = Args[I].getAsExpr();
9202
9203 // We can have a pack expansion of any of the bullets below.
9204 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
9205 ArgExpr = Expansion->getPattern();
9206
9207 // Strip off any implicit casts we added as part of type checking.
9208 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9209 ArgExpr = ICE->getSubExpr();
9210
9211 // C++ [temp.class.spec]p8:
9212 // A non-type argument is non-specialized if it is the name of a
9213 // non-type parameter. All other non-type arguments are
9214 // specialized.
9215 //
9216 // Below, we check the two conditions that only apply to
9217 // specialized non-type arguments, so skip any non-specialized
9218 // arguments.
9219 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
9220 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
9221 continue;
9222
9223 // C++ [temp.class.spec]p9:
9224 // Within the argument list of a class template partial
9225 // specialization, the following restrictions apply:
9226 // -- A partially specialized non-type argument expression
9227 // shall not involve a template parameter of the partial
9228 // specialization except when the argument expression is a
9229 // simple identifier.
9230 // -- The type of a template parameter corresponding to a
9231 // specialized non-type argument shall not be dependent on a
9232 // parameter of the specialization.
9233 // DR1315 removes the first bullet, leaving an incoherent set of rules.
9234 // We implement a compromise between the original rules and DR1315:
9235 // -- A specialized non-type template argument shall not be
9236 // type-dependent and the corresponding template parameter
9237 // shall have a non-dependent type.
9238 SourceRange ParamUseRange =
9239 findTemplateParameterInType(Param->getDepth(), ArgExpr);
9240 if (ParamUseRange.isValid()) {
9241 if (IsDefaultArgument) {
9242 S.Diag(TemplateNameLoc,
9243 diag::err_dependent_non_type_arg_in_partial_spec);
9244 S.Diag(ParamUseRange.getBegin(),
9245 diag::note_dependent_non_type_default_arg_in_partial_spec)
9246 << ParamUseRange;
9247 } else {
9248 S.Diag(ParamUseRange.getBegin(),
9249 diag::err_dependent_non_type_arg_in_partial_spec)
9250 << ParamUseRange;
9251 }
9252 return true;
9253 }
9254
9255 ParamUseRange = findTemplateParameter(
9256 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
9257 if (ParamUseRange.isValid()) {
9258 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
9259 diag::err_dependent_typed_non_type_arg_in_partial_spec)
9260 << Param->getType();
9262 return true;
9263 }
9264 }
9265
9266 return false;
9267}
9268
9269/// Check the non-type template arguments of a class template
9270/// partial specialization according to C++ [temp.class.spec]p9.
9271///
9272/// \param TemplateNameLoc the location of the template name.
9273/// \param PrimaryTemplate the template parameters of the primary class
9274/// template.
9275/// \param NumExplicit the number of explicitly-specified template arguments.
9276/// \param TemplateArgs the template arguments of the class template
9277/// partial specialization.
9278///
9279/// \returns \c true if there was an error, \c false otherwise.
9281 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
9282 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
9283 // We have to be conservative when checking a template in a dependent
9284 // context.
9285 if (PrimaryTemplate->getDeclContext()->isDependentContext())
9286 return false;
9287
9288 TemplateParameterList *TemplateParams =
9289 PrimaryTemplate->getTemplateParameters();
9290 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9292 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
9293 if (!Param)
9294 continue;
9295
9296 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
9297 Param, &TemplateArgs[I],
9298 1, I >= NumExplicit))
9299 return true;
9300 }
9301
9302 return false;
9303}
9304
9306 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
9307 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
9309 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
9310 assert(TUK != TUK_Reference && "References are not specializations");
9311
9312 // NOTE: KWLoc is the location of the tag keyword. This will instead
9313 // store the location of the outermost template keyword in the declaration.
9314 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
9315 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
9316 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
9317 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
9318 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
9319
9320 // Find the class template we're specializing
9321 TemplateName Name = TemplateId.Template.get();
9323 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
9324
9325 if (!ClassTemplate) {
9326 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
9327 << (Name.getAsTemplateDecl() &&
9328 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
9329 return true;
9330 }
9331
9332 bool isMemberSpecialization = false;
9333 bool isPartialSpecialization = false;
9334
9335 if (SS.isSet()) {
9336 if (TUK != TUK_Reference && TUK != TUK_Friend &&
9337 diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
9338 ClassTemplate->getDeclName(),
9339 TemplateNameLoc, &TemplateId,
9340 /*IsMemberSpecialization=*/false))
9341 return true;
9342 }
9343
9344 // Check the validity of the template headers that introduce this
9345 // template.
9346 // FIXME: We probably shouldn't complain about these headers for
9347 // friend declarations.
9348 bool Invalid = false;
9349 TemplateParameterList *TemplateParams =
9351 KWLoc, TemplateNameLoc, SS, &TemplateId,
9352 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
9353 Invalid);
9354 if (Invalid)
9355 return true;
9356
9357 // Check that we can declare a template specialization here.
9358 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
9359 return true;
9360
9361 if (TemplateParams && TemplateParams->size() > 0) {
9362 isPartialSpecialization = true;
9363
9364 if (TUK == TUK_Friend) {
9365 Diag(KWLoc, diag::err_partial_specialization_friend)
9366 << SourceRange(LAngleLoc, RAngleLoc);
9367 return true;
9368 }
9369
9370 // C++ [temp.class.spec]p10:
9371 // The template parameter list of a specialization shall not
9372 // contain default template argument values.
9373 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9374 Decl *Param = TemplateParams->getParam(I);
9375 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
9376 if (TTP->hasDefaultArgument()) {
9378 diag::err_default_arg_in_partial_spec);
9379 TTP->removeDefaultArgument();
9380 }
9381 } else if (NonTypeTemplateParmDecl *NTTP
9382 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
9383 if (Expr *DefArg = NTTP->getDefaultArgument()) {
9384 Diag(NTTP->getDefaultArgumentLoc(),
9385 diag::err_default_arg_in_partial_spec)
9386 << DefArg->getSourceRange();
9387 NTTP->removeDefaultArgument();
9388 }
9389 } else {
9390 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
9391 if (TTP->hasDefaultArgument()) {
9393 diag::err_default_arg_in_partial_spec)
9395 TTP->removeDefaultArgument();
9396 }
9397 }
9398 }
9399 } else if (TemplateParams) {
9400 if (TUK == TUK_Friend)
9401 Diag(KWLoc, diag::err_template_spec_friend)
9403 SourceRange(TemplateParams->getTemplateLoc(),
9404 TemplateParams->getRAngleLoc()))
9405 << SourceRange(LAngleLoc, RAngleLoc);
9406 } else {
9407 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
9408 }
9409
9410 // Check that the specialization uses the same tag kind as the
9411 // original template.
9413 assert(Kind != TagTypeKind::Enum &&
9414 "Invalid enum tag in class template spec!");
9415 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9416 Kind, TUK == TUK_Definition, KWLoc,
9417 ClassTemplate->getIdentifier())) {
9418 Diag(KWLoc, diag::err_use_with_wrong_tag)
9419 << ClassTemplate
9421 ClassTemplate->getTemplatedDecl()->getKindName());
9422 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9423 diag::note_previous_use);
9424 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9425 }
9426
9427 // Translate the parser's template argument list in our AST format.
9428 TemplateArgumentListInfo TemplateArgs =
9429 makeTemplateArgumentListInfo(*this, TemplateId);
9430
9431 // Check for unexpanded parameter packs in any of the template arguments.
9432 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9433 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
9434 isPartialSpecialization
9437 return true;
9438
9439 // Check that the template argument list is well-formed for this
9440 // template.
9441 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9442 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9443 false, SugaredConverted, CanonicalConverted,
9444 /*UpdateArgsWithConversions=*/true))
9445 return true;
9446
9447 // Find the class template (partial) specialization declaration that
9448 // corresponds to these arguments.
9449 if (isPartialSpecialization) {
9451 TemplateArgs.size(),
9452 CanonicalConverted))
9453 return true;
9454
9455 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9456 // also do it during instantiation.
9457 if (!Name.isDependent() &&
9459 TemplateArgs, CanonicalConverted)) {
9460 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9461 << ClassTemplate->getDeclName();
9462 isPartialSpecialization = false;
9463 Invalid = true;
9464 }
9465 }
9466
9467 void *InsertPos = nullptr;
9468 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9469
9470 if (isPartialSpecialization)
9471 PrevDecl = ClassTemplate->findPartialSpecialization(
9472 CanonicalConverted, TemplateParams, InsertPos);
9473 else
9474 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9475
9477
9478 // Check whether we can declare a class template specialization in
9479 // the current scope.
9480 if (TUK != TUK_Friend &&
9482 TemplateNameLoc,
9483 isPartialSpecialization))
9484 return true;
9485
9486 // The canonical type
9487 QualType CanonType;
9488 if (isPartialSpecialization) {
9489 // Build the canonical type that describes the converted template
9490 // arguments of the class template partial specialization.
9491 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9492 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9493 CanonicalConverted);
9494
9495 if (Context.hasSameType(CanonType,
9496 ClassTemplate->getInjectedClassNameSpecialization()) &&
9497 (!Context.getLangOpts().CPlusPlus20 ||
9498 !TemplateParams->hasAssociatedConstraints())) {
9499 // C++ [temp.class.spec]p9b3:
9500 //
9501 // -- The argument list of the specialization shall not be identical
9502 // to the implicit argument list of the primary template.
9503 //
9504 // This rule has since been removed, because it's redundant given DR1495,
9505 // but we keep it because it produces better diagnostics and recovery.
9506 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9507 << /*class template*/0 << (TUK == TUK_Definition)
9508 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9509 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
9510 ClassTemplate->getIdentifier(),
9511 TemplateNameLoc,
9512 Attr,
9513 TemplateParams,
9514 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9515 /*FriendLoc*/SourceLocation(),
9516 TemplateParameterLists.size() - 1,
9517 TemplateParameterLists.data());
9518 }
9519
9520 // Create a new class template partial specialization declaration node.
9522 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
9525 Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
9526 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
9527 TemplateArgs, CanonType, PrevPartial);
9528 SetNestedNameSpecifier(*this, Partial, SS);
9529 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9531 Context, TemplateParameterLists.drop_back(1));
9532 }
9533
9534 if (!PrevPartial)
9535 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
9536 Specialization = Partial;
9537
9538 // If we are providing an explicit specialization of a member class
9539 // template specialization, make a note of that.
9540 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9541 PrevPartial->setMemberSpecialization();
9542
9544 } else {
9545 // Create a new class template specialization declaration node for
9546 // this explicit specialization or friend declaration.
9548 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9549 ClassTemplate, CanonicalConverted, PrevDecl);
9551 if (TemplateParameterLists.size() > 0) {
9552 Specialization->setTemplateParameterListsInfo(Context,
9553 TemplateParameterLists);
9554 }
9555
9556 if (!PrevDecl)
9557 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9558
9560 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9561 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
9562 CanonicalConverted);
9563 } else {
9565 }
9566 }
9567
9568 // C++ [temp.expl.spec]p6:
9569 // If a template, a member template or the member of a class template is
9570 // explicitly specialized then that specialization shall be declared
9571 // before the first use of that specialization that would cause an implicit
9572 // instantiation to take place, in every translation unit in which such a
9573 // use occurs; no diagnostic is required.
9574 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9575 bool Okay = false;
9576 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9577 // Is there any previous explicit specialization declaration?
9579 Okay = true;
9580 break;
9581 }
9582 }
9583
9584 if (!Okay) {
9585 SourceRange Range(TemplateNameLoc, RAngleLoc);
9586 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9588
9589 Diag(PrevDecl->getPointOfInstantiation(),
9590 diag::note_instantiation_required_here)
9591 << (PrevDecl->getTemplateSpecializationKind()
9593 return true;
9594 }
9595 }
9596
9597 // If this is not a friend, note that this is an explicit specialization.
9598 if (TUK != TUK_Friend)
9599 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9600
9601 // Check that this isn't a redefinition of this specialization.
9602 if (TUK == TUK_Definition) {
9603 RecordDecl *Def = Specialization->getDefinition();
9604 NamedDecl *Hidden = nullptr;
9605 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9606 SkipBody->ShouldSkip = true;
9607 SkipBody->Previous = Def;
9609 } else if (Def) {
9610 SourceRange Range(TemplateNameLoc, RAngleLoc);
9611 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9612 Diag(Def->getLocation(), diag::note_previous_definition);
9613 Specialization->setInvalidDecl();
9614 return true;
9615 }
9616 }
9617
9620
9621 // Add alignment attributes if necessary; these attributes are checked when
9622 // the ASTContext lays out the structure.
9623 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9626 }
9627
9628 if (ModulePrivateLoc.isValid())
9629 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9630 << (isPartialSpecialization? 1 : 0)
9631 << FixItHint::CreateRemoval(ModulePrivateLoc);
9632
9633 // Build the fully-sugared type for this class template
9634 // specialization as the user wrote in the specialization
9635 // itself. This means that we'll pretty-print the type retrieved
9636 // from the specialization's declaration the way that the user
9637 // actually wrote the specialization, rather than formatting the
9638 // name based on the "canonical" representation used to store the
9639 // template arguments in the specialization.
9640 TypeSourceInfo *WrittenTy
9641 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9642 TemplateArgs, CanonType);
9643 if (TUK != TUK_Friend) {
9644 Specialization->setTypeAsWritten(WrittenTy);
9645 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
9646 }
9647
9648 // C++ [temp.expl.spec]p9:
9649 // A template explicit specialization is in the scope of the
9650 // namespace in which the template was defined.
9651 //
9652 // We actually implement this paragraph where we set the semantic
9653 // context (in the creation of the ClassTemplateSpecializationDecl),
9654 // but we also maintain the lexical context where the actual
9655 // definition occurs.
9656 Specialization->setLexicalDeclContext(CurContext);
9657
9658 // We may be starting the definition of this specialization.
9659 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9660 Specialization->startDefinition();
9661
9662 if (TUK == TUK_Friend) {
9664 TemplateNameLoc,
9665 WrittenTy,
9666 /*FIXME:*/KWLoc);
9667 Friend->setAccess(AS_public);
9668 CurContext->addDecl(Friend);
9669 } else {
9670 // Add the specialization into its lexical context, so that it can
9671 // be seen when iterating through the list of declarations in that
9672 // context. However, specializations are not found by name lookup.
9674 }
9675
9676 if (SkipBody && SkipBody->ShouldSkip)
9677 return SkipBody->Previous;
9678
9679 Specialization->setInvalidDecl(Invalid);
9680 return Specialization;
9681}
9682
9684 MultiTemplateParamsArg TemplateParameterLists,
9685 Declarator &D) {
9686 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9687 ActOnDocumentableDecl(NewDecl);
9688 return NewDecl;
9689}
9690
9692 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9693 const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr) {
9694 DeclContext *DC = CurContext;
9695
9696 if (!DC->getRedeclContext()->isFileContext()) {
9697 Diag(NameLoc,
9698 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9699 return nullptr;
9700 }
9701
9702 if (TemplateParameterLists.size() > 1) {
9703 Diag(NameLoc, diag::err_concept_extra_headers);
9704 return nullptr;
9705 }
9706
9707 TemplateParameterList *Params = TemplateParameterLists.front();
9708
9709 if (Params->size() == 0) {
9710 Diag(NameLoc, diag::err_concept_no_parameters);
9711 return nullptr;
9712 }
9713
9714 // Ensure that the parameter pack, if present, is the last parameter in the
9715 // template.
9716 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9717 ParamEnd = Params->end();
9718 ParamIt != ParamEnd; ++ParamIt) {
9719 Decl const *Param = *ParamIt;
9720 if (Param->isParameterPack()) {
9721 if (++ParamIt == ParamEnd)
9722 break;
9723 Diag(Param->getLocation(),
9724 diag::err_template_param_pack_must_be_last_template_parameter);
9725 return nullptr;
9726 }
9727 }
9728
9729 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9730 return nullptr;
9731
9732 ConceptDecl *NewDecl =
9733 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9734
9735 if (NewDecl->hasAssociatedConstraints()) {
9736 // C++2a [temp.concept]p4:
9737 // A concept shall not have associated constraints.
9738 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9739 NewDecl->setInvalidDecl();
9740 }
9741
9742 // Check for conflicting previous declaration.
9743 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9744 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9746 LookupName(Previous, S);
9747 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9748 /*AllowInlineNamespace*/false);
9749 bool AddToScope = true;
9750 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9751
9752 ActOnDocumentableDecl(NewDecl);
9753 if (AddToScope)
9754 PushOnScopeChains(NewDecl, S);
9755 return NewDecl;
9756}
9757
9759 LookupResult &Previous, bool &AddToScope) {
9760 AddToScope = true;
9761
9762 if (Previous.empty())
9763 return;
9764
9765 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9766 if (!OldConcept) {
9767 auto *Old = Previous.getRepresentativeDecl();
9768 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9769 << NewDecl->getDeclName();
9770 notePreviousDefinition(Old, NewDecl->getLocation());
9771 AddToScope = false;
9772 return;
9773 }
9774 // Check if we can merge with a concept declaration.
9775 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9776 if (!IsSame) {
9777 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9778 << NewDecl->getDeclName();
9779 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9780 AddToScope = false;
9781 return;
9782 }
9783 if (hasReachableDefinition(OldConcept) &&
9784 IsRedefinitionInModule(NewDecl, OldConcept)) {
9785 Diag(NewDecl->getLocation(), diag::err_redefinition)
9786 << NewDecl->getDeclName();
9787 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9788 AddToScope = false;
9789 return;
9790 }
9791 if (!Previous.isSingleResult()) {
9792 // FIXME: we should produce an error in case of ambig and failed lookups.
9793 // Other decls (e.g. namespaces) also have this shortcoming.
9794 return;
9795 }
9796 // We unwrap canonical decl late to check for module visibility.
9797 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9798}
9799
9800/// \brief Strips various properties off an implicit instantiation
9801/// that has just been explicitly specialized.
9802static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9803 if (MinGW || (isa<FunctionDecl>(D) &&
9804 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9805 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9806
9807 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9808 FD->setInlineSpecified(false);
9809}
9810
9811/// Compute the diagnostic location for an explicit instantiation
9812// declaration or definition.
9814 NamedDecl* D, SourceLocation PointOfInstantiation) {
9815 // Explicit instantiations following a specialization have no effect and
9816 // hence no PointOfInstantiation. In that case, walk decl backwards
9817 // until a valid name loc is found.
9818 SourceLocation PrevDiagLoc = PointOfInstantiation;
9819 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9820 Prev = Prev->getPreviousDecl()) {
9821 PrevDiagLoc = Prev->getLocation();
9822 }
9823 assert(PrevDiagLoc.isValid() &&
9824 "Explicit instantiation without point of instantiation?");
9825 return PrevDiagLoc;
9826}
9827
9828/// Diagnose cases where we have an explicit template specialization
9829/// before/after an explicit template instantiation, producing diagnostics
9830/// for those cases where they are required and determining whether the
9831/// new specialization/instantiation will have any effect.
9832///
9833/// \param NewLoc the location of the new explicit specialization or
9834/// instantiation.
9835///
9836/// \param NewTSK the kind of the new explicit specialization or instantiation.
9837///
9838/// \param PrevDecl the previous declaration of the entity.
9839///
9840/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9841///
9842/// \param PrevPointOfInstantiation if valid, indicates where the previous
9843/// declaration was instantiated (either implicitly or explicitly).
9844///
9845/// \param HasNoEffect will be set to true to indicate that the new
9846/// specialization or instantiation has no effect and should be ignored.
9847///
9848/// \returns true if there was an error that should prevent the introduction of
9849/// the new declaration into the AST, false otherwise.
9850bool
9853 NamedDecl *PrevDecl,
9855 SourceLocation PrevPointOfInstantiation,
9856 bool &HasNoEffect) {
9857 HasNoEffect = false;
9858
9859 switch (NewTSK) {
9860 case TSK_Undeclared:
9862 assert(
9863 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9864 "previous declaration must be implicit!");
9865 return false;
9866
9868 switch (PrevTSK) {
9869 case TSK_Undeclared:
9871 // Okay, we're just specializing something that is either already
9872 // explicitly specialized or has merely been mentioned without any
9873 // instantiation.
9874 return false;
9875
9877 if (PrevPointOfInstantiation.isInvalid()) {
9878 // The declaration itself has not actually been instantiated, so it is
9879 // still okay to specialize it.
9881 PrevDecl,
9882 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9883 return false;
9884 }
9885 // Fall through
9886 [[fallthrough]];
9887
9890 assert((PrevTSK == TSK_ImplicitInstantiation ||
9891 PrevPointOfInstantiation.isValid()) &&
9892 "Explicit instantiation without point of instantiation?");
9893
9894 // C++ [temp.expl.spec]p6:
9895 // If a template, a member template or the member of a class template
9896 // is explicitly specialized then that specialization shall be declared
9897 // before the first use of that specialization that would cause an
9898 // implicit instantiation to take place, in every translation unit in
9899 // which such a use occurs; no diagnostic is required.
9900 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9901 // Is there any previous explicit specialization declaration?
9903 return false;
9904 }
9905
9906 Diag(NewLoc, diag::err_specialization_after_instantiation)
9907 << PrevDecl;
9908 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9909 << (PrevTSK != TSK_ImplicitInstantiation);
9910
9911 return true;
9912 }
9913 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9914
9916 switch (PrevTSK) {
9918 // This explicit instantiation declaration is redundant (that's okay).
9919 HasNoEffect = true;
9920 return false;
9921
9922 case TSK_Undeclared:
9924 // We're explicitly instantiating something that may have already been
9925 // implicitly instantiated; that's fine.
9926 return false;
9927
9929 // C++0x [temp.explicit]p4:
9930 // For a given set of template parameters, if an explicit instantiation
9931 // of a template appears after a declaration of an explicit
9932 // specialization for that template, the explicit instantiation has no
9933 // effect.
9934 HasNoEffect = true;
9935 return false;
9936
9938 // C++0x [temp.explicit]p10:
9939 // If an entity is the subject of both an explicit instantiation
9940 // declaration and an explicit instantiation definition in the same
9941 // translation unit, the definition shall follow the declaration.
9942 Diag(NewLoc,
9943 diag::err_explicit_instantiation_declaration_after_definition);
9944
9945 // Explicit instantiations following a specialization have no effect and
9946 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9947 // until a valid name loc is found.
9948 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9949 diag::note_explicit_instantiation_definition_here);
9950 HasNoEffect = true;
9951 return false;
9952 }
9953 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9954
9956 switch (PrevTSK) {
9957 case TSK_Undeclared:
9959 // We're explicitly instantiating something that may have already been
9960 // implicitly instantiated; that's fine.
9961 return false;
9962
9964 // C++ DR 259, C++0x [temp.explicit]p4:
9965 // For a given set of template parameters, if an explicit
9966 // instantiation of a template appears after a declaration of
9967 // an explicit specialization for that template, the explicit
9968 // instantiation has no effect.
9969 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9970 << PrevDecl;
9971 Diag(PrevDecl->getLocation(),
9972 diag::note_previous_template_specialization);
9973 HasNoEffect = true;
9974 return false;
9975
9977 // We're explicitly instantiating a definition for something for which we
9978 // were previously asked to suppress instantiations. That's fine.
9979
9980 // C++0x [temp.explicit]p4:
9981 // For a given set of template parameters, if an explicit instantiation
9982 // of a template appears after a declaration of an explicit
9983 // specialization for that template, the explicit instantiation has no
9984 // effect.
9985 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9986 // Is there any previous explicit specialization declaration?
9988 HasNoEffect = true;
9989 break;
9990 }
9991 }
9992
9993 return false;
9994
9996 // C++0x [temp.spec]p5:
9997 // For a given template and a given set of template-arguments,
9998 // - an explicit instantiation definition shall appear at most once
9999 // in a program,
10000
10001 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
10002 Diag(NewLoc, (getLangOpts().MSVCCompat)
10003 ? diag::ext_explicit_instantiation_duplicate
10004 : diag::err_explicit_instantiation_duplicate)
10005 << PrevDecl;
10006 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
10007 diag::note_previous_explicit_instantiation);
10008 HasNoEffect = true;
10009 return false;
10010 }
10011 }
10012
10013 llvm_unreachable("Missing specialization/instantiation case?");
10014}
10015
10016/// Perform semantic analysis for the given dependent function
10017/// template specialization.
10018///
10019/// The only possible way to get a dependent function template specialization
10020/// is with a friend declaration, like so:
10021///
10022/// \code
10023/// template <class T> void foo(T);
10024/// template <class T> class A {
10025/// friend void foo<>(T);
10026/// };
10027/// \endcode
10028///
10029/// There really isn't any useful analysis we can do here, so we
10030/// just store the information.
10032 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
10034 // Remove anything from Previous that isn't a function template in
10035 // the correct context.
10036 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10037 LookupResult::Filter F = Previous.makeFilter();
10038 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
10039 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
10040 while (F.hasNext()) {
10041 NamedDecl *D = F.next()->getUnderlyingDecl();
10042 if (!isa<FunctionTemplateDecl>(D)) {
10043 F.erase();
10044 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
10045 continue;
10046 }
10047
10048 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10050 F.erase();
10051 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
10052 continue;
10053 }
10054 }
10055 F.done();
10056
10057 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
10058 if (Previous.empty()) {
10059 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
10060 << IsFriend;
10061 for (auto &P : DiscardedCandidates)
10062 Diag(P.second->getLocation(),
10063 diag::note_dependent_function_template_spec_discard_reason)
10064 << P.first << IsFriend;
10065 return true;
10066 }
10067
10069 ExplicitTemplateArgs);
10070 return false;
10071}
10072
10073/// Perform semantic analysis for the given function template
10074/// specialization.
10075///
10076/// This routine performs all of the semantic analysis required for an
10077/// explicit function template specialization. On successful completion,
10078/// the function declaration \p FD will become a function template
10079/// specialization.
10080///
10081/// \param FD the function declaration, which will be updated to become a
10082/// function template specialization.
10083///
10084/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
10085/// if any. Note that this may be valid info even when 0 arguments are
10086/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
10087/// as it anyway contains info on the angle brackets locations.
10088///
10089/// \param Previous the set of declarations that may be specialized by
10090/// this function specialization.
10091///
10092/// \param QualifiedFriend whether this is a lookup for a qualified friend
10093/// declaration with no explicit template argument list that might be
10094/// befriending a function template specialization.
10096 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
10097 LookupResult &Previous, bool QualifiedFriend) {
10098 // The set of function template specializations that could match this
10099 // explicit function template specialization.
10100 UnresolvedSet<8> Candidates;
10101 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
10102 /*ForTakingAddress=*/false);
10103
10104 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
10105 ConvertedTemplateArgs;
10106
10107 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10108 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10109 I != E; ++I) {
10110 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
10111 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
10112 // Only consider templates found within the same semantic lookup scope as
10113 // FD.
10114 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10116 continue;
10117
10118 // When matching a constexpr member function template specialization
10119 // against the primary template, we don't yet know whether the
10120 // specialization has an implicit 'const' (because we don't know whether
10121 // it will be a static member function until we know which template it
10122 // specializes), so adjust it now assuming it specializes this template.
10123 QualType FT = FD->getType();
10124 if (FD->isConstexpr()) {
10125 CXXMethodDecl *OldMD =
10126 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
10127 if (OldMD && OldMD->isConst()) {
10128 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
10130 EPI.TypeQuals.addConst();
10132 FPT->getParamTypes(), EPI);
10133 }
10134 }
10135
10137 if (ExplicitTemplateArgs)
10138 Args = *ExplicitTemplateArgs;
10139
10140 // C++ [temp.expl.spec]p11:
10141 // A trailing template-argument can be left unspecified in the
10142 // template-id naming an explicit function template specialization
10143 // provided it can be deduced from the function argument type.
10144 // Perform template argument deduction to determine whether we may be
10145 // specializing this template.
10146 // FIXME: It is somewhat wasteful to build
10147 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10148 FunctionDecl *Specialization = nullptr;
10150 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
10151 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
10153 // Template argument deduction failed; record why it failed, so
10154 // that we can provide nifty diagnostics.
10155 FailedCandidates.addCandidate().set(
10156 I.getPair(), FunTmpl->getTemplatedDecl(),
10157 MakeDeductionFailureInfo(Context, TDK, Info));
10158 (void)TDK;
10159 continue;
10160 }
10161
10162 // Target attributes are part of the cuda function signature, so
10163 // the deduced template's cuda target must match that of the
10164 // specialization. Given that C++ template deduction does not
10165 // take target attributes into account, we reject candidates
10166 // here that have a different target.
10167 if (LangOpts.CUDA &&
10169 /* IgnoreImplicitHDAttr = */ true) !=
10170 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
10171 FailedCandidates.addCandidate().set(
10172 I.getPair(), FunTmpl->getTemplatedDecl(),
10175 continue;
10176 }
10177
10178 // Record this candidate.
10179 if (ExplicitTemplateArgs)
10180 ConvertedTemplateArgs[Specialization] = std::move(Args);
10181 Candidates.addDecl(Specialization, I.getAccess());
10182 }
10183 }
10184
10185 // For a qualified friend declaration (with no explicit marker to indicate
10186 // that a template specialization was intended), note all (template and
10187 // non-template) candidates.
10188 if (QualifiedFriend && Candidates.empty()) {
10189 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
10190 << FD->getDeclName() << FDLookupContext;
10191 // FIXME: We should form a single candidate list and diagnose all
10192 // candidates at once, to get proper sorting and limiting.
10193 for (auto *OldND : Previous) {
10194 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
10195 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
10196 }
10197 FailedCandidates.NoteCandidates(*this, FD->getLocation());
10198 return true;
10199 }
10200
10201 // Find the most specialized function template.
10203 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
10204 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
10205 PDiag(diag::err_function_template_spec_ambiguous)
10206 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
10207 PDiag(diag::note_function_template_spec_matched));
10208
10209 if (Result == Candidates.end())
10210 return true;
10211
10212 // Ignore access information; it doesn't figure into redeclaration checking.
10213 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
10214
10215 // C++23 [except.spec]p13:
10216 // An exception specification is considered to be needed when:
10217 // - [...]
10218 // - the exception specification is compared to that of another declaration
10219 // (e.g., an explicit specialization or an overriding virtual function);
10220 // - [...]
10221 //
10222 // The exception specification of a defaulted function is evaluated as
10223 // described above only when needed; similarly, the noexcept-specifier of a
10224 // specialization of a function template or member function of a class
10225 // template is instantiated only when needed.
10226 //
10227 // The standard doesn't specify what the "comparison with another declaration"
10228 // entails, nor the exact circumstances in which it occurs. Moreover, it does
10229 // not state which properties of an explicit specialization must match the
10230 // primary template.
10231 //
10232 // We assume that an explicit specialization must correspond with (per
10233 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
10234 // the declaration produced by substitution into the function template.
10235 //
10236 // Since the determination whether two function declarations correspond does
10237 // not consider exception specification, we only need to instantiate it once
10238 // we determine the primary template when comparing types per
10239 // [basic.link]p11.1.
10240 auto *SpecializationFPT =
10241 Specialization->getType()->castAs<FunctionProtoType>();
10242 // If the function has a dependent exception specification, resolve it after
10243 // we have selected the primary template so we can check whether it matches.
10244 if (getLangOpts().CPlusPlus17 &&
10245 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
10246 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
10247 return true;
10248
10250 = Specialization->getTemplateSpecializationInfo();
10251 assert(SpecInfo && "Function template specialization info missing?");
10252
10253 // Note: do not overwrite location info if previous template
10254 // specialization kind was explicit.
10256 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
10257 Specialization->setLocation(FD->getLocation());
10258 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
10259 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
10260 // function can differ from the template declaration with respect to
10261 // the constexpr specifier.
10262 // FIXME: We need an update record for this AST mutation.
10263 // FIXME: What if there are multiple such prior declarations (for instance,
10264 // from different modules)?
10265 Specialization->setConstexprKind(FD->getConstexprKind());
10266 }
10267
10268 // FIXME: Check if the prior specialization has a point of instantiation.
10269 // If so, we have run afoul of .
10270
10271 // If this is a friend declaration, then we're not really declaring
10272 // an explicit specialization.
10273 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
10274
10275 // Check the scope of this explicit specialization.
10276 if (!isFriend &&
10278 Specialization->getPrimaryTemplate(),
10280 false))
10281 return true;
10282
10283 // C++ [temp.expl.spec]p6:
10284 // If a template, a member template or the member of a class template is
10285 // explicitly specialized then that specialization shall be declared
10286 // before the first use of that specialization that would cause an implicit
10287 // instantiation to take place, in every translation unit in which such a
10288 // use occurs; no diagnostic is required.
10289 bool HasNoEffect = false;
10290 if (!isFriend &&
10295 SpecInfo->getPointOfInstantiation(),
10296 HasNoEffect))
10297 return true;
10298
10299 // Mark the prior declaration as an explicit specialization, so that later
10300 // clients know that this is an explicit specialization.
10301 if (!isFriend) {
10302 // Since explicit specializations do not inherit '=delete' from their
10303 // primary function template - check if the 'specialization' that was
10304 // implicitly generated (during template argument deduction for partial
10305 // ordering) from the most specialized of all the function templates that
10306 // 'FD' could have been specializing, has a 'deleted' definition. If so,
10307 // first check that it was implicitly generated during template argument
10308 // deduction by making sure it wasn't referenced, and then reset the deleted
10309 // flag to not-deleted, so that we can inherit that information from 'FD'.
10310 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
10311 !Specialization->getCanonicalDecl()->isReferenced()) {
10312 // FIXME: This assert will not hold in the presence of modules.
10313 assert(
10314 Specialization->getCanonicalDecl() == Specialization &&
10315 "This must be the only existing declaration of this specialization");
10316 // FIXME: We need an update record for this AST mutation.
10317 Specialization->setDeletedAsWritten(false);
10318 }
10319 // FIXME: We need an update record for this AST mutation.
10322 }
10323
10324 // Turn the given function declaration into a function template
10325 // specialization, with the template arguments from the previous
10326 // specialization.
10327 // Take copies of (semantic and syntactic) template argument lists.
10329 Context, Specialization->getTemplateSpecializationArgs()->asArray());
10330 FD->setFunctionTemplateSpecialization(
10331 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
10333 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
10334
10335 // A function template specialization inherits the target attributes
10336 // of its template. (We require the attributes explicitly in the
10337 // code to match, but a template may have implicit attributes by
10338 // virtue e.g. of being constexpr, and it passes these implicit
10339 // attributes on to its specializations.)
10340 if (LangOpts.CUDA)
10341 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
10342
10343 // The "previous declaration" for this function template specialization is
10344 // the prior function template specialization.
10345 Previous.clear();
10346 Previous.addDecl(Specialization);
10347 return false;
10348}
10349
10350/// Perform semantic analysis for the given non-template member
10351/// specialization.
10352///
10353/// This routine performs all of the semantic analysis required for an
10354/// explicit member function specialization. On successful completion,
10355/// the function declaration \p FD will become a member function
10356/// specialization.
10357///
10358/// \param Member the member declaration, which will be updated to become a
10359/// specialization.
10360///
10361/// \param Previous the set of declarations, one of which may be specialized
10362/// by this function specialization; the set will be modified to contain the
10363/// redeclared member.
10364bool
10366 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
10367
10368 // Try to find the member we are instantiating.
10369 NamedDecl *FoundInstantiation = nullptr;
10370 NamedDecl *Instantiation = nullptr;
10371 NamedDecl *InstantiatedFrom = nullptr;
10372 MemberSpecializationInfo *MSInfo = nullptr;
10373
10374 if (Previous.empty()) {
10375 // Nowhere to look anyway.
10376 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
10377 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10378 I != E; ++I) {
10379 NamedDecl *D = (*I)->getUnderlyingDecl();
10380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
10381 QualType Adjusted = Function->getType();
10382 if (!hasExplicitCallingConv(Adjusted))
10383 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
10384 // This doesn't handle deduced return types, but both function
10385 // declarations should be undeduced at this point.
10386 if (Context.hasSameType(Adjusted, Method->getType())) {
10387 FoundInstantiation = *I;
10388 Instantiation = Method;
10389 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
10390 MSInfo = Method->getMemberSpecializationInfo();
10391 break;
10392 }
10393 }
10394 }
10395 } else if (isa<VarDecl>(Member)) {
10396 VarDecl *PrevVar;
10397 if (Previous.isSingleResult() &&
10398 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
10399 if (PrevVar->isStaticDataMember()) {
10400 FoundInstantiation = Previous.getRepresentativeDecl();
10401 Instantiation = PrevVar;
10402 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10403 MSInfo = PrevVar->getMemberSpecializationInfo();
10404 }
10405 } else if (isa<RecordDecl>(Member)) {
10406 CXXRecordDecl *PrevRecord;
10407 if (Previous.isSingleResult() &&
10408 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
10409 FoundInstantiation = Previous.getRepresentativeDecl();
10410 Instantiation = PrevRecord;
10411 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10412 MSInfo = PrevRecord->getMemberSpecializationInfo();
10413 }
10414 } else if (isa<EnumDecl>(Member)) {
10415 EnumDecl *PrevEnum;
10416 if (Previous.isSingleResult() &&
10417 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
10418 FoundInstantiation = Previous.getRepresentativeDecl();
10419 Instantiation = PrevEnum;
10420 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10421 MSInfo = PrevEnum->getMemberSpecializationInfo();
10422 }
10423 }
10424
10425 if (!Instantiation) {
10426 // There is no previous declaration that matches. Since member
10427 // specializations are always out-of-line, the caller will complain about
10428 // this mismatch later.
10429 return false;
10430 }
10431
10432 // A member specialization in a friend declaration isn't really declaring
10433 // an explicit specialization, just identifying a specific (possibly implicit)
10434 // specialization. Don't change the template specialization kind.
10435 //
10436 // FIXME: Is this really valid? Other compilers reject.
10437 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10438 // Preserve instantiation information.
10439 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
10440 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
10441 cast<CXXMethodDecl>(InstantiatedFrom),
10442 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
10443 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
10444 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
10445 cast<CXXRecordDecl>(InstantiatedFrom),
10446 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
10447 }
10448
10449 Previous.clear();
10450 Previous.addDecl(FoundInstantiation);
10451 return false;
10452 }
10453
10454 // Make sure that this is a specialization of a member.
10455 if (!InstantiatedFrom) {
10456 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10457 << Member;
10458 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10459 return true;
10460 }
10461
10462 // C++ [temp.expl.spec]p6:
10463 // If a template, a member template or the member of a class template is
10464 // explicitly specialized then that specialization shall be declared
10465 // before the first use of that specialization that would cause an implicit
10466 // instantiation to take place, in every translation unit in which such a
10467 // use occurs; no diagnostic is required.
10468 assert(MSInfo && "Member specialization info missing?");
10469
10470 bool HasNoEffect = false;
10473 Instantiation,
10475 MSInfo->getPointOfInstantiation(),
10476 HasNoEffect))
10477 return true;
10478
10479 // Check the scope of this explicit specialization.
10481 InstantiatedFrom,
10482 Instantiation, Member->getLocation(),
10483 false))
10484 return true;
10485
10486 // Note that this member specialization is an "instantiation of" the
10487 // corresponding member of the original template.
10488 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
10489 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
10490 if (InstantiationFunction->getTemplateSpecializationKind() ==
10492 // Explicit specializations of member functions of class templates do not
10493 // inherit '=delete' from the member function they are specializing.
10494 if (InstantiationFunction->isDeleted()) {
10495 // FIXME: This assert will not hold in the presence of modules.
10496 assert(InstantiationFunction->getCanonicalDecl() ==
10497 InstantiationFunction);
10498 // FIXME: We need an update record for this AST mutation.
10499 InstantiationFunction->setDeletedAsWritten(false);
10500 }
10501 }
10502
10503 MemberFunction->setInstantiationOfMemberFunction(
10504 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10505 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
10506 MemberVar->setInstantiationOfStaticDataMember(
10507 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10508 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
10509 MemberClass->setInstantiationOfMemberClass(
10510 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10511 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
10512 MemberEnum->setInstantiationOfMemberEnum(
10513 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
10514 } else {
10515 llvm_unreachable("unknown member specialization kind");
10516 }
10517
10518 // Save the caller the trouble of having to figure out which declaration
10519 // this specialization matches.
10520 Previous.clear();
10521 Previous.addDecl(FoundInstantiation);
10522 return false;
10523}
10524
10525/// Complete the explicit specialization of a member of a class template by
10526/// updating the instantiated member to be marked as an explicit specialization.
10527///
10528/// \param OrigD The member declaration instantiated from the template.
10529/// \param Loc The location of the explicit specialization of the member.
10530template<typename DeclT>
10531static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10532 SourceLocation Loc) {
10533 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10534 return;
10535
10536 // FIXME: Inform AST mutation listeners of this AST mutation.
10537 // FIXME: If there are multiple in-class declarations of the member (from
10538 // multiple modules, or a declaration and later definition of a member type),
10539 // should we update all of them?
10540 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10541 OrigD->setLocation(Loc);
10542}
10543
10546 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10547 if (Instantiation == Member)
10548 return;
10549
10550 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10551 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10552 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10553 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10554 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10555 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10556 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10557 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10558 else
10559 llvm_unreachable("unknown member specialization kind");
10560}
10561
10562/// Check the scope of an explicit instantiation.
10563///
10564/// \returns true if a serious error occurs, false otherwise.
10566 SourceLocation InstLoc,
10567 bool WasQualifiedName) {
10569 DeclContext *CurContext = S.CurContext->getRedeclContext();
10570
10571 if (CurContext->isRecord()) {
10572 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10573 << D;
10574 return true;
10575 }
10576
10577 // C++11 [temp.explicit]p3:
10578 // An explicit instantiation shall appear in an enclosing namespace of its
10579 // template. If the name declared in the explicit instantiation is an
10580 // unqualified name, the explicit instantiation shall appear in the
10581 // namespace where its template is declared or, if that namespace is inline
10582 // (7.3.1), any namespace from its enclosing namespace set.
10583 //
10584 // This is DR275, which we do not retroactively apply to C++98/03.
10585 if (WasQualifiedName) {
10586 if (CurContext->Encloses(OrigContext))
10587 return false;
10588 } else {
10589 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
10590 return false;
10591 }
10592
10593 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
10594 if (WasQualifiedName)
10595 S.Diag(InstLoc,
10596 S.getLangOpts().CPlusPlus11?
10597 diag::err_explicit_instantiation_out_of_scope :
10598 diag::warn_explicit_instantiation_out_of_scope_0x)
10599 << D << NS;
10600 else
10601 S.Diag(InstLoc,
10602 S.getLangOpts().CPlusPlus11?
10603 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10604 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10605 << D << NS;
10606 } else
10607 S.Diag(InstLoc,
10608 S.getLangOpts().CPlusPlus11?
10609 diag::err_explicit_instantiation_must_be_global :
10610 diag::warn_explicit_instantiation_must_be_global_0x)
10611 << D;
10612 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10613 return false;
10614}
10615
10616/// Common checks for whether an explicit instantiation of \p D is valid.
10618 SourceLocation InstLoc,
10619 bool WasQualifiedName,
10621 // C++ [temp.explicit]p13:
10622 // An explicit instantiation declaration shall not name a specialization of
10623 // a template with internal linkage.
10626 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10627 return true;
10628 }
10629
10630 // C++11 [temp.explicit]p3: [DR 275]
10631 // An explicit instantiation shall appear in an enclosing namespace of its
10632 // template.
10633 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10634 return true;
10635
10636 return false;
10637}
10638
10639/// Determine whether the given scope specifier has a template-id in it.
10641 if (!SS.isSet())
10642 return false;
10643
10644 // C++11 [temp.explicit]p3:
10645 // If the explicit instantiation is for a member function, a member class
10646 // or a static data member of a class template specialization, the name of
10647 // the class template specialization in the qualified-id for the member
10648 // name shall be a simple-template-id.
10649 //
10650 // C++98 has the same restriction, just worded differently.
10651 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10652 NNS = NNS->getPrefix())
10653 if (const Type *T = NNS->getAsType())
10654 if (isa<TemplateSpecializationType>(T))
10655 return true;
10656
10657 return false;
10658}
10659
10660/// Make a dllexport or dllimport attr on a class template specialization take
10661/// effect.
10664 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
10665 assert(A && "dllExportImportClassTemplateSpecialization called "
10666 "on Def without dllexport or dllimport");
10667
10668 // We reject explicit instantiations in class scope, so there should
10669 // never be any delayed exported classes to worry about.
10670 assert(S.DelayedDllExportClasses.empty() &&
10671 "delayed exports present at explicit instantiation");
10673
10674 // Propagate attribute to base class templates.
10675 for (auto &B : Def->bases()) {
10676 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10677 B.getType()->getAsCXXRecordDecl()))
10679 }
10680
10682}
10683
10684// Explicit instantiation of a class template specialization
10686 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10687 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10688 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10689 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10690 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10691 // Find the class template we're specializing
10692 TemplateName Name = TemplateD.get();
10693 TemplateDecl *TD = Name.getAsTemplateDecl();
10694 // Check that the specialization uses the same tag kind as the
10695 // original template.
10697 assert(Kind != TagTypeKind::Enum &&
10698 "Invalid enum tag in class template explicit instantiation!");
10699
10700 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
10701
10702 if (!ClassTemplate) {
10703 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10704 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10705 << TD << NTK << llvm::to_underlying(Kind);
10706 Diag(TD->getLocation(), diag::note_previous_use);
10707 return true;
10708 }
10709
10710 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
10711 Kind, /*isDefinition*/false, KWLoc,
10712 ClassTemplate->getIdentifier())) {
10713 Diag(KWLoc, diag::err_use_with_wrong_tag)
10714 << ClassTemplate
10716 ClassTemplate->getTemplatedDecl()->getKindName());
10717 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10718 diag::note_previous_use);
10719 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10720 }
10721
10722 // C++0x [temp.explicit]p2:
10723 // There are two forms of explicit instantiation: an explicit instantiation
10724 // definition and an explicit instantiation declaration. An explicit
10725 // instantiation declaration begins with the extern keyword. [...]
10726 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10729
10731 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10732 // Check for dllexport class template instantiation declarations,
10733 // except for MinGW mode.
10734 for (const ParsedAttr &AL : Attr) {
10735 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10736 Diag(ExternLoc,
10737 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10738 Diag(AL.getLoc(), diag::note_attribute);
10739 break;
10740 }
10741 }
10742
10743 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10744 Diag(ExternLoc,
10745 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10746 Diag(A->getLocation(), diag::note_attribute);
10747 }
10748 }
10749
10750 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10751 // instantiation declarations for most purposes.
10752 bool DLLImportExplicitInstantiationDef = false;
10755 // Check for dllimport class template instantiation definitions.
10756 bool DLLImport =
10757 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10758 for (const ParsedAttr &AL : Attr) {
10759 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10760 DLLImport = true;
10761 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10762 // dllexport trumps dllimport here.
10763 DLLImport = false;
10764 break;
10765 }
10766 }
10767 if (DLLImport) {
10769 DLLImportExplicitInstantiationDef = true;
10770 }
10771 }
10772
10773 // Translate the parser's template argument list in our AST format.
10774 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10775 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10776
10777 // Check that the template argument list is well-formed for this
10778 // template.
10779 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10780 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10781 false, SugaredConverted, CanonicalConverted,
10782 /*UpdateArgsWithConversions=*/true))
10783 return true;
10784
10785 // Find the class template specialization declaration that
10786 // corresponds to these arguments.
10787 void *InsertPos = nullptr;
10789 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10790
10791 TemplateSpecializationKind PrevDecl_TSK
10792 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10793
10794 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10795 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10796 // Check for dllexport class template instantiation definitions in MinGW
10797 // mode, if a previous declaration of the instantiation was seen.
10798 for (const ParsedAttr &AL : Attr) {
10799 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10800 Diag(AL.getLoc(),
10801 diag::warn_attribute_dllexport_explicit_instantiation_def);
10802 break;
10803 }
10804 }
10805 }
10806
10807 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10808 SS.isSet(), TSK))
10809 return true;
10810
10812
10813 bool HasNoEffect = false;
10814 if (PrevDecl) {
10815 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10816 PrevDecl, PrevDecl_TSK,
10817 PrevDecl->getPointOfInstantiation(),
10818 HasNoEffect))
10819 return PrevDecl;
10820
10821 // Even though HasNoEffect == true means that this explicit instantiation
10822 // has no effect on semantics, we go on to put its syntax in the AST.
10823
10824 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10825 PrevDecl_TSK == TSK_Undeclared) {
10826 // Since the only prior class template specialization with these
10827 // arguments was referenced but not declared, reuse that
10828 // declaration node as our own, updating the source location
10829 // for the template name to reflect our new declaration.
10830 // (Other source locations will be updated later.)
10831 Specialization = PrevDecl;
10832 Specialization->setLocation(TemplateNameLoc);
10833 PrevDecl = nullptr;
10834 }
10835
10836 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10837 DLLImportExplicitInstantiationDef) {
10838 // The new specialization might add a dllimport attribute.
10839 HasNoEffect = false;
10840 }
10841 }
10842
10843 if (!Specialization) {
10844 // Create a new class template specialization declaration node for
10845 // this explicit specialization.
10847 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10848 ClassTemplate, CanonicalConverted, PrevDecl);
10850
10851 // A MSInheritanceAttr attached to the previous declaration must be
10852 // propagated to the new node prior to instantiation.
10853 if (PrevDecl) {
10854 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10855 auto *Clone = A->clone(getASTContext());
10856 Clone->setInherited(true);
10857 Specialization->addAttr(Clone);
10859 }
10860 }
10861
10862 if (!HasNoEffect && !PrevDecl) {
10863 // Insert the new specialization.
10864 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10865 }
10866 }
10867
10868 // Build the fully-sugared type for this explicit instantiation as
10869 // the user wrote in the explicit instantiation itself. This means
10870 // that we'll pretty-print the type retrieved from the
10871 // specialization's declaration the way that the user actually wrote
10872 // the explicit instantiation, rather than formatting the name based
10873 // on the "canonical" representation used to store the template
10874 // arguments in the specialization.
10875 TypeSourceInfo *WrittenTy
10876 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10877 TemplateArgs,
10879 Specialization->setTypeAsWritten(WrittenTy);
10880
10881 // Set source locations for keywords.
10882 Specialization->setExternLoc(ExternLoc);
10883 Specialization->setTemplateKeywordLoc(TemplateLoc);
10884 Specialization->setBraceRange(SourceRange());
10885
10886 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10889
10890 // Add the explicit instantiation into its lexical context. However,
10891 // since explicit instantiations are never found by name lookup, we
10892 // just put it into the declaration context directly.
10893 Specialization->setLexicalDeclContext(CurContext);
10895
10896 // Syntax is now OK, so return if it has no other effect on semantics.
10897 if (HasNoEffect) {
10898 // Set the template specialization kind.
10899 Specialization->setTemplateSpecializationKind(TSK);
10900 return Specialization;
10901 }
10902
10903 // C++ [temp.explicit]p3:
10904 // A definition of a class template or class member template
10905 // shall be in scope at the point of the explicit instantiation of
10906 // the class template or class member template.
10907 //
10908 // This check comes when we actually try to perform the
10909 // instantiation.
10911 = cast_or_null<ClassTemplateSpecializationDecl>(
10912 Specialization->getDefinition());
10913 if (!Def)
10915 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10916 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10917 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10918 }
10919
10920 // Instantiate the members of this class template specialization.
10921 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10922 Specialization->getDefinition());
10923 if (Def) {
10925 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10926 // TSK_ExplicitInstantiationDefinition
10927 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10929 DLLImportExplicitInstantiationDef)) {
10930 // FIXME: Need to notify the ASTMutationListener that we did this.
10932
10933 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10935 !Context.getTargetInfo().getTriple().isPS())) {
10936 // An explicit instantiation definition can add a dll attribute to a
10937 // template with a previous instantiation declaration. MinGW doesn't
10938 // allow this.
10939 auto *A = cast<InheritableAttr>(
10941 A->setInherited(true);
10942 Def->addAttr(A);
10944 }
10945 }
10946
10947 // Fix a TSK_ImplicitInstantiation followed by a
10948 // TSK_ExplicitInstantiationDefinition
10949 bool NewlyDLLExported =
10950 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10951 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10953 !Context.getTargetInfo().getTriple().isPS())) {
10954 // An explicit instantiation definition can add a dll attribute to a
10955 // template with a previous implicit instantiation. MinGW doesn't allow
10956 // this. We limit clang to only adding dllexport, to avoid potentially
10957 // strange codegen behavior. For example, if we extend this conditional
10958 // to dllimport, and we have a source file calling a method on an
10959 // implicitly instantiated template class instance and then declaring a
10960 // dllimport explicit instantiation definition for the same template
10961 // class, the codegen for the method call will not respect the dllimport,
10962 // while it will with cl. The Def will already have the DLL attribute,
10963 // since the Def and Specialization will be the same in the case of
10964 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10965 // attribute to the Specialization; we just need to make it take effect.
10966 assert(Def == Specialization &&
10967 "Def and Specialization should match for implicit instantiation");
10969 }
10970
10971 // In MinGW mode, export the template instantiation if the declaration
10972 // was marked dllexport.
10973 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10974 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10975 PrevDecl->hasAttr<DLLExportAttr>()) {
10977 }
10978
10979 // Set the template specialization kind. Make sure it is set before
10980 // instantiating the members which will trigger ASTConsumer callbacks.
10981 Specialization->setTemplateSpecializationKind(TSK);
10982 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10983 } else {
10984
10985 // Set the template specialization kind.
10986 Specialization->setTemplateSpecializationKind(TSK);
10987 }
10988
10989 return Specialization;
10990}
10991
10992// Explicit instantiation of a member class of a class template.
10995 SourceLocation TemplateLoc, unsigned TagSpec,
10996 SourceLocation KWLoc, CXXScopeSpec &SS,
10997 IdentifierInfo *Name, SourceLocation NameLoc,
10998 const ParsedAttributesView &Attr) {
10999
11000 bool Owned = false;
11001 bool IsDependent = false;
11002 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
11003 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
11004 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
11005 false, TypeResult(), /*IsTypeSpecifier*/ false,
11006 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
11007 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
11008
11009 if (!TagD)
11010 return true;
11011
11012 TagDecl *Tag = cast<TagDecl>(TagD);
11013 assert(!Tag->isEnum() && "shouldn't see enumerations here");
11014
11015 if (Tag->isInvalidDecl())
11016 return true;
11017
11018 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
11019 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
11020 if (!Pattern) {
11021 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
11023 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
11024 return true;
11025 }
11026
11027 // C++0x [temp.explicit]p2:
11028 // If the explicit instantiation is for a class or member class, the
11029 // elaborated-type-specifier in the declaration shall include a
11030 // simple-template-id.
11031 //
11032 // C++98 has the same restriction, just worded differently.
11034 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
11035 << Record << SS.getRange();
11036
11037 // C++0x [temp.explicit]p2:
11038 // There are two forms of explicit instantiation: an explicit instantiation
11039 // definition and an explicit instantiation declaration. An explicit
11040 // instantiation declaration begins with the extern keyword. [...]
11044
11045 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
11046
11047 // Verify that it is okay to explicitly instantiate here.
11048 CXXRecordDecl *PrevDecl
11049 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
11050 if (!PrevDecl && Record->getDefinition())
11051 PrevDecl = Record;
11052 if (PrevDecl) {
11054 bool HasNoEffect = false;
11055 assert(MSInfo && "No member specialization information?");
11056 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
11057 PrevDecl,
11059 MSInfo->getPointOfInstantiation(),
11060 HasNoEffect))
11061 return true;
11062 if (HasNoEffect)
11063 return TagD;
11064 }
11065
11066 CXXRecordDecl *RecordDef
11067 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
11068 if (!RecordDef) {
11069 // C++ [temp.explicit]p3:
11070 // A definition of a member class of a class template shall be in scope
11071 // at the point of an explicit instantiation of the member class.
11072 CXXRecordDecl *Def
11073 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
11074 if (!Def) {
11075 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
11076 << 0 << Record->getDeclName() << Record->getDeclContext();
11077 Diag(Pattern->getLocation(), diag::note_forward_declaration)
11078 << Pattern;
11079 return true;
11080 } else {
11081 if (InstantiateClass(NameLoc, Record, Def,
11083 TSK))
11084 return true;
11085
11086 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
11087 if (!RecordDef)
11088 return true;
11089 }
11090 }
11091
11092 // Instantiate all of the members of the class.
11093 InstantiateClassMembers(NameLoc, RecordDef,
11095
11097 MarkVTableUsed(NameLoc, RecordDef, true);
11098
11099 // FIXME: We don't have any representation for explicit instantiations of
11100 // member classes. Such a representation is not needed for compilation, but it
11101 // should be available for clients that want to see all of the declarations in
11102 // the source code.
11103 return TagD;
11104}
11105
11107 SourceLocation ExternLoc,
11108 SourceLocation TemplateLoc,
11109 Declarator &D) {
11110 // Explicit instantiations always require a name.
11111 // TODO: check if/when DNInfo should replace Name.
11113 DeclarationName Name = NameInfo.getName();
11114 if (!Name) {
11115 if (!D.isInvalidType())
11117 diag::err_explicit_instantiation_requires_name)
11119
11120 return true;
11121 }
11122
11123 // Get the innermost enclosing declaration scope.
11124 S = S->getDeclParent();
11125
11126 // Determine the type of the declaration.
11128 QualType R = T->getType();
11129 if (R.isNull())
11130 return true;
11131
11132 // C++ [dcl.stc]p1:
11133 // A storage-class-specifier shall not be specified in [...] an explicit
11134 // instantiation (14.7.2) directive.
11136 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
11137 << Name;
11138 return true;
11139 } else if (D.getDeclSpec().getStorageClassSpec()
11141 // Complain about then remove the storage class specifier.
11142 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
11144
11146 }
11147
11148 // C++0x [temp.explicit]p1:
11149 // [...] An explicit instantiation of a function template shall not use the
11150 // inline or constexpr specifiers.
11151 // Presumably, this also applies to member functions of class templates as
11152 // well.
11156 diag::err_explicit_instantiation_inline :
11157 diag::warn_explicit_instantiation_inline_0x)
11160 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
11161 // not already specified.
11163 diag::err_explicit_instantiation_constexpr);
11164
11165 // A deduction guide is not on the list of entities that can be explicitly
11166 // instantiated.
11167 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
11168 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
11169 << /*explicit instantiation*/ 0;
11170 return true;
11171 }
11172
11173 // C++0x [temp.explicit]p2:
11174 // There are two forms of explicit instantiation: an explicit instantiation
11175 // definition and an explicit instantiation declaration. An explicit
11176 // instantiation declaration begins with the extern keyword. [...]
11180
11181 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
11183
11184 if (!R->isFunctionType()) {
11185 // C++ [temp.explicit]p1:
11186 // A [...] static data member of a class template can be explicitly
11187 // instantiated from the member definition associated with its class
11188 // template.
11189 // C++1y [temp.explicit]p1:
11190 // A [...] variable [...] template specialization can be explicitly
11191 // instantiated from its template.
11192 if (Previous.isAmbiguous())
11193 return true;
11194
11195 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
11196 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
11197
11198 if (!PrevTemplate) {
11199 if (!Prev || !Prev->isStaticDataMember()) {
11200 // We expect to see a static data member here.
11201 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
11202 << Name;
11203 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11204 P != PEnd; ++P)
11205 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
11206 return true;
11207 }
11208
11210 // FIXME: Check for explicit specialization?
11212 diag::err_explicit_instantiation_data_member_not_instantiated)
11213 << Prev;
11214 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
11215 // FIXME: Can we provide a note showing where this was declared?
11216 return true;
11217 }
11218 } else {
11219 // Explicitly instantiate a variable template.
11220
11221 // C++1y [dcl.spec.auto]p6:
11222 // ... A program that uses auto or decltype(auto) in a context not
11223 // explicitly allowed in this section is ill-formed.
11224 //
11225 // This includes auto-typed variable template instantiations.
11226 if (R->isUndeducedType()) {
11227 Diag(T->getTypeLoc().getBeginLoc(),
11228 diag::err_auto_not_allowed_var_inst);
11229 return true;
11230 }
11231
11233 // C++1y [temp.explicit]p3:
11234 // If the explicit instantiation is for a variable, the unqualified-id
11235 // in the declaration shall be a template-id.
11237 diag::err_explicit_instantiation_without_template_id)
11238 << PrevTemplate;
11239 Diag(PrevTemplate->getLocation(),
11240 diag::note_explicit_instantiation_here);
11241 return true;
11242 }
11243
11244 // Translate the parser's template argument list into our AST format.
11245 TemplateArgumentListInfo TemplateArgs =
11247
11248 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
11249 D.getIdentifierLoc(), TemplateArgs);
11250 if (Res.isInvalid())
11251 return true;
11252
11253 if (!Res.isUsable()) {
11254 // We somehow specified dependent template arguments in an explicit
11255 // instantiation. This should probably only happen during error
11256 // recovery.
11257 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
11258 return true;
11259 }
11260
11261 // Ignore access control bits, we don't need them for redeclaration
11262 // checking.
11263 Prev = cast<VarDecl>(Res.get());
11264 }
11265
11266 // C++0x [temp.explicit]p2:
11267 // If the explicit instantiation is for a member function, a member class
11268 // or a static data member of a class template specialization, the name of
11269 // the class template specialization in the qualified-id for the member
11270 // name shall be a simple-template-id.
11271 //
11272 // C++98 has the same restriction, just worded differently.
11273 //
11274 // This does not apply to variable template specializations, where the
11275 // template-id is in the unqualified-id instead.
11276 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
11278 diag::ext_explicit_instantiation_without_qualified_id)
11279 << Prev << D.getCXXScopeSpec().getRange();
11280
11281 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
11282
11283 // Verify that it is okay to explicitly instantiate here.
11286 bool HasNoEffect = false;
11288 PrevTSK, POI, HasNoEffect))
11289 return true;
11290
11291 if (!HasNoEffect) {
11292 // Instantiate static data member or variable template.
11294 // Merge attributes.
11296 if (PrevTemplate)
11297 ProcessAPINotes(Prev);
11298
11301 }
11302
11303 // Check the new variable specialization against the parsed input.
11304 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
11305 Diag(T->getTypeLoc().getBeginLoc(),
11306 diag::err_invalid_var_template_spec_type)
11307 << 0 << PrevTemplate << R << Prev->getType();
11308 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11309 << 2 << PrevTemplate->getDeclName();
11310 return true;
11311 }
11312
11313 // FIXME: Create an ExplicitInstantiation node?
11314 return (Decl*) nullptr;
11315 }
11316
11317 // If the declarator is a template-id, translate the parser's template
11318 // argument list into our AST format.
11319 bool HasExplicitTemplateArgs = false;
11320 TemplateArgumentListInfo TemplateArgs;
11322 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
11323 HasExplicitTemplateArgs = true;
11324 }
11325
11326 // C++ [temp.explicit]p1:
11327 // A [...] function [...] can be explicitly instantiated from its template.
11328 // A member function [...] of a class template can be explicitly
11329 // instantiated from the member definition associated with its class
11330 // template.
11331 UnresolvedSet<8> TemplateMatches;
11332 FunctionDecl *NonTemplateMatch = nullptr;
11333 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
11334 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11335 P != PEnd; ++P) {
11336 NamedDecl *Prev = *P;
11337 if (!HasExplicitTemplateArgs) {
11338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
11339 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
11340 /*AdjustExceptionSpec*/true);
11341 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
11342 if (Method->getPrimaryTemplate()) {
11343 TemplateMatches.addDecl(Method, P.getAccess());
11344 } else {
11345 // FIXME: Can this assert ever happen? Needs a test.
11346 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
11347 NonTemplateMatch = Method;
11348 }
11349 }
11350 }
11351 }
11352
11353 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
11354 if (!FunTmpl)
11355 continue;
11356
11357 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11358 FunctionDecl *Specialization = nullptr;
11360 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
11361 Specialization, Info);
11363 // Keep track of almost-matches.
11364 FailedCandidates.addCandidate()
11365 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
11366 MakeDeductionFailureInfo(Context, TDK, Info));
11367 (void)TDK;
11368 continue;
11369 }
11370
11371 // Target attributes are part of the cuda function signature, so
11372 // the cuda target of the instantiated function must match that of its
11373 // template. Given that C++ template deduction does not take
11374 // target attributes into account, we reject candidates here that
11375 // have a different target.
11376 if (LangOpts.CUDA &&
11378 /* IgnoreImplicitHDAttr = */ true) !=
11380 FailedCandidates.addCandidate().set(
11381 P.getPair(), FunTmpl->getTemplatedDecl(),
11384 continue;
11385 }
11386
11387 TemplateMatches.addDecl(Specialization, P.getAccess());
11388 }
11389
11390 FunctionDecl *Specialization = NonTemplateMatch;
11391 if (!Specialization) {
11392 // Find the most specialized function template specialization.
11394 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
11395 D.getIdentifierLoc(),
11396 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11397 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11398 PDiag(diag::note_explicit_instantiation_candidate));
11399
11400 if (Result == TemplateMatches.end())
11401 return true;
11402
11403 // Ignore access control bits, we don't need them for redeclaration checking.
11404 Specialization = cast<FunctionDecl>(*Result);
11405 }
11406
11407 // C++11 [except.spec]p4
11408 // In an explicit instantiation an exception-specification may be specified,
11409 // but is not required.
11410 // If an exception-specification is specified in an explicit instantiation
11411 // directive, it shall be compatible with the exception-specifications of
11412 // other declarations of that function.
11413 if (auto *FPT = R->getAs<FunctionProtoType>())
11414 if (FPT->hasExceptionSpec()) {
11415 unsigned DiagID =
11416 diag::err_mismatched_exception_spec_explicit_instantiation;
11417 if (getLangOpts().MicrosoftExt)
11418 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11420 PDiag(DiagID) << Specialization->getType(),
11421 PDiag(diag::note_explicit_instantiation_here),
11422 Specialization->getType()->getAs<FunctionProtoType>(),
11423 Specialization->getLocation(), FPT, D.getBeginLoc());
11424 // In Microsoft mode, mismatching exception specifications just cause a
11425 // warning.
11426 if (!getLangOpts().MicrosoftExt && Result)
11427 return true;
11428 }
11429
11430 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11432 diag::err_explicit_instantiation_member_function_not_instantiated)
11434 << (Specialization->getTemplateSpecializationKind() ==
11436 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11437 return true;
11438 }
11439
11440 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11441 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11442 PrevDecl = Specialization;
11443
11444 if (PrevDecl) {
11445 bool HasNoEffect = false;
11447 PrevDecl,
11449 PrevDecl->getPointOfInstantiation(),
11450 HasNoEffect))
11451 return true;
11452
11453 // FIXME: We may still want to build some representation of this
11454 // explicit specialization.
11455 if (HasNoEffect)
11456 return (Decl*) nullptr;
11457 }
11458
11459 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11460 // functions
11461 // valarray<size_t>::valarray(size_t) and
11462 // valarray<size_t>::~valarray()
11463 // that it declared to have internal linkage with the internal_linkage
11464 // attribute. Ignore the explicit instantiation declaration in this case.
11465 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11467 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11468 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11469 RD->isInStdNamespace())
11470 return (Decl*) nullptr;
11471 }
11472
11475
11476 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11477 // instantiation declarations.
11479 Specialization->hasAttr<DLLImportAttr>() &&
11482
11483 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
11484
11485 if (Specialization->isDefined()) {
11486 // Let the ASTConsumer know that this function has been explicitly
11487 // instantiated now, and its linkage might have changed.
11489 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11491
11492 // C++0x [temp.explicit]p2:
11493 // If the explicit instantiation is for a member function, a member class
11494 // or a static data member of a class template specialization, the name of
11495 // the class template specialization in the qualified-id for the member
11496 // name shall be a simple-template-id.
11497 //
11498 // C++98 has the same restriction, just worded differently.
11499 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11500 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11501 D.getCXXScopeSpec().isSet() &&
11504 diag::ext_explicit_instantiation_without_qualified_id)
11506
11508 *this,
11509 FunTmpl ? (NamedDecl *)FunTmpl
11510 : Specialization->getInstantiatedFromMemberFunction(),
11511 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11512
11513 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11514 return (Decl*) nullptr;
11515}
11516
11518 const CXXScopeSpec &SS,
11519 const IdentifierInfo *Name,
11520 SourceLocation TagLoc,
11521 SourceLocation NameLoc) {
11522 // This has to hold, because SS is expected to be defined.
11523 assert(Name && "Expected a name in a dependent tag");
11524
11525 NestedNameSpecifier *NNS = SS.getScopeRep();
11526 if (!NNS)
11527 return true;
11528
11530
11531 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
11532 Diag(NameLoc, diag::err_dependent_tag_decl)
11533 << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
11534 << SS.getRange();
11535 return true;
11536 }
11537
11538 // Create the resulting type.
11540 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
11541
11542 // Create type-source location information for this type.
11543 TypeLocBuilder TLB;
11545 TL.setElaboratedKeywordLoc(TagLoc);
11547 TL.setNameLoc(NameLoc);
11549}
11550
11552 const CXXScopeSpec &SS,
11553 const IdentifierInfo &II,
11554 SourceLocation IdLoc,
11555 ImplicitTypenameContext IsImplicitTypename) {
11556 if (SS.isInvalid())
11557 return true;
11558
11559 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11560 Diag(TypenameLoc,
11562 diag::warn_cxx98_compat_typename_outside_of_template :
11563 diag::ext_typename_outside_of_template)
11564 << FixItHint::CreateRemoval(TypenameLoc);
11565
11567 TypeSourceInfo *TSI = nullptr;
11568 QualType T =
11569 CheckTypenameType((TypenameLoc.isValid() ||
11570 IsImplicitTypename == ImplicitTypenameContext::Yes)
11573 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
11574 /*DeducedTSTContext=*/true);
11575 if (T.isNull())
11576 return true;
11577 return CreateParsedType(T, TSI);
11578}
11579
11582 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11583 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11584 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11585 ASTTemplateArgsPtr TemplateArgsIn,
11586 SourceLocation RAngleLoc) {
11587 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11588 Diag(TypenameLoc,
11590 diag::warn_cxx98_compat_typename_outside_of_template :
11591 diag::ext_typename_outside_of_template)
11592 << FixItHint::CreateRemoval(TypenameLoc);
11593
11594 // Strangely, non-type results are not ignored by this lookup, so the
11595 // program is ill-formed if it finds an injected-class-name.
11596 if (TypenameLoc.isValid()) {
11597 auto *LookupRD =
11598 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
11599 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11600 Diag(TemplateIILoc,
11601 diag::ext_out_of_line_qualified_id_type_names_constructor)
11602 << TemplateII << 0 /*injected-class-name used as template name*/
11603 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11604 }
11605 }
11606
11607 // Translate the parser's template argument list in our AST format.
11608 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11609 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11610
11611 TemplateName Template = TemplateIn.get();
11612 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11613 // Construct a dependent template specialization type.
11614 assert(DTN && "dependent template has non-dependent name?");
11615 assert(DTN->getQualifier() == SS.getScopeRep());
11617 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
11618 DTN->getIdentifier(), TemplateArgs.arguments());
11619
11620 // Create source-location information for this type.
11621 TypeLocBuilder Builder;
11624 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11626 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11627 SpecTL.setTemplateNameLoc(TemplateIILoc);
11628 SpecTL.setLAngleLoc(LAngleLoc);
11629 SpecTL.setRAngleLoc(RAngleLoc);
11630 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11631 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11632 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
11633 }
11634
11635 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
11636 if (T.isNull())
11637 return true;
11638
11639 // Provide source-location information for the template specialization type.
11640 TypeLocBuilder Builder;
11642 = Builder.push<TemplateSpecializationTypeLoc>(T);
11643 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11644 SpecTL.setTemplateNameLoc(TemplateIILoc);
11645 SpecTL.setLAngleLoc(LAngleLoc);
11646 SpecTL.setRAngleLoc(RAngleLoc);
11647 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11648 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
11649
11651 SS.getScopeRep(), T);
11652 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11653 TL.setElaboratedKeywordLoc(TypenameLoc);
11655
11656 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11657 return CreateParsedType(T, TSI);
11658}
11659
11660/// Determine whether this failed name lookup should be treated as being
11661/// disabled by a usage of std::enable_if.
11663 SourceRange &CondRange, Expr *&Cond) {
11664 // We must be looking for a ::type...
11665 if (!II.isStr("type"))
11666 return false;
11667
11668 // ... within an explicitly-written template specialization...
11669 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11670 return false;
11671 TypeLoc EnableIfTy = NNS.getTypeLoc();
11672 TemplateSpecializationTypeLoc EnableIfTSTLoc =
11674 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11675 return false;
11676 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11677
11678 // ... which names a complete class template declaration...
11679 const TemplateDecl *EnableIfDecl =
11680 EnableIfTST->getTemplateName().getAsTemplateDecl();
11681 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11682 return false;
11683
11684 // ... called "enable_if".
11685 const IdentifierInfo *EnableIfII =
11686 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11687 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
11688 return false;
11689
11690 // Assume the first template argument is the condition.
11691 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
11692
11693 // Dig out the condition.
11694 Cond = nullptr;
11695 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
11697 return true;
11698
11699 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
11700
11701 // Ignore Boolean literals; they add no value.
11702 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
11703 Cond = nullptr;
11704
11705 return true;
11706}
11707
11710 SourceLocation KeywordLoc,
11711 NestedNameSpecifierLoc QualifierLoc,
11712 const IdentifierInfo &II,
11713 SourceLocation IILoc,
11714 TypeSourceInfo **TSI,
11715 bool DeducedTSTContext) {
11716 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11717 DeducedTSTContext);
11718 if (T.isNull())
11719 return QualType();
11720
11722 if (isa<DependentNameType>(T)) {
11724 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11725 TL.setElaboratedKeywordLoc(KeywordLoc);
11726 TL.setQualifierLoc(QualifierLoc);
11727 TL.setNameLoc(IILoc);
11728 } else {
11729 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11730 TL.setElaboratedKeywordLoc(KeywordLoc);
11731 TL.setQualifierLoc(QualifierLoc);
11732 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11733 }
11734 return T;
11735}
11736
11737/// Build the type that describes a C++ typename specifier,
11738/// e.g., "typename T::type".
11741 SourceLocation KeywordLoc,
11742 NestedNameSpecifierLoc QualifierLoc,
11743 const IdentifierInfo &II,
11744 SourceLocation IILoc, bool DeducedTSTContext) {
11745 CXXScopeSpec SS;
11746 SS.Adopt(QualifierLoc);
11747
11748 DeclContext *Ctx = nullptr;
11749 if (QualifierLoc) {
11750 Ctx = computeDeclContext(SS);
11751 if (!Ctx) {
11752 // If the nested-name-specifier is dependent and couldn't be
11753 // resolved to a type, build a typename type.
11754 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11755 return Context.getDependentNameType(Keyword,
11756 QualifierLoc.getNestedNameSpecifier(),
11757 &II);
11758 }
11759
11760 // If the nested-name-specifier refers to the current instantiation,
11761 // the "typename" keyword itself is superfluous. In C++03, the
11762 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11763 // allows such extraneous "typename" keywords, and we retroactively
11764 // apply this DR to C++03 code with only a warning. In any case we continue.
11765
11766 if (RequireCompleteDeclContext(SS, Ctx))
11767 return QualType();
11768 }
11769
11770 DeclarationName Name(&II);
11771 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11772 if (Ctx)
11773 LookupQualifiedName(Result, Ctx, SS);
11774 else
11775 LookupName(Result, CurScope);
11776 unsigned DiagID = 0;
11777 Decl *Referenced = nullptr;
11778 switch (Result.getResultKind()) {
11780 // If we're looking up 'type' within a template named 'enable_if', produce
11781 // a more specific diagnostic.
11782 SourceRange CondRange;
11783 Expr *Cond = nullptr;
11784 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11785 // If we have a condition, narrow it down to the specific failed
11786 // condition.
11787 if (Cond) {
11788 Expr *FailedCond;
11789 std::string FailedDescription;
11790 std::tie(FailedCond, FailedDescription) =
11792
11793 Diag(FailedCond->getExprLoc(),
11794 diag::err_typename_nested_not_found_requirement)
11795 << FailedDescription
11796 << FailedCond->getSourceRange();
11797 return QualType();
11798 }
11799
11800 Diag(CondRange.getBegin(),
11801 diag::err_typename_nested_not_found_enable_if)
11802 << Ctx << CondRange;
11803 return QualType();
11804 }
11805
11806 DiagID = Ctx ? diag::err_typename_nested_not_found
11807 : diag::err_unknown_typename;
11808 break;
11809 }
11810
11812 // We found a using declaration that is a value. Most likely, the using
11813 // declaration itself is meant to have the 'typename' keyword.
11814 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11815 IILoc);
11816 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11817 << Name << Ctx << FullRange;
11818 if (UnresolvedUsingValueDecl *Using
11819 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11820 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11821 Diag(Loc, diag::note_using_value_decl_missing_typename)
11822 << FixItHint::CreateInsertion(Loc, "typename ");
11823 }
11824 }
11825 // Fall through to create a dependent typename type, from which we can recover
11826 // better.
11827 [[fallthrough]];
11828
11830 // Okay, it's a member of an unknown instantiation.
11831 return Context.getDependentNameType(Keyword,
11832 QualifierLoc.getNestedNameSpecifier(),
11833 &II);
11834
11836 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11837 // C++ [class.qual]p2:
11838 // In a lookup in which function names are not ignored and the
11839 // nested-name-specifier nominates a class C, if the name specified
11840 // after the nested-name-specifier, when looked up in C, is the
11841 // injected-class-name of C [...] then the name is instead considered
11842 // to name the constructor of class C.
11843 //
11844 // Unlike in an elaborated-type-specifier, function names are not ignored
11845 // in typename-specifier lookup. However, they are ignored in all the
11846 // contexts where we form a typename type with no keyword (that is, in
11847 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11848 //
11849 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11850 // ignore functions, but that appears to be an oversight.
11851 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11852 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11853 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11854 FoundRD->isInjectedClassName() &&
11855 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11856 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11857 << &II << 1 << 0 /*'typename' keyword used*/;
11858
11859 // We found a type. Build an ElaboratedType, since the
11860 // typename-specifier was just sugar.
11861 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11862 return Context.getElaboratedType(Keyword,
11863 QualifierLoc.getNestedNameSpecifier(),
11865 }
11866
11867 // C++ [dcl.type.simple]p2:
11868 // A type-specifier of the form
11869 // typename[opt] nested-name-specifier[opt] template-name
11870 // is a placeholder for a deduced class type [...].
11871 if (getLangOpts().CPlusPlus17) {
11872 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11873 if (!DeducedTSTContext) {
11874 QualType T(QualifierLoc
11875 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11876 : nullptr, 0);
11877 if (!T.isNull())
11878 Diag(IILoc, diag::err_dependent_deduced_tst)
11880 else
11881 Diag(IILoc, diag::err_deduced_tst)
11884 return QualType();
11885 }
11887 Keyword, QualifierLoc.getNestedNameSpecifier(),
11889 QualType(), false));
11890 }
11891 }
11892
11893 DiagID = Ctx ? diag::err_typename_nested_not_type
11894 : diag::err_typename_not_type;
11895 Referenced = Result.getFoundDecl();
11896 break;
11897
11899 DiagID = Ctx ? diag::err_typename_nested_not_type
11900 : diag::err_typename_not_type;
11901 Referenced = *Result.begin();
11902 break;
11903
11905 return QualType();
11906 }
11907
11908 // If we get here, it's because name lookup did not find a
11909 // type. Emit an appropriate diagnostic and return an error.
11910 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11911 IILoc);
11912 if (Ctx)
11913 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11914 else
11915 Diag(IILoc, DiagID) << FullRange << Name;
11916 if (Referenced)
11917 Diag(Referenced->getLocation(),
11918 Ctx ? diag::note_typename_member_refers_here
11919 : diag::note_typename_refers_here)
11920 << Name;
11921 return QualType();
11922}
11923
11924namespace {
11925 // See Sema::RebuildTypeInCurrentInstantiation
11926 class CurrentInstantiationRebuilder
11927 : public TreeTransform<CurrentInstantiationRebuilder> {
11928 SourceLocation Loc;
11929 DeclarationName Entity;
11930
11931 public:
11933
11934 CurrentInstantiationRebuilder(Sema &SemaRef,
11935 SourceLocation Loc,
11936 DeclarationName Entity)
11937 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11938 Loc(Loc), Entity(Entity) { }
11939
11940 /// Determine whether the given type \p T has already been
11941 /// transformed.
11942 ///
11943 /// For the purposes of type reconstruction, a type has already been
11944 /// transformed if it is NULL or if it is not dependent.
11945 bool AlreadyTransformed(QualType T) {
11946 return T.isNull() || !T->isInstantiationDependentType();
11947 }
11948
11949 /// Returns the location of the entity whose type is being
11950 /// rebuilt.
11951 SourceLocation getBaseLocation() { return Loc; }
11952
11953 /// Returns the name of the entity whose type is being rebuilt.
11954 DeclarationName getBaseEntity() { return Entity; }
11955
11956 /// Sets the "base" location and entity when that
11957 /// information is known based on another transformation.
11958 void setBase(SourceLocation Loc, DeclarationName Entity) {
11959 this->Loc = Loc;
11960 this->Entity = Entity;
11961 }
11962
11963 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11964 // Lambdas never need to be transformed.
11965 return E;
11966 }
11967 };
11968} // end anonymous namespace
11969
11970/// Rebuilds a type within the context of the current instantiation.
11971///
11972/// The type \p T is part of the type of an out-of-line member definition of
11973/// a class template (or class template partial specialization) that was parsed
11974/// and constructed before we entered the scope of the class template (or
11975/// partial specialization thereof). This routine will rebuild that type now
11976/// that we have entered the declarator's scope, which may produce different
11977/// canonical types, e.g.,
11978///
11979/// \code
11980/// template<typename T>
11981/// struct X {
11982/// typedef T* pointer;
11983/// pointer data();
11984/// };
11985///
11986/// template<typename T>
11987/// typename X<T>::pointer X<T>::data() { ... }
11988/// \endcode
11989///
11990/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11991/// since we do not know that we can look into X<T> when we parsed the type.
11992/// This function will rebuild the type, performing the lookup of "pointer"
11993/// in X<T> and returning an ElaboratedType whose canonical type is the same
11994/// as the canonical type of T*, allowing the return types of the out-of-line
11995/// definition and the declaration to match.
11997 SourceLocation Loc,
11998 DeclarationName Name) {
11999 if (!T || !T->getType()->isInstantiationDependentType())
12000 return T;
12001
12002 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
12003 return Rebuilder.TransformType(T);
12004}
12005
12007 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
12008 DeclarationName());
12009 return Rebuilder.TransformExpr(E);
12010}
12011
12013 if (SS.isInvalid())
12014 return true;
12015
12017 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
12018 DeclarationName());
12020 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
12021 if (!Rebuilt)
12022 return true;
12023
12024 SS.Adopt(Rebuilt);
12025 return false;
12026}
12027
12028/// Rebuild the template parameters now that we know we're in a current
12029/// instantiation.
12031 TemplateParameterList *Params) {
12032 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12033 Decl *Param = Params->getParam(I);
12034
12035 // There is nothing to rebuild in a type parameter.
12036 if (isa<TemplateTypeParmDecl>(Param))
12037 continue;
12038
12039 // Rebuild the template parameter list of a template template parameter.
12041 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
12043 TTP->getTemplateParameters()))
12044 return true;
12045
12046 continue;
12047 }
12048
12049 // Rebuild the type of a non-type template parameter.
12050 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
12051 TypeSourceInfo *NewTSI
12053 NTTP->getLocation(),
12054 NTTP->getDeclName());
12055 if (!NewTSI)
12056 return true;
12057
12058 if (NewTSI->getType()->isUndeducedType()) {
12059 // C++17 [temp.dep.expr]p3:
12060 // An id-expression is type-dependent if it contains
12061 // - an identifier associated by name lookup with a non-type
12062 // template-parameter declared with a type that contains a
12063 // placeholder type (7.1.7.4),
12064 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
12065 }
12066
12067 if (NewTSI != NTTP->getTypeSourceInfo()) {
12068 NTTP->setTypeSourceInfo(NewTSI);
12069 NTTP->setType(NewTSI->getType());
12070 }
12071 }
12072
12073 return false;
12074}
12075
12076/// Produces a formatted string that describes the binding of
12077/// template parameters to template arguments.
12078std::string
12080 const TemplateArgumentList &Args) {
12081 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
12082}
12083
12084std::string
12086 const TemplateArgument *Args,
12087 unsigned NumArgs) {
12088 SmallString<128> Str;
12089 llvm::raw_svector_ostream Out(Str);
12090
12091 if (!Params || Params->size() == 0 || NumArgs == 0)
12092 return std::string();
12093
12094 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12095 if (I >= NumArgs)
12096 break;
12097
12098 if (I == 0)
12099 Out << "[with ";
12100 else
12101 Out << ", ";
12102
12103 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
12104 Out << Id->getName();
12105 } else {
12106 Out << '$' << I;
12107 }
12108
12109 Out << " = ";
12110 Args[I].print(getPrintingPolicy(), Out,
12112 getPrintingPolicy(), Params, I));
12113 }
12114
12115 Out << ']';
12116 return std::string(Out.str());
12117}
12118
12120 CachedTokens &Toks) {
12121 if (!FD)
12122 return;
12123
12124 auto LPT = std::make_unique<LateParsedTemplate>();
12125
12126 // Take tokens to avoid allocations
12127 LPT->Toks.swap(Toks);
12128 LPT->D = FnD;
12129 LPT->FPO = getCurFPFeatures();
12130 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
12131
12132 FD->setLateTemplateParsed(true);
12133}
12134
12136 if (!FD)
12137 return;
12138 FD->setLateTemplateParsed(false);
12139}
12140
12142 DeclContext *DC = CurContext;
12143
12144 while (DC) {
12145 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
12146 const FunctionDecl *FD = RD->isLocalClass();
12147 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
12148 } else if (DC->isTranslationUnit() || DC->isNamespace())
12149 return false;
12150
12151 DC = DC->getParent();
12152 }
12153 return false;
12154}
12155
12156namespace {
12157/// Walk the path from which a declaration was instantiated, and check
12158/// that every explicit specialization along that path is visible. This enforces
12159/// C++ [temp.expl.spec]/6:
12160///
12161/// If a template, a member template or a member of a class template is
12162/// explicitly specialized then that specialization shall be declared before
12163/// the first use of that specialization that would cause an implicit
12164/// instantiation to take place, in every translation unit in which such a
12165/// use occurs; no diagnostic is required.
12166///
12167/// and also C++ [temp.class.spec]/1:
12168///
12169/// A partial specialization shall be declared before the first use of a
12170/// class template specialization that would make use of the partial
12171/// specialization as the result of an implicit or explicit instantiation
12172/// in every translation unit in which such a use occurs; no diagnostic is
12173/// required.
12174class ExplicitSpecializationVisibilityChecker {
12175 Sema &S;
12176 SourceLocation Loc;
12179
12180public:
12181 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
12183 : S(S), Loc(Loc), Kind(Kind) {}
12184
12185 void check(NamedDecl *ND) {
12186 if (auto *FD = dyn_cast<FunctionDecl>(ND))
12187 return checkImpl(FD);
12188 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
12189 return checkImpl(RD);
12190 if (auto *VD = dyn_cast<VarDecl>(ND))
12191 return checkImpl(VD);
12192 if (auto *ED = dyn_cast<EnumDecl>(ND))
12193 return checkImpl(ED);
12194 }
12195
12196private:
12197 void diagnose(NamedDecl *D, bool IsPartialSpec) {
12198 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
12199 : Sema::MissingImportKind::ExplicitSpecialization;
12200 const bool Recover = true;
12201
12202 // If we got a custom set of modules (because only a subset of the
12203 // declarations are interesting), use them, otherwise let
12204 // diagnoseMissingImport intelligently pick some.
12205 if (Modules.empty())
12206 S.diagnoseMissingImport(Loc, D, Kind, Recover);
12207 else
12208 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
12209 }
12210
12211 bool CheckMemberSpecialization(const NamedDecl *D) {
12212 return Kind == Sema::AcceptableKind::Visible
12215 }
12216
12217 bool CheckExplicitSpecialization(const NamedDecl *D) {
12218 return Kind == Sema::AcceptableKind::Visible
12221 }
12222
12223 bool CheckDeclaration(const NamedDecl *D) {
12224 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
12226 }
12227
12228 // Check a specific declaration. There are three problematic cases:
12229 //
12230 // 1) The declaration is an explicit specialization of a template
12231 // specialization.
12232 // 2) The declaration is an explicit specialization of a member of an
12233 // templated class.
12234 // 3) The declaration is an instantiation of a template, and that template
12235 // is an explicit specialization of a member of a templated class.
12236 //
12237 // We don't need to go any deeper than that, as the instantiation of the
12238 // surrounding class / etc is not triggered by whatever triggered this
12239 // instantiation, and thus should be checked elsewhere.
12240 template<typename SpecDecl>
12241 void checkImpl(SpecDecl *Spec) {
12242 bool IsHiddenExplicitSpecialization = false;
12243 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
12244 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
12245 ? !CheckMemberSpecialization(Spec)
12246 : !CheckExplicitSpecialization(Spec);
12247 } else {
12248 checkInstantiated(Spec);
12249 }
12250
12251 if (IsHiddenExplicitSpecialization)
12252 diagnose(Spec->getMostRecentDecl(), false);
12253 }
12254
12255 void checkInstantiated(FunctionDecl *FD) {
12256 if (auto *TD = FD->getPrimaryTemplate())
12257 checkTemplate(TD);
12258 }
12259
12260 void checkInstantiated(CXXRecordDecl *RD) {
12261 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
12262 if (!SD)
12263 return;
12264
12265 auto From = SD->getSpecializedTemplateOrPartial();
12266 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
12267 checkTemplate(TD);
12268 else if (auto *TD =
12269 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
12270 if (!CheckDeclaration(TD))
12271 diagnose(TD, true);
12272 checkTemplate(TD);
12273 }
12274 }
12275
12276 void checkInstantiated(VarDecl *RD) {
12277 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
12278 if (!SD)
12279 return;
12280
12281 auto From = SD->getSpecializedTemplateOrPartial();
12282 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
12283 checkTemplate(TD);
12284 else if (auto *TD =
12285 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
12286 if (!CheckDeclaration(TD))
12287 diagnose(TD, true);
12288 checkTemplate(TD);
12289 }
12290 }
12291
12292 void checkInstantiated(EnumDecl *FD) {}
12293
12294 template<typename TemplDecl>
12295 void checkTemplate(TemplDecl *TD) {
12296 if (TD->isMemberSpecialization()) {
12297 if (!CheckMemberSpecialization(TD))
12298 diagnose(TD->getMostRecentDecl(), false);
12299 }
12300 }
12301};
12302} // end anonymous namespace
12303
12305 if (!getLangOpts().Modules)
12306 return;
12307
12308 ExplicitSpecializationVisibilityChecker(*this, Loc,
12310 .check(Spec);
12311}
12312
12314 NamedDecl *Spec) {
12315 if (!getLangOpts().CPlusPlusModules)
12316 return checkSpecializationVisibility(Loc, Spec);
12317
12318 ExplicitSpecializationVisibilityChecker(*this, Loc,
12320 .check(Spec);
12321}
12322
12323/// Returns the top most location responsible for the definition of \p N.
12324/// If \p N is a a template specialization, this is the location
12325/// of the top of the instantiation stack.
12326/// Otherwise, the location of \p N is returned.
12329 return N->getLocation();
12330 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
12332 return FD->getLocation();
12335 return N->getLocation();
12336 }
12337 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12338 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12339 continue;
12340 return CSC.PointOfInstantiation;
12341 }
12342 return N->getLocation();
12343}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
Defines enum values for all the target-independent builtin functions.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1109
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.
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6975
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 NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type.
static ExprResult formImmediatelyDeclaredConstraint(Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc, SourceLocation RAngleLoc, QualType ConstrainedType, SourceLocation ParamNameLoc, ArgumentLocAppender Appender, SourceLocation EllipsisLoc)
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 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 TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *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 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 bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *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 SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
static TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
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 bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted)
Substitute template arguments into the default template argument for the given template type paramete...
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 QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, ArrayRef< TemplateArgument > Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
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 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.
Defines utilities for dealing with stack allocation and stack space.
static const TemplateArgument & getArgument(const TemplateArgument &A)
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:974
APSInt & getInt()
Definition: APValue.h:423
APSInt & getComplexIntImag()
Definition: APValue.h:461
ValueKind getKind() const
Definition: APValue.h:395
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isMemberPointer() const
Definition: APValue.h:411
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
@ 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:1010
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
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:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1118
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1590
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl)
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
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.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1119
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2340
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
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:1568
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1039
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3684
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:42
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2189
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2207
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2257
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2231
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2250
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2225
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2237
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5977
A fixed int type of a specified bitwidth.
Definition: Type.h:7238
Pointer to a block type.
Definition: Type.h:3345
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: Type.h:2977
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:2105
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2606
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal)
Definition: DeclCXX.cpp:2157
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3652
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:1484
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isConst() const
Definition: DeclCXX.h:2112
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1876
base_class_range bases()
Definition: DeclCXX.h:619
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1901
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1883
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1916
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:531
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:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
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
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
void setMemberSpecialization()
Note that this member template is a specialization.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
Represents a class template specialization, which refers to a class template with a given set of temp...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
Complex values, per C99 6.2.5p11.
Definition: Type.h:3082
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr)
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:93
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3552
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4163
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
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:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1975
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1298
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
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:1957
bool isNamespace() const
Definition: DeclBase.h:2151
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1938
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1215
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1315
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1319
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
ValueDecl * getDecl()
Definition: Expr.h:1328
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool isVirtualSpecified() const
Definition: DeclSpec.h:644
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
bool isNoreturnSpecified() const
Definition: DeclSpec.h:657
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:570
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:658
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:650
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:869
bool isInlineSpecified() const
Definition: DeclSpec.h:633
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:645
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:832
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:647
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:833
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:1051
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1207
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:833
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:803
void dropAttrs()
Definition: DeclBase.cpp:968
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1016
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:1170
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2739
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:210
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
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:908
bool hasAttr() const
Definition: DeclBase.h:583
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
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...
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2334
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2724
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2064
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2060
bool hasEllipsis() const
Definition: DeclSpec.h:2723
bool isInvalidType() const
Definition: DeclSpec.h:2712
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2052
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
Represents the type decltype(expr) (C++11).
Definition: Type.h:5354
Represents a C++17 deduced template specialization type.
Definition: Type.h:6025
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
bool isDeduced() const
Definition: Type.h:5965
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3855
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6448
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3292
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3797
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3895
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4222
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:488
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:547
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:544
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6500
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4017
bool isEmpty() const
Definition: TypeLoc.h:2365
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6367
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3868
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4127
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4940
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
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:3039
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:3918
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4057
Represents a member of a struct/union/class.
Definition: Decl.h:3058
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
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, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1971
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2439
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4362
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3617
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2433
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:4228
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2332
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4268
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3126
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4607
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3760
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
ArrayRef< QualType > param_types() const
Definition: Type.h:5040
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:467
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
unsigned getNumParams() const
Definition: TypeLoc.h:1500
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1448
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1464
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1507
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1491
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1472
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1456
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1486
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1460
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1468
QualType getReturnType() const
Definition: Type.h:4569
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.
StringRef getName() const
Return the actual identifier 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:3655
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3699
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:4847
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:8591
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6217
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:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3420
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
Represents a linkage specification.
Definition: DeclCXX.h:2934
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.
void InstantiatedLocal(const Decl *D, Decl *Inst)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
bool hasNext() const
Definition: Lookup.h:704
NamedDecl * next()
Definition: Lookup.h:708
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
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:603
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:318
DeclClass * getAsSingle() const
Definition: Lookup.h:556
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
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:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
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
bool isSuppressingAmbiguousDiagnostics() const
Determines whether this lookup is suppressing ambiguous lookup diagnostics.
Definition: Lookup.h:646
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:573
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
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:4289
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
QualType getPointeeType() const
Definition: Type.h:3472
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:656
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:244
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 addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:257
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 setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getMostRecentDecl()
Definition: Decl.h:476
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:686
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1927
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
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.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
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.
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
void setDefaultArgument(Expr *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.
void setPlaceholderTypeConstraint(Expr *E)
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6948
Represents a pointer to an Objective C object.
Definition: Type.h:7004
Represents a class type in Objective C.
Definition: Type.h:6750
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(TemplateName P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1168
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4149
Represents a pack expansion of types.
Definition: Type.h:6565
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
Expr * getDefaultArg()
Definition: Decl.cpp:2968
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1811
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:126
Represents the parsed form of a C++ template argument.
KindType getKind() const
Determine what kind of template argument we have.
SourceLocation getLocation() const
Retrieve the location of the template argument.
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.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument.
PipeType - OpenCL20.
Definition: Type.h:7204
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:940
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7444
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
void * getAsOpaquePtr() const
Definition: Type.h:987
bool isCanonical() const
Definition: Type.h:7412
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7401
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
The collection of all-type qualifiers we support.
Definition: Type.h:318
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
void addConst()
Definition: Type.h:446
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3438
Represents a struct/union/class.
Definition: Decl.h:4169
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4360
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:861
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:866
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4995
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
QualType getPointeeType() const
Definition: Type.h:3394
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:259
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
@ 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:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1053
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10305
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6552
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
Whether and why a template name is required in this lookup.
Definition: Sema.h:8854
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:8862
bool hasTemplateKeyword() const
Definition: Sema.h:8865
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5776
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9415
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6794
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10239
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9787
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:1583
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15753
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7372
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7379
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19890
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:40
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc)
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:6232
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...
TypeResult ActOnTemplateIdType(Scope *S, 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)
Decl * ActOnConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr)
NamedDecl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e....
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:7552
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6199
void NoteAllFoundTemplates(TemplateName Name)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, const IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
SemaCUDA & CUDA()
Definition: Sema.h:998
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.
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, 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...
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 ...
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
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:6360
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17458
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:53
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 ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
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.
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:8825
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:9173
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:9176
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:9180
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation=false)
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType)
Convert a parsed type into a parsed template argument.
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
ASTContext & Context
Definition: Sema.h:858
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...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:3084
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5898
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
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:527
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
Definition: SemaDecl.cpp:1754
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:645
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 RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9662
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:775
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:17127
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2206
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:8815
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:9259
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:9277
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:9288
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:9267
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:9298
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:8875
@ 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 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:8808
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
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:10839
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:10827
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:10836
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:10830
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:10854
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition: Sema.h:857
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
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.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, 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:11246
const LangOptions & LangOpts
Definition: Sema.h:856
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 ...
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:7062
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:20311
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:7364
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.
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9761
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8350
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:17098
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1231
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:10732
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef< const Expr * > AC1, NamedDecl *D2, ArrayRef< const Expr * > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
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:996
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15070
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5904
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6287
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1309
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4804
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,...
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9398
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3161
@ NTK_TypeAliasTemplate
Definition: Sema.h:3169
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg)
Check a template argument against its corresponding template template parameter.
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,...
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
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.
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
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...
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true, bool AllowDependent=true)
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef< const Expr * > AC1, NamedDecl *D2, MutableArrayRef< const Expr * > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
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:89
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:227
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:11707
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
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...
@ CTK_ErrorRecovery
Definition: Sema.h:7605
RedeclarationKind forRedeclarationInCurContext() const
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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.
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:8029
void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3194
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:1946
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
ASTConsumer & Consumer
Definition: Sema.h:859
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)
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
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:9876
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:6122
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:17321
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
@ TemplateNameIsRequired
Definition: Sema.h:8852
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.
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:527
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
@ TUK_Definition
Definition: Sema.h:3184
@ TUK_Declaration
Definition: Sema.h:3183
@ TUK_Friend
Definition: Sema.h:3185
@ TUK_Reference
Definition: Sema.h:3182
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:15107
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:9003
@ TPC_ClassTemplate
Definition: Sema.h:9004
@ TPC_FriendFunctionTemplate
Definition: Sema.h:9009
@ TPC_ClassTemplateMember
Definition: Sema.h:9007
@ TPC_FunctionTemplate
Definition: Sema.h:9006
@ TPC_FriendClassTemplate
Definition: Sema.h:9008
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:9010
@ TPC_TypeAliasTemplate
Definition: Sema.h:9011
@ TPC_VarTemplate
Definition: Sema.h:9005
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:1605
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:1588
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2343
@ OOK_Outside
Definition: Sema.h:3190
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:520
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:4628
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)
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)
Definition: SemaDecl.cpp:1728
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output)
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3222
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:2537
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:8817
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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.
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:7561
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:9722
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6153
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:218
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6733
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
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
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:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4442
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5885
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:5815
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
bool isEnum() const
Definition: Decl.h:3792
StringRef getKindName() const
Definition: Decl.h:3776
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4739
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4822
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
TagKind getTagKind() const
Definition: Decl.h:3780
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:3997
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:1235
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1273
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:283
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:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getLocation() const
Definition: TemplateBase.h:563
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:623
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
Expr * getSourceExpression() const
Definition: TemplateBase.h:584
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:418
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:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
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:343
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:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
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:377
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ 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:295
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:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
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:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &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:199
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 setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6085
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6153
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6151
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4186
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.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
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...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
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.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
unsigned getIndex() const
Retrieve the index of the template parameter.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
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, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
void removeDefaultArgument()
Removes the default argument of this template parameter.
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
unsigned getNumExpansionParameters() const
Retrieves the number of parameters in an expanded parameter pack.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5778
unsigned getIndex() const
Definition: Type.h:5775
unsigned getDepth() const
Definition: Type.h:5774
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:3556
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5556
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
Represents a declaration of a type.
Definition: Decl.h:3391
const Type * getTypeForDecl() const
Definition: Decl.h:3415
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3418
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:153
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:739
bool isNull() const
Definition: TypeLoc.h:121
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5270
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5318
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7337
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
An operation on a type.
Definition: TypeVisitor.h:64
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3139
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3121
The base class of the type hierarchy.
Definition: Type.h:1813
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2396
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBooleanType() const
Definition: Type.h:8029
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2155
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2205
bool isRValueReferenceType() const
Definition: Type.h:7628
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isArrayType() const
Definition: Type.h:7674
bool isPointerType() const
Definition: Type.h:7608
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isEnumeralType() const
Definition: Type.h:7706
bool isScalarType() const
Definition: Type.h:8000
bool isChar8Type() const
Definition: Type.cpp:2093
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
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:426
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8016
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2113
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7748
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2754
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isBitIntType() const
Definition: Type.h:7836
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:2945
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isChar16Type() const
Definition: Type.cpp:2099
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1999
QualType getCanonicalTypeInternal() const
Definition: Type.h:2932
bool isMemberPointerType() const
Definition: Type.h:7656
bool isChar32Type() const
Definition: Type.cpp:2105
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2667
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4504
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isVectorType() const
Definition: Type.h:7714
bool isWideCharType() const
Definition: Type.cpp:2086
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5505
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3433
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3483
QualType getUnderlyingType() const
Definition: Decl.h:3488
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
TypedefNameDecl * getTypedefNameDecl() const
Definition: TypeLoc.h:695
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:2183
A unary type transform, which is a type constructed from another.
Definition: Type.h:5462
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3173
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5140
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
TLSKind getTLSKind() const
Definition: Decl.cpp:2165
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
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:2876
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
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:2777
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:2756
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void setMemberSpecialization()
Note that this member template is a specialization.
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos)
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.
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: Type.h:3743
Represents a GCC generic vector type.
Definition: Type.h:3965
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 * takeCanonical()
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
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:1881
bool isa(CodeGen::Address addr)
Definition: Address.h:294
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ 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+.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Extern
Definition: Specifiers.h:248
@ SC_None
Definition: Specifiers.h:247
@ TSCS_unspecified
Definition: Specifiers.h:233
@ 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:54
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6295
@ Enum
The "enum" keyword.
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:262
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...
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:307
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:304
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
CastKind
CastKind - The kind of operation required for a conversion.
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
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:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
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:373
@ 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:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6270
@ 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:1584
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:120
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
#define false
Definition: stdbool.h:22
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
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.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:4731
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned TerseOutput
Provide a 'terse' output.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9804
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:9911
A stack object to be created when performing template instantiation.
Definition: Sema.h:9989
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10143
NamedDecl * Previous
Definition: Sema.h:360
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
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)
Contains all information for a given match.