clang 20.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
28#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/StringExtras.h"
41
42#include <optional>
43using namespace clang;
44using namespace sema;
45
46// Exported for use by Parser.
49 unsigned N) {
50 if (!N) return SourceRange();
51 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
52}
53
54unsigned Sema::getTemplateDepth(Scope *S) const {
55 unsigned Depth = 0;
56
57 // Each template parameter scope represents one level of template parameter
58 // depth.
59 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
60 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
61 ++Depth;
62 }
63
64 // Note that there are template parameters with the given depth.
65 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
66
67 // Look for parameters of an enclosing generic lambda. We don't create a
68 // template parameter scope for these.
70 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
71 if (!LSI->TemplateParams.empty()) {
72 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
73 break;
74 }
75 if (LSI->GLTemplateParameterList) {
76 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
77 break;
78 }
79 }
80 }
81
82 // Look for parameters of an enclosing terse function template. We don't
83 // create a template parameter scope for these either.
84 for (const InventedTemplateParameterInfo &Info :
86 if (!Info.TemplateParams.empty()) {
87 ParamsAtDepth(Info.AutoTemplateParameterDepth);
88 break;
89 }
90 }
91
92 return Depth;
93}
94
95/// \brief Determine whether the declaration found is acceptable as the name
96/// of a template and, if so, return that template declaration. Otherwise,
97/// returns null.
98///
99/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
100/// is true. In all other cases it will return a TemplateDecl (or null).
102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
104 D = D->getUnderlyingDecl();
105
106 if (isa<TemplateDecl>(D)) {
107 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
108 return nullptr;
109
110 return D;
111 }
112
113 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
114 // C++ [temp.local]p1:
115 // Like normal (non-template) classes, class templates have an
116 // injected-class-name (Clause 9). The injected-class-name
117 // can be used with or without a template-argument-list. When
118 // it is used without a template-argument-list, it is
119 // equivalent to the injected-class-name followed by the
120 // template-parameters of the class template enclosed in
121 // <>. When it is used with a template-argument-list, it
122 // refers to the specified class template specialization,
123 // which could be the current specialization or another
124 // specialization.
125 if (Record->isInjectedClassName()) {
126 Record = cast<CXXRecordDecl>(Record->getDeclContext());
127 if (Record->getDescribedClassTemplate())
128 return Record->getDescribedClassTemplate();
129
130 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131 return Spec->getSpecializedTemplate();
132 }
133
134 return nullptr;
135 }
136
137 // 'using Dependent::foo;' can resolve to a template name.
138 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139 // injected-class-name).
140 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141 return D;
142
143 return nullptr;
144}
145
147 bool AllowFunctionTemplates,
148 bool AllowDependent) {
149 LookupResult::Filter filter = R.makeFilter();
150 while (filter.hasNext()) {
151 NamedDecl *Orig = filter.next();
152 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153 filter.erase();
154 }
155 filter.done();
156}
157
159 bool AllowFunctionTemplates,
160 bool AllowDependent,
161 bool AllowNonTemplateFunctions) {
162 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164 return true;
165 if (AllowNonTemplateFunctions &&
166 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167 return true;
168 }
169
170 return false;
171}
172
174 CXXScopeSpec &SS,
175 bool hasTemplateKeyword,
176 const UnqualifiedId &Name,
177 ParsedType ObjectTypePtr,
178 bool EnteringContext,
179 TemplateTy &TemplateResult,
180 bool &MemberOfUnknownSpecialization,
181 bool Disambiguation) {
182 assert(getLangOpts().CPlusPlus && "No template names in C!");
183
184 DeclarationName TName;
185 MemberOfUnknownSpecialization = false;
186
187 switch (Name.getKind()) {
189 TName = DeclarationName(Name.Identifier);
190 break;
191
194 Name.OperatorFunctionId.Operator);
195 break;
196
198 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199 break;
200
201 default:
202 return TNK_Non_template;
203 }
204
205 QualType ObjectType = ObjectTypePtr.get();
206
207 AssumedTemplateKind AssumedTemplate;
208 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210 /*RequiredTemplate=*/SourceLocation(),
211 &AssumedTemplate,
212 /*AllowTypoCorrection=*/!Disambiguation))
213 return TNK_Non_template;
214 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
215
216 if (AssumedTemplate != AssumedTemplateKind::None) {
217 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
218 // Let the parser know whether we found nothing or found functions; if we
219 // found nothing, we want to more carefully check whether this is actually
220 // a function template name versus some other kind of undeclared identifier.
221 return AssumedTemplate == AssumedTemplateKind::FoundNothing
224 }
225
226 if (R.empty())
227 return TNK_Non_template;
228
229 NamedDecl *D = nullptr;
230 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
231 if (R.isAmbiguous()) {
232 // If we got an ambiguity involving a non-function template, treat this
233 // as a template name, and pick an arbitrary template for error recovery.
234 bool AnyFunctionTemplates = false;
235 for (NamedDecl *FoundD : R) {
236 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
237 if (isa<FunctionTemplateDecl>(FoundTemplate))
238 AnyFunctionTemplates = true;
239 else {
240 D = FoundTemplate;
241 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
242 break;
243 }
244 }
245 }
246
247 // If we didn't find any templates at all, this isn't a template name.
248 // Leave the ambiguity for a later lookup to diagnose.
249 if (!D && !AnyFunctionTemplates) {
250 R.suppressDiagnostics();
251 return TNK_Non_template;
252 }
253
254 // If the only templates were function templates, filter out the rest.
255 // We'll diagnose the ambiguity later.
256 if (!D)
258 }
259
260 // At this point, we have either picked a single template name declaration D
261 // or we have a non-empty set of results R containing either one template name
262 // declaration or a set of function templates.
263
264 TemplateName Template;
265 TemplateNameKind TemplateKind;
266
267 unsigned ResultCount = R.end() - R.begin();
268 if (!D && ResultCount > 1) {
269 // We assume that we'll preserve the qualifier from a function
270 // template name in other ways.
271 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
272 TemplateKind = TNK_Function_template;
273
274 // We'll do this lookup again later.
276 } else {
277 if (!D) {
279 assert(D && "unambiguous result is not a template name");
280 }
281
282 if (isa<UnresolvedUsingValueDecl>(D)) {
283 // We don't yet know whether this is a template-name or not.
284 MemberOfUnknownSpecialization = true;
285 return TNK_Non_template;
286 }
287
288 TemplateDecl *TD = cast<TemplateDecl>(D);
289 Template =
290 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
291 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
292 if (!SS.isInvalid()) {
293 NestedNameSpecifier *Qualifier = SS.getScopeRep();
294 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
295 Template);
296 }
297
298 if (isa<FunctionTemplateDecl>(TD)) {
299 TemplateKind = TNK_Function_template;
300
301 // We'll do this lookup again later.
303 } else {
304 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
305 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
306 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
307 TemplateKind =
308 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
309 isa<ConceptDecl>(TD) ? TNK_Concept_template :
311 }
312 }
313
314 TemplateResult = TemplateTy::make(Template);
315 return TemplateKind;
316}
317
319 SourceLocation NameLoc, CXXScopeSpec &SS,
320 ParsedTemplateTy *Template /*=nullptr*/) {
321 // We could use redeclaration lookup here, but we don't need to: the
322 // syntactic form of a deduction guide is enough to identify it even
323 // if we can't look up the template name at all.
324 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
325 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
326 /*EnteringContext*/ false))
327 return false;
328
329 if (R.empty()) return false;
330 if (R.isAmbiguous()) {
331 // FIXME: Diagnose an ambiguity if we find at least one template.
333 return false;
334 }
335
336 // We only treat template-names that name type templates as valid deduction
337 // guide names.
339 if (!TD || !getAsTypeTemplateDecl(TD))
340 return false;
341
342 if (Template) {
344 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
345 *Template = TemplateTy::make(Name);
346 }
347 return true;
348}
349
351 SourceLocation IILoc,
352 Scope *S,
353 const CXXScopeSpec *SS,
354 TemplateTy &SuggestedTemplate,
355 TemplateNameKind &SuggestedKind) {
356 // We can't recover unless there's a dependent scope specifier preceding the
357 // template name.
358 // FIXME: Typo correction?
359 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361 return false;
362
363 // The code is missing a 'template' keyword prior to the dependent template
364 // name.
366 Diag(IILoc, diag::err_template_kw_missing)
367 << Qualifier << II.getName()
368 << FixItHint::CreateInsertion(IILoc, "template ");
369 SuggestedTemplate
371 SuggestedKind = TNK_Dependent_template_name;
372 return true;
373}
374
376 QualType ObjectType, bool EnteringContext,
377 RequiredTemplateKind RequiredTemplate,
379 bool AllowTypoCorrection) {
380 if (ATK)
382
383 if (SS.isInvalid())
384 return true;
385
386 Found.setTemplateNameLookup(true);
387
388 // Determine where to perform name lookup
389 DeclContext *LookupCtx = nullptr;
390 bool IsDependent = false;
391 if (!ObjectType.isNull()) {
392 // This nested-name-specifier occurs in a member access expression, e.g.,
393 // x->B::f, and we are looking into the type of the object.
394 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
395 LookupCtx = computeDeclContext(ObjectType);
396 IsDependent = !LookupCtx && ObjectType->isDependentType();
397 assert((IsDependent || !ObjectType->isIncompleteType() ||
398 !ObjectType->getAs<TagType>() ||
399 ObjectType->castAs<TagType>()->isBeingDefined()) &&
400 "Caller should have completed object type");
401
402 // Template names cannot appear inside an Objective-C class or object type
403 // or a vector type.
404 //
405 // FIXME: This is wrong. For example:
406 //
407 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
408 // Vec<int> vi;
409 // vi.Vec<int>::~Vec<int>();
410 //
411 // ... should be accepted but we will not treat 'Vec' as a template name
412 // here. The right thing to do would be to check if the name is a valid
413 // vector component name, and look up a template name if not. And similarly
414 // for lookups into Objective-C class and object types, where the same
415 // problem can arise.
416 if (ObjectType->isObjCObjectOrInterfaceType() ||
417 ObjectType->isVectorType()) {
418 Found.clear();
419 return false;
420 }
421 } else if (SS.isNotEmpty()) {
422 // This nested-name-specifier occurs after another nested-name-specifier,
423 // so long into the context associated with the prior nested-name-specifier.
424 LookupCtx = computeDeclContext(SS, EnteringContext);
425 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
426
427 // The declaration context must be complete.
428 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
429 return true;
430 }
431
432 bool ObjectTypeSearchedInScope = false;
433 bool AllowFunctionTemplatesInLookup = true;
434 if (LookupCtx) {
435 // Perform "qualified" name lookup into the declaration context we
436 // computed, which is either the type of the base of a member access
437 // expression or the declaration context associated with a prior
438 // nested-name-specifier.
439 LookupQualifiedName(Found, LookupCtx);
440
441 // FIXME: The C++ standard does not clearly specify what happens in the
442 // case where the object type is dependent, and implementations vary. In
443 // Clang, we treat a name after a . or -> as a template-name if lookup
444 // finds a non-dependent member or member of the current instantiation that
445 // is a type template, or finds no such members and lookup in the context
446 // of the postfix-expression finds a type template. In the latter case, the
447 // name is nonetheless dependent, and we may resolve it to a member of an
448 // unknown specialization when we come to instantiate the template.
449 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
450 }
451
452 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
453 // C++ [basic.lookup.classref]p1:
454 // In a class member access expression (5.2.5), if the . or -> token is
455 // immediately followed by an identifier followed by a <, the
456 // identifier must be looked up to determine whether the < is the
457 // beginning of a template argument list (14.2) or a less-than operator.
458 // The identifier is first looked up in the class of the object
459 // expression. If the identifier is not found, it is then looked up in
460 // the context of the entire postfix-expression and shall name a class
461 // template.
462 if (S)
463 LookupName(Found, S);
464
465 if (!ObjectType.isNull()) {
466 // FIXME: We should filter out all non-type templates here, particularly
467 // variable templates and concepts. But the exclusion of alias templates
468 // and template template parameters is a wording defect.
469 AllowFunctionTemplatesInLookup = false;
470 ObjectTypeSearchedInScope = true;
471 }
472
473 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
474 }
475
476 if (Found.isAmbiguous())
477 return false;
478
479 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
480 !RequiredTemplate.hasTemplateKeyword()) {
481 // C++2a [temp.names]p2:
482 // A name is also considered to refer to a template if it is an
483 // unqualified-id followed by a < and name lookup finds either one or more
484 // functions or finds nothing.
485 //
486 // To keep our behavior consistent, we apply the "finds nothing" part in
487 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
488 // successfully form a call to an undeclared template-id.
489 bool AllFunctions =
490 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
491 return isa<FunctionDecl>(ND->getUnderlyingDecl());
492 });
493 if (AllFunctions || (Found.empty() && !IsDependent)) {
494 // If lookup found any functions, or if this is a name that can only be
495 // used for a function, then strongly assume this is a function
496 // template-id.
497 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
500 Found.clear();
501 return false;
502 }
503 }
504
505 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
506 // If we did not find any names, and this is not a disambiguation, attempt
507 // to correct any typos.
508 DeclarationName Name = Found.getLookupName();
509 Found.clear();
510 // Simple filter callback that, for keywords, only accepts the C++ *_cast
511 DefaultFilterCCC FilterCCC{};
512 FilterCCC.WantTypeSpecifiers = false;
513 FilterCCC.WantExpressionKeywords = false;
514 FilterCCC.WantRemainingKeywords = false;
515 FilterCCC.WantCXXNamedCasts = true;
516 if (TypoCorrection Corrected =
517 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
518 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
519 if (auto *ND = Corrected.getFoundDecl())
520 Found.addDecl(ND);
522 if (Found.isAmbiguous()) {
523 Found.clear();
524 } else if (!Found.empty()) {
525 Found.setLookupName(Corrected.getCorrection());
526 if (LookupCtx) {
527 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
529 Name.getAsString() == CorrectedStr;
530 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
531 << Name << LookupCtx << DroppedSpecifier
532 << SS.getRange());
533 } else {
534 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
535 }
536 }
537 }
538 }
539
540 NamedDecl *ExampleLookupResult =
541 Found.empty() ? nullptr : Found.getRepresentativeDecl();
542 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
543 if (Found.empty()) {
544 if (IsDependent) {
545 Found.setNotFoundInCurrentInstantiation();
546 return false;
547 }
548
549 // If a 'template' keyword was used, a lookup that finds only non-template
550 // names is an error.
551 if (ExampleLookupResult && RequiredTemplate) {
552 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
553 << Found.getLookupName() << SS.getRange()
554 << RequiredTemplate.hasTemplateKeyword()
555 << RequiredTemplate.getTemplateKeywordLoc();
556 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
557 diag::note_template_kw_refers_to_non_template)
558 << Found.getLookupName();
559 return true;
560 }
561
562 return false;
563 }
564
565 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
567 // C++03 [basic.lookup.classref]p1:
568 // [...] If the lookup in the class of the object expression finds a
569 // template, the name is also looked up in the context of the entire
570 // postfix-expression and [...]
571 //
572 // Note: C++11 does not perform this second lookup.
573 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
575 FoundOuter.setTemplateNameLookup(true);
576 LookupName(FoundOuter, S);
577 // FIXME: We silently accept an ambiguous lookup here, in violation of
578 // [basic.lookup]/1.
579 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
580
581 NamedDecl *OuterTemplate;
582 if (FoundOuter.empty()) {
583 // - if the name is not found, the name found in the class of the
584 // object expression is used, otherwise
585 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
586 !(OuterTemplate =
587 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
588 // - if the name is found in the context of the entire
589 // postfix-expression and does not name a class template, the name
590 // found in the class of the object expression is used, otherwise
591 FoundOuter.clear();
592 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
593 // - if the name found is a class template, it must refer to the same
594 // entity as the one found in the class of the object expression,
595 // otherwise the program is ill-formed.
596 if (!Found.isSingleResult() ||
597 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
598 OuterTemplate->getCanonicalDecl()) {
599 Diag(Found.getNameLoc(),
600 diag::ext_nested_name_member_ref_lookup_ambiguous)
601 << Found.getLookupName()
602 << ObjectType;
603 Diag(Found.getRepresentativeDecl()->getLocation(),
604 diag::note_ambig_member_ref_object_type)
605 << ObjectType;
606 Diag(FoundOuter.getFoundDecl()->getLocation(),
607 diag::note_ambig_member_ref_scope);
608
609 // Recover by taking the template that we found in the object
610 // expression's type.
611 }
612 }
613 }
614
615 return false;
616}
617
621 if (TemplateName.isInvalid())
622 return;
623
624 DeclarationNameInfo NameInfo;
625 CXXScopeSpec SS;
626 LookupNameKind LookupKind;
627
628 DeclContext *LookupCtx = nullptr;
629 NamedDecl *Found = nullptr;
630 bool MissingTemplateKeyword = false;
631
632 // Figure out what name we looked up.
633 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
634 NameInfo = DRE->getNameInfo();
635 SS.Adopt(DRE->getQualifierLoc());
636 LookupKind = LookupOrdinaryName;
637 Found = DRE->getFoundDecl();
638 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
639 NameInfo = ME->getMemberNameInfo();
640 SS.Adopt(ME->getQualifierLoc());
641 LookupKind = LookupMemberName;
642 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
643 Found = ME->getMemberDecl();
644 } else if (auto *DSDRE =
645 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
646 NameInfo = DSDRE->getNameInfo();
647 SS.Adopt(DSDRE->getQualifierLoc());
648 MissingTemplateKeyword = true;
649 } else if (auto *DSME =
650 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
651 NameInfo = DSME->getMemberNameInfo();
652 SS.Adopt(DSME->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else {
655 llvm_unreachable("unexpected kind of potential template name");
656 }
657
658 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
659 // was missing.
660 if (MissingTemplateKeyword) {
661 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
662 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
663 return;
664 }
665
666 // Try to correct the name by looking for templates and C++ named casts.
667 struct TemplateCandidateFilter : CorrectionCandidateCallback {
668 Sema &S;
669 TemplateCandidateFilter(Sema &S) : S(S) {
670 WantTypeSpecifiers = false;
671 WantExpressionKeywords = false;
672 WantRemainingKeywords = false;
673 WantCXXNamedCasts = true;
674 };
675 bool ValidateCandidate(const TypoCorrection &Candidate) override {
676 if (auto *ND = Candidate.getCorrectionDecl())
677 return S.getAsTemplateNameDecl(ND);
678 return Candidate.isKeyword();
679 }
680
681 std::unique_ptr<CorrectionCandidateCallback> clone() override {
682 return std::make_unique<TemplateCandidateFilter>(*this);
683 }
684 };
685
686 DeclarationName Name = NameInfo.getName();
687 TemplateCandidateFilter CCC(*this);
688 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
689 CTK_ErrorRecovery, LookupCtx)) {
690 auto *ND = Corrected.getFoundDecl();
691 if (ND)
692 ND = getAsTemplateNameDecl(ND);
693 if (ND || Corrected.isKeyword()) {
694 if (LookupCtx) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 Name.getAsString() == CorrectedStr;
698 diagnoseTypo(Corrected,
699 PDiag(diag::err_non_template_in_member_template_id_suggest)
700 << Name << LookupCtx << DroppedSpecifier
701 << SS.getRange(), false);
702 } else {
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_template_id_suggest)
705 << Name, false);
706 }
707 if (Found)
708 Diag(Found->getLocation(),
709 diag::note_non_template_in_template_id_found);
710 return;
711 }
712 }
713
714 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
715 << Name << SourceRange(Less, Greater);
716 if (Found)
717 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
718}
719
722 SourceLocation TemplateKWLoc,
723 const DeclarationNameInfo &NameInfo,
724 bool isAddressOfOperand,
725 const TemplateArgumentListInfo *TemplateArgs) {
726 if (SS.isEmpty()) {
727 // FIXME: This codepath is only used by dependent unqualified names
728 // (e.g. a dependent conversion-function-id, or operator= once we support
729 // it). It doesn't quite do the right thing, and it will silently fail if
730 // getCurrentThisType() returns null.
731 QualType ThisType = getCurrentThisType();
732 if (ThisType.isNull())
733 return ExprError();
734
736 Context, /*Base=*/nullptr, ThisType,
737 /*IsArrow=*/!Context.getLangOpts().HLSL,
738 /*OperatorLoc=*/SourceLocation(),
739 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
740 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
741 }
742 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
743}
744
747 SourceLocation TemplateKWLoc,
748 const DeclarationNameInfo &NameInfo,
749 const TemplateArgumentListInfo *TemplateArgs) {
750 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
751 if (!SS.isValid())
752 return CreateRecoveryExpr(
753 SS.getBeginLoc(),
754 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
755
757 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
758 TemplateArgs);
759}
760
762 NamedDecl *Instantiation,
763 bool InstantiatedFromMember,
764 const NamedDecl *Pattern,
765 const NamedDecl *PatternDef,
767 bool Complain /*= true*/) {
768 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
769 isa<VarDecl>(Instantiation));
770
771 bool IsEntityBeingDefined = false;
772 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
773 IsEntityBeingDefined = TD->isBeingDefined();
774
775 if (PatternDef && !IsEntityBeingDefined) {
776 NamedDecl *SuggestedDef = nullptr;
777 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
778 &SuggestedDef,
779 /*OnlyNeedComplete*/ false)) {
780 // If we're allowed to diagnose this and recover, do so.
781 bool Recover = Complain && !isSFINAEContext();
782 if (Complain)
783 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
785 return !Recover;
786 }
787 return false;
788 }
789
790 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
791 return true;
792
793 QualType InstantiationTy;
794 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
795 InstantiationTy = Context.getTypeDeclType(TD);
796 if (PatternDef) {
797 Diag(PointOfInstantiation,
798 diag::err_template_instantiate_within_definition)
799 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
800 << InstantiationTy;
801 // Not much point in noting the template declaration here, since
802 // we're lexically inside it.
803 Instantiation->setInvalidDecl();
804 } else if (InstantiatedFromMember) {
805 if (isa<FunctionDecl>(Instantiation)) {
806 Diag(PointOfInstantiation,
807 diag::err_explicit_instantiation_undefined_member)
808 << /*member function*/ 1 << Instantiation->getDeclName()
809 << Instantiation->getDeclContext();
810 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
811 } else {
812 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
813 Diag(PointOfInstantiation,
814 diag::err_implicit_instantiate_member_undefined)
815 << InstantiationTy;
816 Diag(Pattern->getLocation(), diag::note_member_declared_at);
817 }
818 } else {
819 if (isa<FunctionDecl>(Instantiation)) {
820 Diag(PointOfInstantiation,
821 diag::err_explicit_instantiation_undefined_func_template)
822 << Pattern;
823 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
824 } else if (isa<TagDecl>(Instantiation)) {
825 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
826 << (TSK != TSK_ImplicitInstantiation)
827 << InstantiationTy;
828 NoteTemplateLocation(*Pattern);
829 } else {
830 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
831 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
832 Diag(PointOfInstantiation,
833 diag::err_explicit_instantiation_undefined_var_template)
834 << Instantiation;
835 Instantiation->setInvalidDecl();
836 } else
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*static data member*/ 2 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
842 }
843 }
844
845 // In general, Instantiation isn't marked invalid to get more than one
846 // error for multiple undefined instantiations. But the code that does
847 // explicit declaration -> explicit definition conversion can't handle
848 // invalid declarations, so mark as invalid in that case.
850 Instantiation->setInvalidDecl();
851 return true;
852}
853
855 bool SupportedForCompatibility) {
856 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
857
858 // C++23 [temp.local]p6:
859 // The name of a template-parameter shall not be bound to any following.
860 // declaration whose locus is contained by the scope to which the
861 // template-parameter belongs.
862 //
863 // When MSVC compatibility is enabled, the diagnostic is always a warning
864 // by default. Otherwise, it an error unless SupportedForCompatibility is
865 // true, in which case it is a default-to-error warning.
866 unsigned DiagId =
867 getLangOpts().MSVCCompat
868 ? diag::ext_template_param_shadow
869 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
870 : diag::err_template_param_shadow);
871 const auto *ND = cast<NamedDecl>(PrevDecl);
872 Diag(Loc, DiagId) << ND->getDeclName();
874}
875
877 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
878 D = Temp->getTemplatedDecl();
879 return Temp;
880 }
881 return nullptr;
882}
883
885 SourceLocation EllipsisLoc) const {
886 assert(Kind == Template &&
887 "Only template template arguments can be pack expansions here");
888 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
889 "Template template argument pack expansion without packs");
891 Result.EllipsisLoc = EllipsisLoc;
892 return Result;
893}
894
896 const ParsedTemplateArgument &Arg) {
897
898 switch (Arg.getKind()) {
900 TypeSourceInfo *DI;
901 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
902 if (!DI)
903 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
905 }
906
908 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
910 }
911
913 TemplateName Template = Arg.getAsTemplate().get();
914 TemplateArgument TArg;
915 if (Arg.getEllipsisLoc().isValid())
916 TArg = TemplateArgument(Template, std::optional<unsigned int>());
917 else
918 TArg = Template;
919 return TemplateArgumentLoc(
920 SemaRef.Context, TArg,
922 Arg.getLocation(), Arg.getEllipsisLoc());
923 }
924 }
925
926 llvm_unreachable("Unhandled parsed template argument");
927}
928
930 TemplateArgumentListInfo &TemplateArgs) {
931 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
932 TemplateArgs.addArgument(translateTemplateArgument(*this,
933 TemplateArgsIn[I]));
934}
935
938 const IdentifierInfo *Name) {
939 NamedDecl *PrevDecl =
941 RedeclarationKind::ForVisibleRedeclaration);
942 if (PrevDecl && PrevDecl->isTemplateParameter())
943 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
944}
945
947 TypeSourceInfo *TInfo;
949 if (T.isNull())
950 return ParsedTemplateArgument();
951 assert(TInfo && "template argument with no location");
952
953 // If we might have formed a deduced template specialization type, convert
954 // it to a template template argument.
955 if (getLangOpts().CPlusPlus17) {
956 TypeLoc TL = TInfo->getTypeLoc();
957 SourceLocation EllipsisLoc;
958 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
959 EllipsisLoc = PET.getEllipsisLoc();
960 TL = PET.getPatternLoc();
961 }
962
963 CXXScopeSpec SS;
964 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
965 SS.Adopt(ET.getQualifierLoc());
966 TL = ET.getNamedTypeLoc();
967 }
968
969 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
970 TemplateName Name = DTST.getTypePtr()->getTemplateName();
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
976 }
977 }
978
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
985 TInfo->getTypeLoc().getBeginLoc());
986}
987
989 SourceLocation EllipsisLoc,
990 SourceLocation KeyLoc,
991 IdentifierInfo *ParamName,
992 SourceLocation ParamNameLoc,
993 unsigned Depth, unsigned Position,
994 SourceLocation EqualLoc,
995 ParsedType DefaultArg,
996 bool HasTypeConstraint) {
997 assert(S->isTemplateParamScope() &&
998 "Template type parameter not in template parameter scope!");
999
1000 bool IsParameterPack = EllipsisLoc.isValid();
1003 KeyLoc, ParamNameLoc, Depth, Position,
1004 ParamName, Typename, IsParameterPack,
1005 HasTypeConstraint);
1006 Param->setAccess(AS_public);
1007
1008 if (Param->isParameterPack())
1009 if (auto *CSI = getEnclosingLambdaOrBlock())
1010 CSI->LocalPacks.push_back(Param);
1011
1012 if (ParamName) {
1013 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1014
1015 // Add the template parameter into the current scope.
1016 S->AddDecl(Param);
1017 IdResolver.AddDecl(Param);
1018 }
1019
1020 // C++0x [temp.param]p9:
1021 // A default template-argument may be specified for any kind of
1022 // template-parameter that is not a template parameter pack.
1023 if (DefaultArg && IsParameterPack) {
1024 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1025 DefaultArg = nullptr;
1026 }
1027
1028 // Handle the default argument, if provided.
1029 if (DefaultArg) {
1030 TypeSourceInfo *DefaultTInfo;
1031 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1032
1033 assert(DefaultTInfo && "expected source information for type");
1034
1035 // Check for unexpanded parameter packs.
1036 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1038 return Param;
1039
1040 // Check the template argument itself.
1041 if (CheckTemplateArgument(DefaultTInfo)) {
1042 Param->setInvalidDecl();
1043 return Param;
1044 }
1045
1046 Param->setDefaultArgument(
1047 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1048 }
1049
1050 return Param;
1051}
1052
1053/// Convert the parser's template argument list representation into our form.
1056 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1057 TemplateId.RAngleLoc);
1058 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1059 TemplateId.NumArgs);
1060 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1061 return TemplateArgs;
1062}
1063
1065
1066 TemplateName TN = TypeConstr->Template.get();
1067 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1068
1069 // C++2a [temp.param]p4:
1070 // [...] The concept designated by a type-constraint shall be a type
1071 // concept ([temp.concept]).
1072 if (!CD->isTypeConcept()) {
1073 Diag(TypeConstr->TemplateNameLoc,
1074 diag::err_type_constraint_non_type_concept);
1075 return true;
1076 }
1077
1078 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1079 return true;
1080
1081 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1082
1083 if (!WereArgsSpecified &&
1085 Diag(TypeConstr->TemplateNameLoc,
1086 diag::err_type_constraint_missing_arguments)
1087 << CD;
1088 return true;
1089 }
1090 return false;
1091}
1092
1094 TemplateIdAnnotation *TypeConstr,
1095 TemplateTypeParmDecl *ConstrainedParameter,
1096 SourceLocation EllipsisLoc) {
1097 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1098 false);
1099}
1100
1102 TemplateIdAnnotation *TypeConstr,
1103 TemplateTypeParmDecl *ConstrainedParameter,
1104 SourceLocation EllipsisLoc,
1105 bool AllowUnexpandedPack) {
1106
1107 if (CheckTypeConstraint(TypeConstr))
1108 return true;
1109
1110 TemplateName TN = TypeConstr->Template.get();
1111 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1113
1114 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1115 TypeConstr->TemplateNameLoc);
1116
1117 TemplateArgumentListInfo TemplateArgs;
1118 if (TypeConstr->LAngleLoc.isValid()) {
1119 TemplateArgs =
1120 makeTemplateArgumentListInfo(*this, *TypeConstr);
1121
1122 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1123 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1125 return true;
1126 }
1127 }
1128 }
1129 return AttachTypeConstraint(
1131 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1132 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1133 ConstrainedParameter, Context.getTypeDeclType(ConstrainedParameter),
1134 EllipsisLoc);
1135}
1136
1137template <typename ArgumentLocAppender>
1140 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1141 SourceLocation RAngleLoc, QualType ConstrainedType,
1142 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1143 SourceLocation EllipsisLoc) {
1144
1145 TemplateArgumentListInfo ConstraintArgs;
1146 ConstraintArgs.addArgument(
1148 /*NTTPType=*/QualType(), ParamNameLoc));
1149
1150 ConstraintArgs.setRAngleLoc(RAngleLoc);
1151 ConstraintArgs.setLAngleLoc(LAngleLoc);
1152 Appender(ConstraintArgs);
1153
1154 // C++2a [temp.param]p4:
1155 // [...] This constraint-expression E is called the immediately-declared
1156 // constraint of T. [...]
1157 CXXScopeSpec SS;
1158 SS.Adopt(NS);
1159 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1160 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1161 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1162 &ConstraintArgs);
1163 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1164 return ImmediatelyDeclaredConstraint;
1165
1166 // C++2a [temp.param]p4:
1167 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1168 //
1169 // We have the following case:
1170 //
1171 // template<typename T> concept C1 = true;
1172 // template<C1... T> struct s1;
1173 //
1174 // The constraint: (C1<T> && ...)
1175 //
1176 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1177 // any unqualified lookups for 'operator&&' here.
1178 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1179 /*LParenLoc=*/SourceLocation(),
1180 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1181 EllipsisLoc, /*RHS=*/nullptr,
1182 /*RParenLoc=*/SourceLocation(),
1183 /*NumExpansions=*/std::nullopt);
1184}
1185
1187 DeclarationNameInfo NameInfo,
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1189 const TemplateArgumentListInfo *TemplateArgs,
1190 TemplateTypeParmDecl *ConstrainedParameter,
1191 QualType ConstrainedType,
1192 SourceLocation EllipsisLoc) {
1193 // C++2a [temp.param]p4:
1194 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1195 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1196 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1198 *TemplateArgs) : nullptr;
1199
1200 QualType ParamAsArgument = ConstrainedType;
1201
1202 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1203 *this, NS, NameInfo, NamedConcept, FoundDecl,
1204 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1205 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1206 ParamAsArgument, ConstrainedParameter->getLocation(),
1207 [&](TemplateArgumentListInfo &ConstraintArgs) {
1208 if (TemplateArgs)
1209 for (const auto &ArgLoc : TemplateArgs->arguments())
1210 ConstraintArgs.addArgument(ArgLoc);
1211 },
1212 EllipsisLoc);
1213 if (ImmediatelyDeclaredConstraint.isInvalid())
1214 return true;
1215
1216 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1217 /*TemplateKWLoc=*/SourceLocation{},
1218 /*ConceptNameInfo=*/NameInfo,
1219 /*FoundDecl=*/FoundDecl,
1220 /*NamedConcept=*/NamedConcept,
1221 /*ArgsWritten=*/ArgsAsWritten);
1222 ConstrainedParameter->setTypeConstraint(CL,
1223 ImmediatelyDeclaredConstraint.get());
1224 return false;
1225}
1226
1228 NonTypeTemplateParmDecl *NewConstrainedParm,
1229 NonTypeTemplateParmDecl *OrigConstrainedParm,
1230 SourceLocation EllipsisLoc) {
1231 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1233 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1234 diag::err_unsupported_placeholder_constraint)
1235 << NewConstrainedParm->getTypeSourceInfo()
1236 ->getTypeLoc()
1237 .getSourceRange();
1238 return true;
1239 }
1240 // FIXME: Concepts: This should be the type of the placeholder, but this is
1241 // unclear in the wording right now.
1242 DeclRefExpr *Ref =
1243 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1244 VK_PRValue, OrigConstrainedParm->getLocation());
1245 if (!Ref)
1246 return true;
1247 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1249 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1251 OrigConstrainedParm->getLocation(),
1252 [&](TemplateArgumentListInfo &ConstraintArgs) {
1253 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1254 ConstraintArgs.addArgument(TL.getArgLoc(I));
1255 },
1256 EllipsisLoc);
1257 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1258 !ImmediatelyDeclaredConstraint.isUsable())
1259 return true;
1260
1261 NewConstrainedParm->setPlaceholderTypeConstraint(
1262 ImmediatelyDeclaredConstraint.get());
1263 return false;
1264}
1265
1268 if (TSI->getType()->isUndeducedType()) {
1269 // C++17 [temp.dep.expr]p3:
1270 // An id-expression is type-dependent if it contains
1271 // - an identifier associated by name lookup with a non-type
1272 // template-parameter declared with a type that contains a
1273 // placeholder type (7.1.7.4),
1275 }
1276
1278}
1279
1281 if (T->isDependentType())
1282 return false;
1283
1284 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1285 return true;
1286
1287 if (T->isStructuralType())
1288 return false;
1289
1290 // Structural types are required to be object types or lvalue references.
1291 if (T->isRValueReferenceType()) {
1292 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1293 return true;
1294 }
1295
1296 // Don't mention structural types in our diagnostic prior to C++20. Also,
1297 // there's not much more we can say about non-scalar non-class types --
1298 // because we can't see functions or arrays here, those can only be language
1299 // extensions.
1300 if (!getLangOpts().CPlusPlus20 ||
1301 (!T->isScalarType() && !T->isRecordType())) {
1302 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1303 return true;
1304 }
1305
1306 // Structural types are required to be literal types.
1307 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1308 return true;
1309
1310 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1311
1312 // Drill down into the reason why the class is non-structural.
1313 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1314 // All members are required to be public and non-mutable, and can't be of
1315 // rvalue reference type. Check these conditions first to prefer a "local"
1316 // reason over a more distant one.
1317 for (const FieldDecl *FD : RD->fields()) {
1318 if (FD->getAccess() != AS_public) {
1319 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1320 return true;
1321 }
1322 if (FD->isMutable()) {
1323 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1324 return true;
1325 }
1326 if (FD->getType()->isRValueReferenceType()) {
1327 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1328 << T;
1329 return true;
1330 }
1331 }
1332
1333 // All bases are required to be public.
1334 for (const auto &BaseSpec : RD->bases()) {
1335 if (BaseSpec.getAccessSpecifier() != AS_public) {
1336 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1337 << T << 1;
1338 return true;
1339 }
1340 }
1341
1342 // All subobjects are required to be of structural types.
1343 SourceLocation SubLoc;
1344 QualType SubType;
1345 int Kind = -1;
1346
1347 for (const FieldDecl *FD : RD->fields()) {
1348 QualType T = Context.getBaseElementType(FD->getType());
1349 if (!T->isStructuralType()) {
1350 SubLoc = FD->getLocation();
1351 SubType = T;
1352 Kind = 0;
1353 break;
1354 }
1355 }
1356
1357 if (Kind == -1) {
1358 for (const auto &BaseSpec : RD->bases()) {
1359 QualType T = BaseSpec.getType();
1360 if (!T->isStructuralType()) {
1361 SubLoc = BaseSpec.getBaseTypeLoc();
1362 SubType = T;
1363 Kind = 1;
1364 break;
1365 }
1366 }
1367 }
1368
1369 assert(Kind != -1 && "couldn't find reason why type is not structural");
1370 Diag(SubLoc, diag::note_not_structural_subobject)
1371 << T << Kind << SubType;
1372 T = SubType;
1373 RD = T->getAsCXXRecordDecl();
1374 }
1375
1376 return true;
1377}
1378
1381 // We don't allow variably-modified types as the type of non-type template
1382 // parameters.
1383 if (T->isVariablyModifiedType()) {
1384 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1385 << T;
1386 return QualType();
1387 }
1388
1389 // C++ [temp.param]p4:
1390 //
1391 // A non-type template-parameter shall have one of the following
1392 // (optionally cv-qualified) types:
1393 //
1394 // -- integral or enumeration type,
1396 // -- pointer to object or pointer to function,
1397 T->isPointerType() ||
1398 // -- lvalue reference to object or lvalue reference to function,
1400 // -- pointer to member,
1402 // -- std::nullptr_t, or
1403 T->isNullPtrType() ||
1404 // -- a type that contains a placeholder type.
1405 T->isUndeducedType()) {
1406 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1407 // are ignored when determining its type.
1408 return T.getUnqualifiedType();
1409 }
1410
1411 // C++ [temp.param]p8:
1412 //
1413 // A non-type template-parameter of type "array of T" or
1414 // "function returning T" is adjusted to be of type "pointer to
1415 // T" or "pointer to function returning T", respectively.
1416 if (T->isArrayType() || T->isFunctionType())
1417 return Context.getDecayedType(T);
1418
1419 // If T is a dependent type, we can't do the check now, so we
1420 // assume that it is well-formed. Note that stripping off the
1421 // qualifiers here is not really correct if T turns out to be
1422 // an array type, but we'll recompute the type everywhere it's
1423 // used during instantiation, so that should be OK. (Using the
1424 // qualified type is equally wrong.)
1425 if (T->isDependentType())
1426 return T.getUnqualifiedType();
1427
1428 // C++20 [temp.param]p6:
1429 // -- a structural type
1431 return QualType();
1432
1433 if (!getLangOpts().CPlusPlus20) {
1434 // FIXME: Consider allowing structural types as an extension in C++17. (In
1435 // earlier language modes, the template argument evaluation rules are too
1436 // inflexible.)
1437 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1438 return QualType();
1439 }
1440
1441 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1442 return T.getUnqualifiedType();
1443}
1444
1446 unsigned Depth,
1447 unsigned Position,
1448 SourceLocation EqualLoc,
1449 Expr *Default) {
1451
1452 // Check that we have valid decl-specifiers specified.
1453 auto CheckValidDeclSpecifiers = [this, &D] {
1454 // C++ [temp.param]
1455 // p1
1456 // template-parameter:
1457 // ...
1458 // parameter-declaration
1459 // p2
1460 // ... A storage class shall not be specified in a template-parameter
1461 // declaration.
1462 // [dcl.typedef]p1:
1463 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1464 // of a parameter-declaration
1465 const DeclSpec &DS = D.getDeclSpec();
1466 auto EmitDiag = [this](SourceLocation Loc) {
1467 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1469 };
1471 EmitDiag(DS.getStorageClassSpecLoc());
1472
1474 EmitDiag(DS.getThreadStorageClassSpecLoc());
1475
1476 // [dcl.inline]p1:
1477 // The inline specifier can be applied only to the declaration or
1478 // definition of a variable or function.
1479
1480 if (DS.isInlineSpecified())
1481 EmitDiag(DS.getInlineSpecLoc());
1482
1483 // [dcl.constexpr]p1:
1484 // The constexpr specifier shall be applied only to the definition of a
1485 // variable or variable template or the declaration of a function or
1486 // function template.
1487
1488 if (DS.hasConstexprSpecifier())
1489 EmitDiag(DS.getConstexprSpecLoc());
1490
1491 // [dcl.fct.spec]p1:
1492 // Function-specifiers can be used only in function declarations.
1493
1494 if (DS.isVirtualSpecified())
1495 EmitDiag(DS.getVirtualSpecLoc());
1496
1497 if (DS.hasExplicitSpecifier())
1498 EmitDiag(DS.getExplicitSpecLoc());
1499
1500 if (DS.isNoreturnSpecified())
1501 EmitDiag(DS.getNoreturnSpecLoc());
1502 };
1503
1504 CheckValidDeclSpecifiers();
1505
1506 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1507 if (isa<AutoType>(T))
1508 Diag(D.getIdentifierLoc(),
1509 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1510 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1511
1512 assert(S->isTemplateParamScope() &&
1513 "Non-type template parameter not in template parameter scope!");
1514 bool Invalid = false;
1515
1516 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1517 if (T.isNull()) {
1518 T = Context.IntTy; // Recover with an 'int' type.
1519 Invalid = true;
1520 }
1521
1523
1524 const IdentifierInfo *ParamName = D.getIdentifier();
1525 bool IsParameterPack = D.hasEllipsis();
1528 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1529 TInfo);
1530 Param->setAccess(AS_public);
1531
1533 if (TL.isConstrained()) {
1534 if (D.getEllipsisLoc().isInvalid() &&
1536 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1537 for (auto &Loc :
1538 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1541 }
1542 if (!Invalid &&
1543 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1544 Invalid = true;
1545 }
1546
1547 if (Invalid)
1548 Param->setInvalidDecl();
1549
1550 if (Param->isParameterPack())
1551 if (auto *CSI = getEnclosingLambdaOrBlock())
1552 CSI->LocalPacks.push_back(Param);
1553
1554 if (ParamName) {
1555 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1556 ParamName);
1557
1558 // Add the template parameter into the current scope.
1559 S->AddDecl(Param);
1560 IdResolver.AddDecl(Param);
1561 }
1562
1563 // C++0x [temp.param]p9:
1564 // A default template-argument may be specified for any kind of
1565 // template-parameter that is not a template parameter pack.
1566 if (Default && IsParameterPack) {
1567 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1568 Default = nullptr;
1569 }
1570
1571 // Check the well-formedness of the default template argument, if provided.
1572 if (Default) {
1573 // Check for unexpanded parameter packs.
1575 return Param;
1576
1577 Param->setDefaultArgument(
1579 QualType(), SourceLocation()));
1580 }
1581
1582 return Param;
1583}
1584
1586 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1587 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1588 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1590 assert(S->isTemplateParamScope() &&
1591 "Template template parameter not in template parameter scope!");
1592
1593 // Construct the parameter object.
1594 bool IsParameterPack = EllipsisLoc.isValid();
1597 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1598 Name, Typename, Params);
1599 Param->setAccess(AS_public);
1600
1601 if (Param->isParameterPack())
1602 if (auto *LSI = getEnclosingLambdaOrBlock())
1603 LSI->LocalPacks.push_back(Param);
1604
1605 // If the template template parameter has a name, then link the identifier
1606 // into the scope and lookup mechanisms.
1607 if (Name) {
1608 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1609
1610 S->AddDecl(Param);
1611 IdResolver.AddDecl(Param);
1612 }
1613
1614 if (Params->size() == 0) {
1615 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1616 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1617 Param->setInvalidDecl();
1618 }
1619
1620 // C++0x [temp.param]p9:
1621 // A default template-argument may be specified for any kind of
1622 // template-parameter that is not a template parameter pack.
1623 if (IsParameterPack && !Default.isInvalid()) {
1624 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1626 }
1627
1628 if (!Default.isInvalid()) {
1629 // Check only that we have a template template argument. We don't want to
1630 // try to check well-formedness now, because our template template parameter
1631 // might have dependent types in its template parameters, which we wouldn't
1632 // be able to match now.
1633 //
1634 // If none of the template template parameter's template arguments mention
1635 // other template parameters, we could actually perform more checking here.
1636 // However, it isn't worth doing.
1638 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1639 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1640 << DefaultArg.getSourceRange();
1641 return Param;
1642 }
1643
1644 // Check for unexpanded parameter packs.
1646 DefaultArg.getArgument().getAsTemplate(),
1648 return Param;
1649
1650 Param->setDefaultArgument(Context, DefaultArg);
1651 }
1652
1653 return Param;
1654}
1655
1656namespace {
1657class ConstraintRefersToContainingTemplateChecker
1658 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1659 bool Result = false;
1660 const FunctionDecl *Friend = nullptr;
1661 unsigned TemplateDepth = 0;
1662
1663 // Check a record-decl that we've seen to see if it is a lexical parent of the
1664 // Friend, likely because it was referred to without its template arguments.
1665 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1666 CheckingRD = CheckingRD->getMostRecentDecl();
1667 if (!CheckingRD->isTemplated())
1668 return;
1669
1670 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1671 DC && !DC->isFileContext(); DC = DC->getParent())
1672 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1673 if (CheckingRD == RD->getMostRecentDecl())
1674 Result = true;
1675 }
1676
1677 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1678 if (D->getDepth() < TemplateDepth)
1679 Result = true;
1680
1681 // Necessary because the type of the NTTP might be what refers to the parent
1682 // constriant.
1683 TransformType(D->getType());
1684 }
1685
1686public:
1688
1689 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1690 const FunctionDecl *Friend,
1691 unsigned TemplateDepth)
1692 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1693 bool getResult() const { return Result; }
1694
1695 // This should be the only template parm type that we have to deal with.
1696 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1697 // FunctionParmPackExpr are all partially substituted, which cannot happen
1698 // with concepts at this point in translation.
1699 using inherited::TransformTemplateTypeParmType;
1700 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1701 TemplateTypeParmTypeLoc TL, bool) {
1702 if (TL.getDecl()->getDepth() < TemplateDepth)
1703 Result = true;
1704 return inherited::TransformTemplateTypeParmType(
1705 TLB, TL,
1706 /*SuppressObjCLifetime=*/false);
1707 }
1708
1709 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1710 if (!D)
1711 return D;
1712 // FIXME : This is possibly an incomplete list, but it is unclear what other
1713 // Decl kinds could be used to refer to the template parameters. This is a
1714 // best guess so far based on examples currently available, but the
1715 // unreachable should catch future instances/cases.
1716 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1717 TransformType(TD->getUnderlyingType());
1718 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1719 CheckNonTypeTemplateParmDecl(NTTPD);
1720 else if (auto *VD = dyn_cast<ValueDecl>(D))
1721 TransformType(VD->getType());
1722 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1723 TransformTemplateParameterList(TD->getTemplateParameters());
1724 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1725 CheckIfContainingRecord(RD);
1726 else if (isa<NamedDecl>(D)) {
1727 // No direct types to visit here I believe.
1728 } else
1729 llvm_unreachable("Don't know how to handle this declaration type yet");
1730 return D;
1731 }
1732};
1733} // namespace
1734
1736 const FunctionDecl *Friend, unsigned TemplateDepth,
1737 const Expr *Constraint) {
1738 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1739 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1740 TemplateDepth);
1741 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1742 return Checker.getResult();
1743}
1744
1747 SourceLocation ExportLoc,
1748 SourceLocation TemplateLoc,
1749 SourceLocation LAngleLoc,
1750 ArrayRef<NamedDecl *> Params,
1751 SourceLocation RAngleLoc,
1752 Expr *RequiresClause) {
1753 if (ExportLoc.isValid())
1754 Diag(ExportLoc, diag::warn_template_export_unsupported);
1755
1756 for (NamedDecl *P : Params)
1758
1760 Context, TemplateLoc, LAngleLoc,
1761 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1762}
1763
1765 const CXXScopeSpec &SS) {
1766 if (SS.isSet())
1767 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1768}
1769
1770// Returns the template parameter list with all default template argument
1771// information.
1773 // Make sure we get the template parameter list from the most
1774 // recent declaration, since that is the only one that is guaranteed to
1775 // have all the default template argument information.
1776 Decl *D = TD->getMostRecentDecl();
1777 // C++11 N3337 [temp.param]p12:
1778 // A default template argument shall not be specified in a friend class
1779 // template declaration.
1780 //
1781 // Skip past friend *declarations* because they are not supposed to contain
1782 // default template arguments. Moreover, these declarations may introduce
1783 // template parameters living in different template depths than the
1784 // corresponding template parameters in TD, causing unmatched constraint
1785 // substitution.
1786 //
1787 // FIXME: Diagnose such cases within a class template:
1788 // template <class T>
1789 // struct S {
1790 // template <class = void> friend struct C;
1791 // };
1792 // template struct S<int>;
1794 D->getPreviousDecl())
1795 D = D->getPreviousDecl();
1796 return cast<TemplateDecl>(D)->getTemplateParameters();
1797}
1798
1800 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1801 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1802 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1803 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1804 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1805 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1806 assert(TemplateParams && TemplateParams->size() > 0 &&
1807 "No template parameters");
1808 assert(TUK != TagUseKind::Reference &&
1809 "Can only declare or define class templates");
1810 bool Invalid = false;
1811
1812 // Check that we can declare a template here.
1813 if (CheckTemplateDeclScope(S, TemplateParams))
1814 return true;
1815
1817 assert(Kind != TagTypeKind::Enum &&
1818 "can't build template of enumerated type");
1819
1820 // There is no such thing as an unnamed class template.
1821 if (!Name) {
1822 Diag(KWLoc, diag::err_template_unnamed_class);
1823 return true;
1824 }
1825
1826 // Find any previous declaration with this name. For a friend with no
1827 // scope explicitly specified, we only look for tag declarations (per
1828 // C++11 [basic.lookup.elab]p2).
1829 DeclContext *SemanticContext;
1830 LookupResult Previous(*this, Name, NameLoc,
1831 (SS.isEmpty() && TUK == TagUseKind::Friend)
1835 if (SS.isNotEmpty() && !SS.isInvalid()) {
1836 SemanticContext = computeDeclContext(SS, true);
1837 if (!SemanticContext) {
1838 // FIXME: Horrible, horrible hack! We can't currently represent this
1839 // in the AST, and historically we have just ignored such friend
1840 // class templates, so don't complain here.
1841 Diag(NameLoc, TUK == TagUseKind::Friend
1842 ? diag::warn_template_qualified_friend_ignored
1843 : diag::err_template_qualified_declarator_no_match)
1844 << SS.getScopeRep() << SS.getRange();
1845 return TUK != TagUseKind::Friend;
1846 }
1847
1848 if (RequireCompleteDeclContext(SS, SemanticContext))
1849 return true;
1850
1851 // If we're adding a template to a dependent context, we may need to
1852 // rebuilding some of the types used within the template parameter list,
1853 // now that we know what the current instantiation is.
1854 if (SemanticContext->isDependentContext()) {
1855 ContextRAII SavedContext(*this, SemanticContext);
1857 Invalid = true;
1858 }
1859
1860 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1861 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1862 /*TemplateId-*/ nullptr,
1863 /*IsMemberSpecialization*/ false);
1864
1865 LookupQualifiedName(Previous, SemanticContext);
1866 } else {
1867 SemanticContext = CurContext;
1868
1869 // C++14 [class.mem]p14:
1870 // If T is the name of a class, then each of the following shall have a
1871 // name different from T:
1872 // -- every member template of class T
1873 if (TUK != TagUseKind::Friend &&
1874 DiagnoseClassNameShadow(SemanticContext,
1875 DeclarationNameInfo(Name, NameLoc)))
1876 return true;
1877
1878 LookupName(Previous, S);
1879 }
1880
1881 if (Previous.isAmbiguous())
1882 return true;
1883
1884 // Let the template parameter scope enter the lookup chain of the current
1885 // class template. For example, given
1886 //
1887 // namespace ns {
1888 // template <class> bool Param = false;
1889 // template <class T> struct N;
1890 // }
1891 //
1892 // template <class Param> struct ns::N { void foo(Param); };
1893 //
1894 // When we reference Param inside the function parameter list, our name lookup
1895 // chain for it should be like:
1896 // FunctionScope foo
1897 // -> RecordScope N
1898 // -> TemplateParamScope (where we will find Param)
1899 // -> NamespaceScope ns
1900 //
1901 // See also CppLookupName().
1902 if (S->isTemplateParamScope())
1903 EnterTemplatedContext(S, SemanticContext);
1904
1905 NamedDecl *PrevDecl = nullptr;
1906 if (Previous.begin() != Previous.end())
1907 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1908
1909 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1910 // Maybe we will complain about the shadowed template parameter.
1911 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1912 // Just pretend that we didn't see the previous declaration.
1913 PrevDecl = nullptr;
1914 }
1915
1916 // If there is a previous declaration with the same name, check
1917 // whether this is a valid redeclaration.
1918 ClassTemplateDecl *PrevClassTemplate =
1919 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1920
1921 // We may have found the injected-class-name of a class template,
1922 // class template partial specialization, or class template specialization.
1923 // In these cases, grab the template that is being defined or specialized.
1924 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1925 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1926 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1927 PrevClassTemplate
1928 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1929 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1930 PrevClassTemplate
1931 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1932 ->getSpecializedTemplate();
1933 }
1934 }
1935
1936 if (TUK == TagUseKind::Friend) {
1937 // C++ [namespace.memdef]p3:
1938 // [...] When looking for a prior declaration of a class or a function
1939 // declared as a friend, and when the name of the friend class or
1940 // function is neither a qualified name nor a template-id, scopes outside
1941 // the innermost enclosing namespace scope are not considered.
1942 if (!SS.isSet()) {
1943 DeclContext *OutermostContext = CurContext;
1944 while (!OutermostContext->isFileContext())
1945 OutermostContext = OutermostContext->getLookupParent();
1946
1947 if (PrevDecl &&
1948 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1949 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1950 SemanticContext = PrevDecl->getDeclContext();
1951 } else {
1952 // Declarations in outer scopes don't matter. However, the outermost
1953 // context we computed is the semantic context for our new
1954 // declaration.
1955 PrevDecl = PrevClassTemplate = nullptr;
1956 SemanticContext = OutermostContext;
1957
1958 // Check that the chosen semantic context doesn't already contain a
1959 // declaration of this name as a non-tag type.
1961 DeclContext *LookupContext = SemanticContext;
1962 while (LookupContext->isTransparentContext())
1963 LookupContext = LookupContext->getLookupParent();
1964 LookupQualifiedName(Previous, LookupContext);
1965
1966 if (Previous.isAmbiguous())
1967 return true;
1968
1969 if (Previous.begin() != Previous.end())
1970 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1971 }
1972 }
1973 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1974 SemanticContext, S, SS.isValid()))
1975 PrevDecl = PrevClassTemplate = nullptr;
1976
1977 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1978 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1979 if (SS.isEmpty() &&
1980 !(PrevClassTemplate &&
1981 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1982 SemanticContext->getRedeclContext()))) {
1983 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1984 Diag(Shadow->getTargetDecl()->getLocation(),
1985 diag::note_using_decl_target);
1986 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1987 // Recover by ignoring the old declaration.
1988 PrevDecl = PrevClassTemplate = nullptr;
1989 }
1990 }
1991
1992 if (PrevClassTemplate) {
1993 // Ensure that the template parameter lists are compatible. Skip this check
1994 // for a friend in a dependent context: the template parameter list itself
1995 // could be dependent.
1996 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1998 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1999 : CurContext,
2000 CurContext, KWLoc),
2001 TemplateParams, PrevClassTemplate,
2002 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2004 return true;
2005
2006 // C++ [temp.class]p4:
2007 // In a redeclaration, partial specialization, explicit
2008 // specialization or explicit instantiation of a class template,
2009 // the class-key shall agree in kind with the original class
2010 // template declaration (7.1.5.3).
2011 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2013 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2014 Diag(KWLoc, diag::err_use_with_wrong_tag)
2015 << Name
2016 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2017 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2018 Kind = PrevRecordDecl->getTagKind();
2019 }
2020
2021 // Check for redefinition of this class template.
2022 if (TUK == TagUseKind::Definition) {
2023 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2024 // If we have a prior definition that is not visible, treat this as
2025 // simply making that previous definition visible.
2026 NamedDecl *Hidden = nullptr;
2027 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2028 SkipBody->ShouldSkip = true;
2029 SkipBody->Previous = Def;
2030 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2031 assert(Tmpl && "original definition of a class template is not a "
2032 "class template?");
2035 } else {
2036 Diag(NameLoc, diag::err_redefinition) << Name;
2037 Diag(Def->getLocation(), diag::note_previous_definition);
2038 // FIXME: Would it make sense to try to "forget" the previous
2039 // definition, as part of error recovery?
2040 return true;
2041 }
2042 }
2043 }
2044 } else if (PrevDecl) {
2045 // C++ [temp]p5:
2046 // A class template shall not have the same name as any other
2047 // template, class, function, object, enumeration, enumerator,
2048 // namespace, or type in the same scope (3.3), except as specified
2049 // in (14.5.4).
2050 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2051 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2052 return true;
2053 }
2054
2055 // Check the template parameter list of this declaration, possibly
2056 // merging in the template parameter list from the previous class
2057 // template declaration. Skip this check for a friend in a dependent
2058 // context, because the template parameter list might be dependent.
2059 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2061 TemplateParams,
2062 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2063 : nullptr,
2064 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2065 SemanticContext->isDependentContext())
2069 SkipBody))
2070 Invalid = true;
2071
2072 if (SS.isSet()) {
2073 // If the name of the template was qualified, we must be defining the
2074 // template out-of-line.
2075 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2076 Diag(NameLoc, TUK == TagUseKind::Friend
2077 ? diag::err_friend_decl_does_not_match
2078 : diag::err_member_decl_does_not_match)
2079 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2080 Invalid = true;
2081 }
2082 }
2083
2084 // If this is a templated friend in a dependent context we should not put it
2085 // on the redecl chain. In some cases, the templated friend can be the most
2086 // recent declaration tricking the template instantiator to make substitutions
2087 // there.
2088 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2089 bool ShouldAddRedecl =
2091
2092 CXXRecordDecl *NewClass =
2093 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2094 PrevClassTemplate && ShouldAddRedecl ?
2095 PrevClassTemplate->getTemplatedDecl() : nullptr,
2096 /*DelayTypeCreation=*/true);
2097 SetNestedNameSpecifier(*this, NewClass, SS);
2098 if (NumOuterTemplateParamLists > 0)
2100 Context,
2101 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2102
2103 // Add alignment attributes if necessary; these attributes are checked when
2104 // the ASTContext lays out the structure.
2105 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2108 }
2109
2110 ClassTemplateDecl *NewTemplate
2111 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2112 DeclarationName(Name), TemplateParams,
2113 NewClass);
2114
2115 if (ShouldAddRedecl)
2116 NewTemplate->setPreviousDecl(PrevClassTemplate);
2117
2118 NewClass->setDescribedClassTemplate(NewTemplate);
2119
2120 if (ModulePrivateLoc.isValid())
2121 NewTemplate->setModulePrivate();
2122
2123 // Build the type for the class template declaration now.
2125 T = Context.getInjectedClassNameType(NewClass, T);
2126 assert(T->isDependentType() && "Class template type is not dependent?");
2127 (void)T;
2128
2129 // If we are providing an explicit specialization of a member that is a
2130 // class template, make a note of that.
2131 if (PrevClassTemplate &&
2132 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2133 PrevClassTemplate->setMemberSpecialization();
2134
2135 // Set the access specifier.
2136 if (!Invalid && TUK != TagUseKind::Friend &&
2137 NewTemplate->getDeclContext()->isRecord())
2138 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2139
2140 // Set the lexical context of these templates
2142 NewTemplate->setLexicalDeclContext(CurContext);
2143
2144 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2145 NewClass->startDefinition();
2146
2147 ProcessDeclAttributeList(S, NewClass, Attr);
2148 ProcessAPINotes(NewClass);
2149
2150 if (PrevClassTemplate)
2151 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2152
2156
2157 if (TUK != TagUseKind::Friend) {
2158 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2159 Scope *Outer = S;
2160 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2161 Outer = Outer->getParent();
2162 PushOnScopeChains(NewTemplate, Outer);
2163 } else {
2164 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2165 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2166 NewClass->setAccess(PrevClassTemplate->getAccess());
2167 }
2168
2169 NewTemplate->setObjectOfFriendDecl();
2170
2171 // Friend templates are visible in fairly strange ways.
2173 DeclContext *DC = SemanticContext->getRedeclContext();
2174 DC->makeDeclVisibleInContext(NewTemplate);
2175 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2176 PushOnScopeChains(NewTemplate, EnclosingScope,
2177 /* AddToContext = */ false);
2178 }
2179
2181 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2182 Friend->setAccess(AS_public);
2184 }
2185
2186 if (PrevClassTemplate)
2187 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2188
2189 if (Invalid) {
2190 NewTemplate->setInvalidDecl();
2191 NewClass->setInvalidDecl();
2192 }
2193
2194 ActOnDocumentableDecl(NewTemplate);
2195
2196 if (SkipBody && SkipBody->ShouldSkip)
2197 return SkipBody->Previous;
2198
2199 return NewTemplate;
2200}
2201
2202/// Diagnose the presence of a default template argument on a
2203/// template parameter, which is ill-formed in certain contexts.
2204///
2205/// \returns true if the default template argument should be dropped.
2208 SourceLocation ParamLoc,
2209 SourceRange DefArgRange) {
2210 switch (TPC) {
2214 return false;
2215
2218 // C++ [temp.param]p9:
2219 // A default template-argument shall not be specified in a
2220 // function template declaration or a function template
2221 // definition [...]
2222 // If a friend function template declaration specifies a default
2223 // template-argument, that declaration shall be a definition and shall be
2224 // the only declaration of the function template in the translation unit.
2225 // (C++98/03 doesn't have this wording; see DR226).
2226 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2227 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2228 : diag::ext_template_parameter_default_in_function_template)
2229 << DefArgRange;
2230 return false;
2231
2233 // C++0x [temp.param]p9:
2234 // A default template-argument shall not be specified in the
2235 // template-parameter-lists of the definition of a member of a
2236 // class template that appears outside of the member's class.
2237 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2238 << DefArgRange;
2239 return true;
2240
2243 // C++ [temp.param]p9:
2244 // A default template-argument shall not be specified in a
2245 // friend template declaration.
2246 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2247 << DefArgRange;
2248 return true;
2249
2250 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2251 // for friend function templates if there is only a single
2252 // declaration (and it is a definition). Strange!
2253 }
2254
2255 llvm_unreachable("Invalid TemplateParamListContext!");
2256}
2257
2258/// Check for unexpanded parameter packs within the template parameters
2259/// of a template template parameter, recursively.
2262 // A template template parameter which is a parameter pack is also a pack
2263 // expansion.
2264 if (TTP->isParameterPack())
2265 return false;
2266
2268 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2269 NamedDecl *P = Params->getParam(I);
2270 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2271 if (!TTP->isParameterPack())
2272 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2273 if (TC->hasExplicitTemplateArgs())
2274 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2277 return true;
2278 continue;
2279 }
2280
2281 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2282 if (!NTTP->isParameterPack() &&
2283 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2284 NTTP->getTypeSourceInfo(),
2286 return true;
2287
2288 continue;
2289 }
2290
2291 if (TemplateTemplateParmDecl *InnerTTP
2292 = dyn_cast<TemplateTemplateParmDecl>(P))
2293 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2294 return true;
2295 }
2296
2297 return false;
2298}
2299
2301 TemplateParameterList *OldParams,
2303 SkipBodyInfo *SkipBody) {
2304 bool Invalid = false;
2305
2306 // C++ [temp.param]p10:
2307 // The set of default template-arguments available for use with a
2308 // template declaration or definition is obtained by merging the
2309 // default arguments from the definition (if in scope) and all
2310 // declarations in scope in the same way default function
2311 // arguments are (8.3.6).
2312 bool SawDefaultArgument = false;
2313 SourceLocation PreviousDefaultArgLoc;
2314
2315 // Dummy initialization to avoid warnings.
2316 TemplateParameterList::iterator OldParam = NewParams->end();
2317 if (OldParams)
2318 OldParam = OldParams->begin();
2319
2320 bool RemoveDefaultArguments = false;
2321 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2322 NewParamEnd = NewParams->end();
2323 NewParam != NewParamEnd; ++NewParam) {
2324 // Whether we've seen a duplicate default argument in the same translation
2325 // unit.
2326 bool RedundantDefaultArg = false;
2327 // Whether we've found inconsis inconsitent default arguments in different
2328 // translation unit.
2329 bool InconsistentDefaultArg = false;
2330 // The name of the module which contains the inconsistent default argument.
2331 std::string PrevModuleName;
2332
2333 SourceLocation OldDefaultLoc;
2334 SourceLocation NewDefaultLoc;
2335
2336 // Variable used to diagnose missing default arguments
2337 bool MissingDefaultArg = false;
2338
2339 // Variable used to diagnose non-final parameter packs
2340 bool SawParameterPack = false;
2341
2342 if (TemplateTypeParmDecl *NewTypeParm
2343 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2344 // Check the presence of a default argument here.
2345 if (NewTypeParm->hasDefaultArgument() &&
2347 *this, TPC, NewTypeParm->getLocation(),
2348 NewTypeParm->getDefaultArgument().getSourceRange()))
2349 NewTypeParm->removeDefaultArgument();
2350
2351 // Merge default arguments for template type parameters.
2352 TemplateTypeParmDecl *OldTypeParm
2353 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2354 if (NewTypeParm->isParameterPack()) {
2355 assert(!NewTypeParm->hasDefaultArgument() &&
2356 "Parameter packs can't have a default argument!");
2357 SawParameterPack = true;
2358 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2359 NewTypeParm->hasDefaultArgument() &&
2360 (!SkipBody || !SkipBody->ShouldSkip)) {
2361 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2362 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2363 SawDefaultArgument = true;
2364
2365 if (!OldTypeParm->getOwningModule())
2366 RedundantDefaultArg = true;
2367 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2368 NewTypeParm)) {
2369 InconsistentDefaultArg = true;
2370 PrevModuleName =
2372 }
2373 PreviousDefaultArgLoc = NewDefaultLoc;
2374 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2375 // Merge the default argument from the old declaration to the
2376 // new declaration.
2377 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2378 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2379 } else if (NewTypeParm->hasDefaultArgument()) {
2380 SawDefaultArgument = true;
2381 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2382 } else if (SawDefaultArgument)
2383 MissingDefaultArg = true;
2384 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2385 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2386 // Check for unexpanded parameter packs.
2387 if (!NewNonTypeParm->isParameterPack() &&
2388 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2389 NewNonTypeParm->getTypeSourceInfo(),
2391 Invalid = true;
2392 continue;
2393 }
2394
2395 // Check the presence of a default argument here.
2396 if (NewNonTypeParm->hasDefaultArgument() &&
2398 *this, TPC, NewNonTypeParm->getLocation(),
2399 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2400 NewNonTypeParm->removeDefaultArgument();
2401 }
2402
2403 // Merge default arguments for non-type template parameters
2404 NonTypeTemplateParmDecl *OldNonTypeParm
2405 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2406 if (NewNonTypeParm->isParameterPack()) {
2407 assert(!NewNonTypeParm->hasDefaultArgument() &&
2408 "Parameter packs can't have a default argument!");
2409 if (!NewNonTypeParm->isPackExpansion())
2410 SawParameterPack = true;
2411 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2412 NewNonTypeParm->hasDefaultArgument() &&
2413 (!SkipBody || !SkipBody->ShouldSkip)) {
2414 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2415 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2416 SawDefaultArgument = true;
2417 if (!OldNonTypeParm->getOwningModule())
2418 RedundantDefaultArg = true;
2419 else if (!getASTContext().isSameDefaultTemplateArgument(
2420 OldNonTypeParm, NewNonTypeParm)) {
2421 InconsistentDefaultArg = true;
2422 PrevModuleName =
2423 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2424 }
2425 PreviousDefaultArgLoc = NewDefaultLoc;
2426 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2427 // Merge the default argument from the old declaration to the
2428 // new declaration.
2429 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2430 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2431 } else if (NewNonTypeParm->hasDefaultArgument()) {
2432 SawDefaultArgument = true;
2433 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2434 } else if (SawDefaultArgument)
2435 MissingDefaultArg = true;
2436 } else {
2437 TemplateTemplateParmDecl *NewTemplateParm
2438 = cast<TemplateTemplateParmDecl>(*NewParam);
2439
2440 // Check for unexpanded parameter packs, recursively.
2441 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2442 Invalid = true;
2443 continue;
2444 }
2445
2446 // Check the presence of a default argument here.
2447 if (NewTemplateParm->hasDefaultArgument() &&
2449 NewTemplateParm->getLocation(),
2450 NewTemplateParm->getDefaultArgument().getSourceRange()))
2451 NewTemplateParm->removeDefaultArgument();
2452
2453 // Merge default arguments for template template parameters
2454 TemplateTemplateParmDecl *OldTemplateParm
2455 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2456 if (NewTemplateParm->isParameterPack()) {
2457 assert(!NewTemplateParm->hasDefaultArgument() &&
2458 "Parameter packs can't have a default argument!");
2459 if (!NewTemplateParm->isPackExpansion())
2460 SawParameterPack = true;
2461 } else if (OldTemplateParm &&
2462 hasVisibleDefaultArgument(OldTemplateParm) &&
2463 NewTemplateParm->hasDefaultArgument() &&
2464 (!SkipBody || !SkipBody->ShouldSkip)) {
2465 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2466 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2467 SawDefaultArgument = true;
2468 if (!OldTemplateParm->getOwningModule())
2469 RedundantDefaultArg = true;
2470 else if (!getASTContext().isSameDefaultTemplateArgument(
2471 OldTemplateParm, NewTemplateParm)) {
2472 InconsistentDefaultArg = true;
2473 PrevModuleName =
2474 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2475 }
2476 PreviousDefaultArgLoc = NewDefaultLoc;
2477 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2478 // Merge the default argument from the old declaration to the
2479 // new declaration.
2480 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2481 PreviousDefaultArgLoc
2482 = OldTemplateParm->getDefaultArgument().getLocation();
2483 } else if (NewTemplateParm->hasDefaultArgument()) {
2484 SawDefaultArgument = true;
2485 PreviousDefaultArgLoc
2486 = NewTemplateParm->getDefaultArgument().getLocation();
2487 } else if (SawDefaultArgument)
2488 MissingDefaultArg = true;
2489 }
2490
2491 // C++11 [temp.param]p11:
2492 // If a template parameter of a primary class template or alias template
2493 // is a template parameter pack, it shall be the last template parameter.
2494 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2495 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2496 TPC == TPC_TypeAliasTemplate)) {
2497 Diag((*NewParam)->getLocation(),
2498 diag::err_template_param_pack_must_be_last_template_parameter);
2499 Invalid = true;
2500 }
2501
2502 // [basic.def.odr]/13:
2503 // There can be more than one definition of a
2504 // ...
2505 // default template argument
2506 // ...
2507 // in a program provided that each definition appears in a different
2508 // translation unit and the definitions satisfy the [same-meaning
2509 // criteria of the ODR].
2510 //
2511 // Simply, the design of modules allows the definition of template default
2512 // argument to be repeated across translation unit. Note that the ODR is
2513 // checked elsewhere. But it is still not allowed to repeat template default
2514 // argument in the same translation unit.
2515 if (RedundantDefaultArg) {
2516 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2517 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2518 Invalid = true;
2519 } else if (InconsistentDefaultArg) {
2520 // We could only diagnose about the case that the OldParam is imported.
2521 // The case NewParam is imported should be handled in ASTReader.
2522 Diag(NewDefaultLoc,
2523 diag::err_template_param_default_arg_inconsistent_redefinition);
2524 Diag(OldDefaultLoc,
2525 diag::note_template_param_prev_default_arg_in_other_module)
2526 << PrevModuleName;
2527 Invalid = true;
2528 } else if (MissingDefaultArg &&
2529 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2530 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2531 // C++ 23[temp.param]p14:
2532 // If a template-parameter of a class template, variable template, or
2533 // alias template has a default template argument, each subsequent
2534 // template-parameter shall either have a default template argument
2535 // supplied or be a template parameter pack.
2536 Diag((*NewParam)->getLocation(),
2537 diag::err_template_param_default_arg_missing);
2538 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2539 Invalid = true;
2540 RemoveDefaultArguments = true;
2541 }
2542
2543 // If we have an old template parameter list that we're merging
2544 // in, move on to the next parameter.
2545 if (OldParams)
2546 ++OldParam;
2547 }
2548
2549 // We were missing some default arguments at the end of the list, so remove
2550 // all of the default arguments.
2551 if (RemoveDefaultArguments) {
2552 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2553 NewParamEnd = NewParams->end();
2554 NewParam != NewParamEnd; ++NewParam) {
2555 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2556 TTP->removeDefaultArgument();
2557 else if (NonTypeTemplateParmDecl *NTTP
2558 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2559 NTTP->removeDefaultArgument();
2560 else
2561 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2562 }
2563 }
2564
2565 return Invalid;
2566}
2567
2568namespace {
2569
2570/// A class which looks for a use of a certain level of template
2571/// parameter.
2572struct DependencyChecker : DynamicRecursiveASTVisitor {
2573 unsigned Depth;
2574
2575 // Whether we're looking for a use of a template parameter that makes the
2576 // overall construct type-dependent / a dependent type. This is strictly
2577 // best-effort for now; we may fail to match at all for a dependent type
2578 // in some cases if this is set.
2579 bool IgnoreNonTypeDependent;
2580
2581 bool Match;
2582 SourceLocation MatchLoc;
2583
2584 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2585 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2586 Match(false) {}
2587
2588 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2589 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2590 NamedDecl *ND = Params->getParam(0);
2591 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2592 Depth = PD->getDepth();
2593 } else if (NonTypeTemplateParmDecl *PD =
2594 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2595 Depth = PD->getDepth();
2596 } else {
2597 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2598 }
2599 }
2600
2601 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2602 if (ParmDepth >= Depth) {
2603 Match = true;
2604 MatchLoc = Loc;
2605 return true;
2606 }
2607 return false;
2608 }
2609
2610 bool TraverseStmt(Stmt *S) override {
2611 // Prune out non-type-dependent expressions if requested. This can
2612 // sometimes result in us failing to find a template parameter reference
2613 // (if a value-dependent expression creates a dependent type), but this
2614 // mode is best-effort only.
2615 if (auto *E = dyn_cast_or_null<Expr>(S))
2616 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2617 return true;
2619 }
2620
2621 bool TraverseTypeLoc(TypeLoc TL) override {
2622 if (IgnoreNonTypeDependent && !TL.isNull() &&
2623 !TL.getType()->isDependentType())
2624 return true;
2626 }
2627
2628 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2629 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2630 }
2631
2632 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2633 // For a best-effort search, keep looking until we find a location.
2634 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2635 }
2636
2637 bool TraverseTemplateName(TemplateName N) override {
2638 if (TemplateTemplateParmDecl *PD =
2639 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2640 if (Matches(PD->getDepth()))
2641 return false;
2643 }
2644
2645 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2646 if (NonTypeTemplateParmDecl *PD =
2647 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2648 if (Matches(PD->getDepth(), E->getExprLoc()))
2649 return false;
2650 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2651 }
2652
2653 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2654 return TraverseType(T->getReplacementType());
2655 }
2656
2657 bool VisitSubstTemplateTypeParmPackType(
2658 SubstTemplateTypeParmPackType *T) override {
2659 return TraverseTemplateArgument(T->getArgumentPack());
2660 }
2661
2662 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2663 return TraverseType(T->getInjectedSpecializationType());
2664 }
2665};
2666} // end anonymous namespace
2667
2668/// Determines whether a given type depends on the given parameter
2669/// list.
2670static bool
2672 if (!Params->size())
2673 return false;
2674
2675 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2676 Checker.TraverseType(T);
2677 return Checker.Match;
2678}
2679
2680// Find the source range corresponding to the named type in the given
2681// nested-name-specifier, if any.
2683 QualType T,
2684 const CXXScopeSpec &SS) {
2686 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2687 if (const Type *CurType = NNS->getAsType()) {
2688 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2689 return NNSLoc.getTypeLoc().getSourceRange();
2690 } else
2691 break;
2692
2693 NNSLoc = NNSLoc.getPrefix();
2694 }
2695
2696 return SourceRange();
2697}
2698
2700 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2701 TemplateIdAnnotation *TemplateId,
2702 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2703 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2704 IsMemberSpecialization = false;
2705 Invalid = false;
2706
2707 // The sequence of nested types to which we will match up the template
2708 // parameter lists. We first build this list by starting with the type named
2709 // by the nested-name-specifier and walking out until we run out of types.
2710 SmallVector<QualType, 4> NestedTypes;
2711 QualType T;
2712 if (SS.getScopeRep()) {
2714 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2716 else
2717 T = QualType(SS.getScopeRep()->getAsType(), 0);
2718 }
2719
2720 // If we found an explicit specialization that prevents us from needing
2721 // 'template<>' headers, this will be set to the location of that
2722 // explicit specialization.
2723 SourceLocation ExplicitSpecLoc;
2724
2725 while (!T.isNull()) {
2726 NestedTypes.push_back(T);
2727
2728 // Retrieve the parent of a record type.
2730 // If this type is an explicit specialization, we're done.
2732 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2733 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2734 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2735 ExplicitSpecLoc = Spec->getLocation();
2736 break;
2737 }
2738 } else if (Record->getTemplateSpecializationKind()
2740 ExplicitSpecLoc = Record->getLocation();
2741 break;
2742 }
2743
2744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2746 else
2747 T = QualType();
2748 continue;
2749 }
2750
2751 if (const TemplateSpecializationType *TST
2753 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2754 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2756 else
2757 T = QualType();
2758 continue;
2759 }
2760 }
2761
2762 // Look one step prior in a dependent template specialization type.
2763 if (const DependentTemplateSpecializationType *DependentTST
2765 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2766 T = QualType(NNS->getAsType(), 0);
2767 else
2768 T = QualType();
2769 continue;
2770 }
2771
2772 // Look one step prior in a dependent name type.
2773 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2774 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2775 T = QualType(NNS->getAsType(), 0);
2776 else
2777 T = QualType();
2778 continue;
2779 }
2780
2781 // Retrieve the parent of an enumeration type.
2782 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2783 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2784 // check here.
2785 EnumDecl *Enum = EnumT->getDecl();
2786
2787 // Get to the parent type.
2788 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2790 else
2791 T = QualType();
2792 continue;
2793 }
2794
2795 T = QualType();
2796 }
2797 // Reverse the nested types list, since we want to traverse from the outermost
2798 // to the innermost while checking template-parameter-lists.
2799 std::reverse(NestedTypes.begin(), NestedTypes.end());
2800
2801 // C++0x [temp.expl.spec]p17:
2802 // A member or a member template may be nested within many
2803 // enclosing class templates. In an explicit specialization for
2804 // such a member, the member declaration shall be preceded by a
2805 // template<> for each enclosing class template that is
2806 // explicitly specialized.
2807 bool SawNonEmptyTemplateParameterList = false;
2808
2809 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2810 if (SawNonEmptyTemplateParameterList) {
2811 if (!SuppressDiagnostic)
2812 Diag(DeclLoc, diag::err_specialize_member_of_template)
2813 << !Recovery << Range;
2814 Invalid = true;
2815 IsMemberSpecialization = false;
2816 return true;
2817 }
2818
2819 return false;
2820 };
2821
2822 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2823 // Check that we can have an explicit specialization here.
2824 if (CheckExplicitSpecialization(Range, true))
2825 return true;
2826
2827 // We don't have a template header, but we should.
2828 SourceLocation ExpectedTemplateLoc;
2829 if (!ParamLists.empty())
2830 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2831 else
2832 ExpectedTemplateLoc = DeclStartLoc;
2833
2834 if (!SuppressDiagnostic)
2835 Diag(DeclLoc, diag::err_template_spec_needs_header)
2836 << Range
2837 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2838 return false;
2839 };
2840
2841 unsigned ParamIdx = 0;
2842 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2843 ++TypeIdx) {
2844 T = NestedTypes[TypeIdx];
2845
2846 // Whether we expect a 'template<>' header.
2847 bool NeedEmptyTemplateHeader = false;
2848
2849 // Whether we expect a template header with parameters.
2850 bool NeedNonemptyTemplateHeader = false;
2851
2852 // For a dependent type, the set of template parameters that we
2853 // expect to see.
2854 TemplateParameterList *ExpectedTemplateParams = nullptr;
2855
2856 // C++0x [temp.expl.spec]p15:
2857 // A member or a member template may be nested within many enclosing
2858 // class templates. In an explicit specialization for such a member, the
2859 // member declaration shall be preceded by a template<> for each
2860 // enclosing class template that is explicitly specialized.
2863 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2864 ExpectedTemplateParams = Partial->getTemplateParameters();
2865 NeedNonemptyTemplateHeader = true;
2866 } else if (Record->isDependentType()) {
2867 if (Record->getDescribedClassTemplate()) {
2868 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2869 ->getTemplateParameters();
2870 NeedNonemptyTemplateHeader = true;
2871 }
2872 } else if (ClassTemplateSpecializationDecl *Spec
2873 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2874 // C++0x [temp.expl.spec]p4:
2875 // Members of an explicitly specialized class template are defined
2876 // in the same manner as members of normal classes, and not using
2877 // the template<> syntax.
2878 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2879 NeedEmptyTemplateHeader = true;
2880 else
2881 continue;
2882 } else if (Record->getTemplateSpecializationKind()) {
2883 if (Record->getTemplateSpecializationKind()
2885 TypeIdx == NumTypes - 1)
2886 IsMemberSpecialization = true;
2887
2888 continue;
2889 }
2890 } else if (const TemplateSpecializationType *TST
2892 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2893 ExpectedTemplateParams = Template->getTemplateParameters();
2894 NeedNonemptyTemplateHeader = true;
2895 }
2897 // FIXME: We actually could/should check the template arguments here
2898 // against the corresponding template parameter list.
2899 NeedNonemptyTemplateHeader = false;
2900 }
2901
2902 // C++ [temp.expl.spec]p16:
2903 // In an explicit specialization declaration for a member of a class
2904 // template or a member template that appears in namespace scope, the
2905 // member template and some of its enclosing class templates may remain
2906 // unspecialized, except that the declaration shall not explicitly
2907 // specialize a class member template if its enclosing class templates
2908 // are not explicitly specialized as well.
2909 if (ParamIdx < ParamLists.size()) {
2910 if (ParamLists[ParamIdx]->size() == 0) {
2911 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2912 false))
2913 return nullptr;
2914 } else
2915 SawNonEmptyTemplateParameterList = true;
2916 }
2917
2918 if (NeedEmptyTemplateHeader) {
2919 // If we're on the last of the types, and we need a 'template<>' header
2920 // here, then it's a member specialization.
2921 if (TypeIdx == NumTypes - 1)
2922 IsMemberSpecialization = true;
2923
2924 if (ParamIdx < ParamLists.size()) {
2925 if (ParamLists[ParamIdx]->size() > 0) {
2926 // The header has template parameters when it shouldn't. Complain.
2927 if (!SuppressDiagnostic)
2928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2929 diag::err_template_param_list_matches_nontemplate)
2930 << T
2931 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2932 ParamLists[ParamIdx]->getRAngleLoc())
2934 Invalid = true;
2935 return nullptr;
2936 }
2937
2938 // Consume this template header.
2939 ++ParamIdx;
2940 continue;
2941 }
2942
2943 if (!IsFriend)
2944 if (DiagnoseMissingExplicitSpecialization(
2946 return nullptr;
2947
2948 continue;
2949 }
2950
2951 if (NeedNonemptyTemplateHeader) {
2952 // In friend declarations we can have template-ids which don't
2953 // depend on the corresponding template parameter lists. But
2954 // assume that empty parameter lists are supposed to match this
2955 // template-id.
2956 if (IsFriend && T->isDependentType()) {
2957 if (ParamIdx < ParamLists.size() &&
2959 ExpectedTemplateParams = nullptr;
2960 else
2961 continue;
2962 }
2963
2964 if (ParamIdx < ParamLists.size()) {
2965 // Check the template parameter list, if we can.
2966 if (ExpectedTemplateParams &&
2968 ExpectedTemplateParams,
2969 !SuppressDiagnostic, TPL_TemplateMatch))
2970 Invalid = true;
2971
2972 if (!Invalid &&
2973 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2975 Invalid = true;
2976
2977 ++ParamIdx;
2978 continue;
2979 }
2980
2981 if (!SuppressDiagnostic)
2982 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2983 << T
2985 Invalid = true;
2986 continue;
2987 }
2988 }
2989
2990 // If there were at least as many template-ids as there were template
2991 // parameter lists, then there are no template parameter lists remaining for
2992 // the declaration itself.
2993 if (ParamIdx >= ParamLists.size()) {
2994 if (TemplateId && !IsFriend) {
2995 // We don't have a template header for the declaration itself, but we
2996 // should.
2997 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2998 TemplateId->RAngleLoc));
2999
3000 // Fabricate an empty template parameter list for the invented header.
3002 SourceLocation(), {},
3003 SourceLocation(), nullptr);
3004 }
3005
3006 return nullptr;
3007 }
3008
3009 // If there were too many template parameter lists, complain about that now.
3010 if (ParamIdx < ParamLists.size() - 1) {
3011 bool HasAnyExplicitSpecHeader = false;
3012 bool AllExplicitSpecHeaders = true;
3013 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3014 if (ParamLists[I]->size() == 0)
3015 HasAnyExplicitSpecHeader = true;
3016 else
3017 AllExplicitSpecHeaders = false;
3018 }
3019
3020 if (!SuppressDiagnostic)
3021 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3022 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3023 : diag::err_template_spec_extra_headers)
3024 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3025 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3026
3027 // If there was a specialization somewhere, such that 'template<>' is
3028 // not required, and there were any 'template<>' headers, note where the
3029 // specialization occurred.
3030 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3031 !SuppressDiagnostic)
3032 Diag(ExplicitSpecLoc,
3033 diag::note_explicit_template_spec_does_not_need_header)
3034 << NestedTypes.back();
3035
3036 // We have a template parameter list with no corresponding scope, which
3037 // means that the resulting template declaration can't be instantiated
3038 // properly (we'll end up with dependent nodes when we shouldn't).
3039 if (!AllExplicitSpecHeaders)
3040 Invalid = true;
3041 }
3042
3043 // C++ [temp.expl.spec]p16:
3044 // In an explicit specialization declaration for a member of a class
3045 // template or a member template that ap- pears in namespace scope, the
3046 // member template and some of its enclosing class templates may remain
3047 // unspecialized, except that the declaration shall not explicitly
3048 // specialize a class member template if its en- closing class templates
3049 // are not explicitly specialized as well.
3050 if (ParamLists.back()->size() == 0 &&
3051 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3052 false))
3053 return nullptr;
3054
3055 // Return the last template parameter list, which corresponds to the
3056 // entity being declared.
3057 return ParamLists.back();
3058}
3059
3061 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3062 Diag(Template->getLocation(), diag::note_template_declared_here)
3063 << (isa<FunctionTemplateDecl>(Template)
3064 ? 0
3065 : isa<ClassTemplateDecl>(Template)
3066 ? 1
3067 : isa<VarTemplateDecl>(Template)
3068 ? 2
3069 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3070 << Template->getDeclName();
3071 return;
3072 }
3073
3074 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3075 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3076 IEnd = OST->end();
3077 I != IEnd; ++I)
3078 Diag((*I)->getLocation(), diag::note_template_declared_here)
3079 << 0 << (*I)->getDeclName();
3080
3081 return;
3082 }
3083}
3084
3086 SourceLocation TemplateLoc,
3088 auto lookUpCommonType = [&](TemplateArgument T1,
3089 TemplateArgument T2) -> QualType {
3090 // Don't bother looking for other specializations if both types are
3091 // builtins - users aren't allowed to specialize for them
3092 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3093 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3094
3099 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3100
3101 EnterExpressionEvaluationContext UnevaluatedContext(
3103 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3105
3106 QualType BaseTemplateInst =
3107 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3108
3109 if (SFINAE.hasErrorOccurred())
3110 return QualType();
3111
3112 return BaseTemplateInst;
3113 };
3114
3115 // Note A: For the common_type trait applied to a template parameter pack T of
3116 // types, the member type shall be either defined or not present as follows:
3117 switch (Ts.size()) {
3118
3119 // If sizeof...(T) is zero, there shall be no member type.
3120 case 0:
3121 return QualType();
3122
3123 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3124 // pack T. The member typedef-name type shall denote the same type, if any, as
3125 // common_type_t<T0, T0>; otherwise there shall be no member type.
3126 case 1:
3127 return lookUpCommonType(Ts[0], Ts[0]);
3128
3129 // If sizeof...(T) is two, let the first and second types constituting T be
3130 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3131 // as decay_t<T1> and decay_t<T2>, respectively.
3132 case 2: {
3133 QualType T1 = Ts[0].getAsType();
3134 QualType T2 = Ts[1].getAsType();
3135 QualType D1 = S.BuiltinDecay(T1, {});
3136 QualType D2 = S.BuiltinDecay(T2, {});
3137
3138 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3139 // the same type, if any, as common_type_t<D1, D2>.
3140 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3141 return lookUpCommonType(D1, D2);
3142
3143 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3144 // denotes a valid type, let C denote that type.
3145 {
3146 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3147 EnterExpressionEvaluationContext UnevaluatedContext(
3149 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3151
3152 // false
3154 VK_PRValue);
3155 ExprResult Cond = &CondExpr;
3156
3157 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3158 if (ConstRefQual) {
3159 D1.addConst();
3160 D2.addConst();
3161 }
3162
3163 // declval<D1>()
3164 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3165 ExprResult LHS = &LHSExpr;
3166
3167 // declval<D2>()
3168 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3169 ExprResult RHS = &RHSExpr;
3170
3173
3174 // decltype(false ? declval<D1>() : declval<D2>())
3176 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3177
3178 if (Result.isNull() || SFINAE.hasErrorOccurred())
3179 return QualType();
3180
3181 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3182 return S.BuiltinDecay(Result, TemplateLoc);
3183 };
3184
3185 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3186 return Res;
3187
3188 // Let:
3189 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3190 // COND-RES(X, Y) be
3191 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3192
3193 // C++20 only
3194 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3195 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3196 if (!S.Context.getLangOpts().CPlusPlus20)
3197 return QualType();
3198 return CheckConditionalOperands(true);
3199 }
3200 }
3201
3202 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3203 // denote the first, second, and (pack of) remaining types constituting T. Let
3204 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3205 // a type C, the member typedef-name type shall denote the same type, if any,
3206 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3207 default: {
3208 QualType Result = Ts.front().getAsType();
3209 for (auto T : llvm::drop_begin(Ts)) {
3210 Result = lookUpCommonType(Result, T.getAsType());
3211 if (Result.isNull())
3212 return QualType();
3213 }
3214 return Result;
3215 }
3216 }
3217}
3218
3219static QualType
3222 SourceLocation TemplateLoc,
3223 TemplateArgumentListInfo &TemplateArgs) {
3224 ASTContext &Context = SemaRef.getASTContext();
3225
3226 switch (BTD->getBuiltinTemplateKind()) {
3227 case BTK__make_integer_seq: {
3228 // Specializations of __make_integer_seq<S, T, N> are treated like
3229 // S<T, 0, ..., N-1>.
3230
3231 QualType OrigType = Converted[1].getAsType();
3232 // C++14 [inteseq.intseq]p1:
3233 // T shall be an integer type.
3234 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3235 SemaRef.Diag(TemplateArgs[1].getLocation(),
3236 diag::err_integer_sequence_integral_element_type);
3237 return QualType();
3238 }
3239
3240 TemplateArgument NumArgsArg = Converted[2];
3241 if (NumArgsArg.isDependent())
3243 Converted);
3244
3245 TemplateArgumentListInfo SyntheticTemplateArgs;
3246 // The type argument, wrapped in substitution sugar, gets reused as the
3247 // first template argument in the synthetic template argument list.
3248 SyntheticTemplateArgs.addArgument(
3251 OrigType, TemplateArgs[1].getLocation())));
3252
3253 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3254 // Expand N into 0 ... N-1.
3255 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3256 I < NumArgs; ++I) {
3257 TemplateArgument TA(Context, I, OrigType);
3258 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3259 TA, OrigType, TemplateArgs[2].getLocation()));
3260 }
3261 } else {
3262 // C++14 [inteseq.make]p1:
3263 // If N is negative the program is ill-formed.
3264 SemaRef.Diag(TemplateArgs[2].getLocation(),
3265 diag::err_integer_sequence_negative_length);
3266 return QualType();
3267 }
3268
3269 // The first template argument will be reused as the template decl that
3270 // our synthetic template arguments will be applied to.
3271 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3272 TemplateLoc, SyntheticTemplateArgs);
3273 }
3274
3276 // Specializations of
3277 // __type_pack_element<Index, T_1, ..., T_N>
3278 // are treated like T_Index.
3279 assert(Converted.size() == 2 &&
3280 "__type_pack_element should be given an index and a parameter pack");
3281
3282 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3283 if (IndexArg.isDependent() || Ts.isDependent())
3285 Converted);
3286
3287 llvm::APSInt Index = IndexArg.getAsIntegral();
3288 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3289 "type std::size_t, and hence be non-negative");
3290 // If the Index is out of bounds, the program is ill-formed.
3291 if (Index >= Ts.pack_size()) {
3292 SemaRef.Diag(TemplateArgs[0].getLocation(),
3293 diag::err_type_pack_element_out_of_bounds);
3294 return QualType();
3295 }
3296
3297 // We simply return the type at index `Index`.
3298 int64_t N = Index.getExtValue();
3299 return Ts.getPackAsArray()[N].getAsType();
3300 }
3301
3303 assert(Converted.size() == 4);
3304 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3306 Converted);
3307
3308 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3309 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3310 QualType HasNoTypeMember = Converted[2].getAsType();
3311 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3312 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3313 !CT.isNull()) {
3317 CT, TemplateArgs[1].getLocation())));
3318
3319 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3320 }
3321 return HasNoTypeMember;
3322 }
3323 }
3324 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3325}
3326
3327/// Determine whether this alias template is "enable_if_t".
3328/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3330 return AliasTemplate->getName() == "enable_if_t" ||
3331 AliasTemplate->getName() == "__enable_if_t";
3332}
3333
3334/// Collect all of the separable terms in the given condition, which
3335/// might be a conjunction.
3336///
3337/// FIXME: The right answer is to convert the logical expression into
3338/// disjunctive normal form, so we can find the first failed term
3339/// within each possible clause.
3340static void collectConjunctionTerms(Expr *Clause,
3341 SmallVectorImpl<Expr *> &Terms) {
3342 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3343 if (BinOp->getOpcode() == BO_LAnd) {
3344 collectConjunctionTerms(BinOp->getLHS(), Terms);
3345 collectConjunctionTerms(BinOp->getRHS(), Terms);
3346 return;
3347 }
3348 }
3349
3350 Terms.push_back(Clause);
3351}
3352
3353// The ranges-v3 library uses an odd pattern of a top-level "||" with
3354// a left-hand side that is value-dependent but never true. Identify
3355// the idiom and ignore that term.
3357 // Top-level '||'.
3358 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3359 if (!BinOp) return Cond;
3360
3361 if (BinOp->getOpcode() != BO_LOr) return Cond;
3362
3363 // With an inner '==' that has a literal on the right-hand side.
3364 Expr *LHS = BinOp->getLHS();
3365 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3366 if (!InnerBinOp) return Cond;
3367
3368 if (InnerBinOp->getOpcode() != BO_EQ ||
3369 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3370 return Cond;
3371
3372 // If the inner binary operation came from a macro expansion named
3373 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3374 // of the '||', which is the real, user-provided condition.
3375 SourceLocation Loc = InnerBinOp->getExprLoc();
3376 if (!Loc.isMacroID()) return Cond;
3377
3378 StringRef MacroName = PP.getImmediateMacroName(Loc);
3379 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3380 return BinOp->getRHS();
3381
3382 return Cond;
3383}
3384
3385namespace {
3386
3387// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3388// within failing boolean expression, such as substituting template parameters
3389// for actual types.
3390class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3391public:
3392 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3393 : Policy(P) {}
3394
3395 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3396 const auto *DR = dyn_cast<DeclRefExpr>(E);
3397 if (DR && DR->getQualifier()) {
3398 // If this is a qualified name, expand the template arguments in nested
3399 // qualifiers.
3400 DR->getQualifier()->print(OS, Policy, true);
3401 // Then print the decl itself.
3402 const ValueDecl *VD = DR->getDecl();
3403 OS << VD->getName();
3404 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3405 // This is a template variable, print the expanded template arguments.
3407 OS, IV->getTemplateArgs().asArray(), Policy,
3408 IV->getSpecializedTemplate()->getTemplateParameters());
3409 }
3410 return true;
3411 }
3412 return false;
3413 }
3414
3415private:
3416 const PrintingPolicy Policy;
3417};
3418
3419} // end anonymous namespace
3420
3421std::pair<Expr *, std::string>
3423 Cond = lookThroughRangesV3Condition(PP, Cond);
3424
3425 // Separate out all of the terms in a conjunction.
3427 collectConjunctionTerms(Cond, Terms);
3428
3429 // Determine which term failed.
3430 Expr *FailedCond = nullptr;
3431 for (Expr *Term : Terms) {
3432 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3433
3434 // Literals are uninteresting.
3435 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3436 isa<IntegerLiteral>(TermAsWritten))
3437 continue;
3438
3439 // The initialization of the parameter from the argument is
3440 // a constant-evaluated context.
3443
3444 bool Succeeded;
3445 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3446 !Succeeded) {
3447 FailedCond = TermAsWritten;
3448 break;
3449 }
3450 }
3451 if (!FailedCond)
3452 FailedCond = Cond->IgnoreParenImpCasts();
3453
3454 std::string Description;
3455 {
3456 llvm::raw_string_ostream Out(Description);
3458 Policy.PrintCanonicalTypes = true;
3459 FailedBooleanConditionPrinterHelper Helper(Policy);
3460 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3461 }
3462 return { FailedCond, Description };
3463}
3464
3466 SourceLocation TemplateLoc,
3467 TemplateArgumentListInfo &TemplateArgs) {
3469 Name.getUnderlying().getAsDependentTemplateName();
3470 if (DTN && DTN->isIdentifier())
3471 // When building a template-id where the template-name is dependent,
3472 // assume the template is a type template. Either our assumption is
3473 // correct, or the code is ill-formed and will be diagnosed when the
3474 // dependent name is substituted.
3477 TemplateArgs.arguments());
3478
3479 if (Name.getAsAssumedTemplateName() &&
3480 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3481 return QualType();
3482
3483 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3484
3485 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3486 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3487 // We might have a substituted template template parameter pack. If so,
3488 // build a template specialization type for it.
3489 if (Name.getAsSubstTemplateTemplateParmPack())
3491 TemplateArgs.arguments());
3492
3493 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3494 << Name;
3496 return QualType();
3497 }
3498
3499 // Check that the template argument list is well-formed for this
3500 // template.
3501 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3502 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3503 DefaultArgs, false, SugaredConverted,
3504 CanonicalConverted,
3505 /*UpdateArgsWithConversions=*/true))
3506 return QualType();
3507
3508 QualType CanonType;
3509
3511 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3512
3513 // Find the canonical type for this type alias template specialization.
3514 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3515 if (Pattern->isInvalidDecl())
3516 return QualType();
3517
3518 // Only substitute for the innermost template argument list. NOTE: Some
3519 // external resugarers rely on leaving a Subst* node here. Make the
3520 // substitution non-final in that case. Note that these external resugarers
3521 // will still miss some information in this representation, because we don't
3522 // provide enough context in the Subst* nodes in order to tell different
3523 // template type alias specializations apart.
3524 MultiLevelTemplateArgumentList TemplateArgLists;
3525 TemplateArgLists.addOuterTemplateArguments(
3526 Template, SugaredConverted,
3527 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3528 TemplateArgLists.addOuterRetainedLevels(
3529 AliasTemplate->getTemplateParameters()->getDepth());
3530
3533 *this, /*PointOfInstantiation=*/TemplateLoc,
3534 /*Entity=*/AliasTemplate,
3535 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3536
3537 // Diagnose uses of this alias.
3538 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3539
3540 if (Inst.isInvalid())
3541 return QualType();
3542
3543 std::optional<ContextRAII> SavedContext;
3544 if (!AliasTemplate->getDeclContext()->isFileContext())
3545 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3546
3547 CanonType =
3548 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3549 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3550 if (CanonType.isNull()) {
3551 // If this was enable_if and we failed to find the nested type
3552 // within enable_if in a SFINAE context, dig out the specific
3553 // enable_if condition that failed and present that instead.
3555 if (auto DeductionInfo = isSFINAEContext()) {
3556 if (*DeductionInfo &&
3557 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3558 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3559 diag::err_typename_nested_not_found_enable_if &&
3560 TemplateArgs[0].getArgument().getKind()
3562 Expr *FailedCond;
3563 std::string FailedDescription;
3564 std::tie(FailedCond, FailedDescription) =
3565 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3566
3567 // Remove the old SFINAE diagnostic.
3568 PartialDiagnosticAt OldDiag =
3570 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3571
3572 // Add a new SFINAE diagnostic specifying which condition
3573 // failed.
3574 (*DeductionInfo)->addSFINAEDiagnostic(
3575 OldDiag.first,
3576 PDiag(diag::err_typename_nested_not_found_requirement)
3577 << FailedDescription
3578 << FailedCond->getSourceRange());
3579 }
3580 }
3581 }
3582
3583 return QualType();
3584 }
3585 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3586 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3587 TemplateLoc, TemplateArgs);
3588 } else if (Name.isDependent() ||
3590 TemplateArgs, CanonicalConverted)) {
3591 // This class template specialization is a dependent
3592 // type. Therefore, its canonical type is another class template
3593 // specialization type that contains all of the converted
3594 // arguments in canonical form. This ensures that, e.g., A<T> and
3595 // A<T, T> have identical types when A is declared as:
3596 //
3597 // template<typename T, typename U = T> struct A;
3599 Name, CanonicalConverted);
3600
3601 // This might work out to be a current instantiation, in which
3602 // case the canonical type needs to be the InjectedClassNameType.
3603 //
3604 // TODO: in theory this could be a simple hashtable lookup; most
3605 // changes to CurContext don't change the set of current
3606 // instantiations.
3607 if (isa<ClassTemplateDecl>(Template)) {
3608 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3609 // If we get out to a namespace, we're done.
3610 if (Ctx->isFileContext()) break;
3611
3612 // If this isn't a record, keep looking.
3613 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3614 if (!Record) continue;
3615
3616 // Look for one of the two cases with InjectedClassNameTypes
3617 // and check whether it's the same template.
3618 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3619 !Record->getDescribedClassTemplate())
3620 continue;
3621
3622 // Fetch the injected class name type and check whether its
3623 // injected type is equal to the type we just built.
3625 QualType Injected = cast<InjectedClassNameType>(ICNT)
3626 ->getInjectedSpecializationType();
3627
3628 if (CanonType != Injected->getCanonicalTypeInternal())
3629 continue;
3630
3631 // If so, the canonical type of this TST is the injected
3632 // class name type of the record we just found.
3633 assert(ICNT.isCanonical());
3634 CanonType = ICNT;
3635 break;
3636 }
3637 }
3638 } else if (ClassTemplateDecl *ClassTemplate =
3639 dyn_cast<ClassTemplateDecl>(Template)) {
3640 // Find the class template specialization declaration that
3641 // corresponds to these arguments.
3642 void *InsertPos = nullptr;
3644 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3645 if (!Decl) {
3646 // This is the first time we have referenced this class template
3647 // specialization. Create the canonical declaration and add it to
3648 // the set of specializations.
3650 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3651 ClassTemplate->getDeclContext(),
3652 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3653 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3654 nullptr);
3655 ClassTemplate->AddSpecialization(Decl, InsertPos);
3656 if (ClassTemplate->isOutOfLine())
3657 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3658 }
3659
3660 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3661 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3662 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3663 if (!Inst.isInvalid()) {
3664 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3665 CanonicalConverted,
3666 /*Final=*/false);
3667 InstantiateAttrsForDecl(TemplateArgLists,
3668 ClassTemplate->getTemplatedDecl(), Decl);
3669 }
3670 }
3671
3672 // Diagnose uses of this specialization.
3673 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3674
3675 CanonType = Context.getTypeDeclType(Decl);
3676 assert(isa<RecordType>(CanonType) &&
3677 "type of non-dependent specialization is not a RecordType");
3678 } else {
3679 llvm_unreachable("Unhandled template kind");
3680 }
3681
3682 // Build the fully-sugared type for this class template
3683 // specialization, which refers back to the class template
3684 // specialization we created or found.
3685 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3686 CanonType);
3687}
3688
3690 TemplateNameKind &TNK,
3691 SourceLocation NameLoc,
3692 IdentifierInfo *&II) {
3693 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3694
3695 TemplateName Name = ParsedName.get();
3696 auto *ATN = Name.getAsAssumedTemplateName();
3697 assert(ATN && "not an assumed template name");
3698 II = ATN->getDeclName().getAsIdentifierInfo();
3699
3700 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3701 // Resolved to a type template name.
3702 ParsedName = TemplateTy::make(Name);
3703 TNK = TNK_Type_template;
3704 }
3705}
3706
3708 SourceLocation NameLoc,
3709 bool Diagnose) {
3710 // We assumed this undeclared identifier to be an (ADL-only) function
3711 // template name, but it was used in a context where a type was required.
3712 // Try to typo-correct it now.
3713 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3714 assert(ATN && "not an assumed template name");
3715
3716 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3717 struct CandidateCallback : CorrectionCandidateCallback {
3718 bool ValidateCandidate(const TypoCorrection &TC) override {
3719 return TC.getCorrectionDecl() &&
3721 }
3722 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3723 return std::make_unique<CandidateCallback>(*this);
3724 }
3725 } FilterCCC;
3726
3727 TypoCorrection Corrected =
3728 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3729 FilterCCC, CTK_ErrorRecovery);
3730 if (Corrected && Corrected.getFoundDecl()) {
3731 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3732 << ATN->getDeclName());
3734 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3736 return false;
3737 }
3738
3739 if (Diagnose)
3740 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3741 return true;
3742}
3743
3745 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3746 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3747 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3748 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3749 bool IsCtorOrDtorName, bool IsClassName,
3750 ImplicitTypenameContext AllowImplicitTypename) {
3751 if (SS.isInvalid())
3752 return true;
3753
3754 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3755 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3756
3757 // C++ [temp.res]p3:
3758 // A qualified-id that refers to a type and in which the
3759 // nested-name-specifier depends on a template-parameter (14.6.2)
3760 // shall be prefixed by the keyword typename to indicate that the
3761 // qualified-id denotes a type, forming an
3762 // elaborated-type-specifier (7.1.5.3).
3763 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3764 // C++2a relaxes some of those restrictions in [temp.res]p5.
3765 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3767 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3768 else
3769 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3770 << SS.getScopeRep() << TemplateII->getName()
3771 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3772 } else
3773 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3774 << SS.getScopeRep() << TemplateII->getName();
3775
3776 // FIXME: This is not quite correct recovery as we don't transform SS
3777 // into the corresponding dependent form (and we don't diagnose missing
3778 // 'template' keywords within SS as a result).
3779 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3780 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3781 TemplateArgsIn, RAngleLoc);
3782 }
3783
3784 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3785 // it's not actually allowed to be used as a type in most cases. Because
3786 // we annotate it before we know whether it's valid, we have to check for
3787 // this case here.
3788 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3789 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3790 Diag(TemplateIILoc,
3791 TemplateKWLoc.isInvalid()
3792 ? diag::err_out_of_line_qualified_id_type_names_constructor
3793 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3794 << TemplateII << 0 /*injected-class-name used as template name*/
3795 << 1 /*if any keyword was present, it was 'template'*/;
3796 }
3797 }
3798
3799 TemplateName Template = TemplateD.get();
3800 if (Template.getAsAssumedTemplateName() &&
3801 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3802 return true;
3803
3804 // Translate the parser's template argument list in our AST format.
3805 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3806 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3807
3808 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3809 assert(SS.getScopeRep() == DTN->getQualifier());
3811 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3812 TemplateArgs.arguments());
3813 // Build type-source information.
3814 TypeLocBuilder TLB;
3819 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3820 SpecTL.setTemplateNameLoc(TemplateIILoc);
3821 SpecTL.setLAngleLoc(LAngleLoc);
3822 SpecTL.setRAngleLoc(RAngleLoc);
3823 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3824 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3826 }
3827
3828 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3829 if (SpecTy.isNull())
3830 return true;
3831
3832 // Build type-source information.
3833 TypeLocBuilder TLB;
3836 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3837 SpecTL.setTemplateNameLoc(TemplateIILoc);
3838 SpecTL.setLAngleLoc(LAngleLoc);
3839 SpecTL.setRAngleLoc(RAngleLoc);
3840 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3841 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3842
3843 // Create an elaborated-type-specifier containing the nested-name-specifier.
3844 QualType ElTy =
3846 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3847 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3849 if (!ElabTL.isEmpty())
3851 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3852}
3853
3855 TypeSpecifierType TagSpec,
3856 SourceLocation TagLoc,
3857 CXXScopeSpec &SS,
3858 SourceLocation TemplateKWLoc,
3859 TemplateTy TemplateD,
3860 SourceLocation TemplateLoc,
3861 SourceLocation LAngleLoc,
3862 ASTTemplateArgsPtr TemplateArgsIn,
3863 SourceLocation RAngleLoc) {
3864 if (SS.isInvalid())
3865 return TypeResult(true);
3866
3867 TemplateName Template = TemplateD.get();
3868
3869 // Translate the parser's template argument list in our AST format.
3870 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3871 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3872
3873 // Determine the tag kind
3875 ElaboratedTypeKeyword Keyword
3877
3878 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3879 assert(SS.getScopeRep() == DTN->getQualifier());
3881 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3882 TemplateArgs.arguments());
3883
3884 // Build type-source information.
3885 TypeLocBuilder TLB;
3888 SpecTL.setElaboratedKeywordLoc(TagLoc);
3890 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3891 SpecTL.setTemplateNameLoc(TemplateLoc);
3892 SpecTL.setLAngleLoc(LAngleLoc);
3893 SpecTL.setRAngleLoc(RAngleLoc);
3894 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3895 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3897 }
3898
3899 if (TypeAliasTemplateDecl *TAT =
3900 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3901 // C++0x [dcl.type.elab]p2:
3902 // If the identifier resolves to a typedef-name or the simple-template-id
3903 // resolves to an alias template specialization, the
3904 // elaborated-type-specifier is ill-formed.
3905 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3906 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3907 Diag(TAT->getLocation(), diag::note_declared_at);
3908 }
3909
3910 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3911 if (Result.isNull())
3912 return TypeResult(true);
3913
3914 // Check the tag kind
3915 if (const RecordType *RT = Result->getAs<RecordType>()) {
3916 RecordDecl *D = RT->getDecl();
3917
3918 IdentifierInfo *Id = D->getIdentifier();
3919 assert(Id && "templated class must have an identifier");
3920
3922 TagLoc, Id)) {
3923 Diag(TagLoc, diag::err_use_with_wrong_tag)
3924 << Result
3925 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3926 Diag(D->getLocation(), diag::note_previous_use);
3927 }
3928 }
3929
3930 // Provide source-location information for the template specialization.
3931 TypeLocBuilder TLB;
3934 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3935 SpecTL.setTemplateNameLoc(TemplateLoc);
3936 SpecTL.setLAngleLoc(LAngleLoc);
3937 SpecTL.setRAngleLoc(RAngleLoc);
3938 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3939 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3940
3941 // Construct an elaborated type containing the nested-name-specifier (if any)
3942 // and tag keyword.
3945 ElabTL.setElaboratedKeywordLoc(TagLoc);
3948}
3949
3950static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3951 NamedDecl *PrevDecl,
3954
3956
3958 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3959 switch (Arg.getKind()) {
3967 return false;
3968
3970 QualType Type = Arg.getAsType();
3971 const TemplateTypeParmType *TPT =
3973 return TPT && !Type.hasQualifiers() &&
3974 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3975 }
3976
3978 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3979 if (!DRE || !DRE->getDecl())
3980 return false;
3981 const NonTypeTemplateParmDecl *NTTP =
3982 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3983 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3984 }
3985
3987 const TemplateTemplateParmDecl *TTP =
3988 dyn_cast_or_null<TemplateTemplateParmDecl>(
3990 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3991 }
3992 llvm_unreachable("unexpected kind of template argument");
3993}
3994
3997 if (Params->size() != Args.size())
3998 return false;
3999
4000 unsigned Depth = Params->getDepth();
4001
4002 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4003 TemplateArgument Arg = Args[I];
4004
4005 // If the parameter is a pack expansion, the argument must be a pack
4006 // whose only element is a pack expansion.
4007 if (Params->getParam(I)->isParameterPack()) {
4008 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4009 !Arg.pack_begin()->isPackExpansion())
4010 return false;
4011 Arg = Arg.pack_begin()->getPackExpansionPattern();
4012 }
4013
4014 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4015 return false;
4016 }
4017
4018 return true;
4019}
4020
4021template<typename PartialSpecDecl>
4022static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4023 if (Partial->getDeclContext()->isDependentContext())
4024 return;
4025
4026 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4027 // for non-substitution-failure issues?
4028 TemplateDeductionInfo Info(Partial->getLocation());
4029 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4030 return;
4031
4032 auto *Template = Partial->getSpecializedTemplate();
4033 S.Diag(Partial->getLocation(),
4034 diag::ext_partial_spec_not_more_specialized_than_primary)
4035 << isa<VarTemplateDecl>(Template);
4036
4037 if (Info.hasSFINAEDiagnostic()) {
4041 SmallString<128> SFINAEArgString;
4042 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4043 S.Diag(Diag.first,
4044 diag::note_partial_spec_not_more_specialized_than_primary)
4045 << SFINAEArgString;
4046 }
4047
4048 S.NoteTemplateLocation(*Template);
4049 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4050 Template->getAssociatedConstraints(TemplateAC);
4051 Partial->getAssociatedConstraints(PartialAC);
4052 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4053 TemplateAC);
4054}
4055
4056static void
4058 const llvm::SmallBitVector &DeducibleParams) {
4059 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4060 if (!DeducibleParams[I]) {
4061 NamedDecl *Param = TemplateParams->getParam(I);
4062 if (Param->getDeclName())
4063 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4064 << Param->getDeclName();
4065 else
4066 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4067 << "(anonymous)";
4068 }
4069 }
4070}
4071
4072
4073template<typename PartialSpecDecl>
4075 PartialSpecDecl *Partial) {
4076 // C++1z [temp.class.spec]p8: (DR1495)
4077 // - The specialization shall be more specialized than the primary
4078 // template (14.5.5.2).
4080
4081 // C++ [temp.class.spec]p8: (DR1315)
4082 // - Each template-parameter shall appear at least once in the
4083 // template-id outside a non-deduced context.
4084 // C++1z [temp.class.spec.match]p3 (P0127R2)
4085 // If the template arguments of a partial specialization cannot be
4086 // deduced because of the structure of its template-parameter-list
4087 // and the template-id, the program is ill-formed.
4088 auto *TemplateParams = Partial->getTemplateParameters();
4089 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4090 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4091 TemplateParams->getDepth(), DeducibleParams);
4092
4093 if (!DeducibleParams.all()) {
4094 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4095 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4096 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4097 << (NumNonDeducible > 1)
4098 << SourceRange(Partial->getLocation(),
4099 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4100 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4101 }
4102}
4103
4106 checkTemplatePartialSpecialization(*this, Partial);
4107}
4108
4111 checkTemplatePartialSpecialization(*this, Partial);
4112}
4113
4115 // C++1z [temp.param]p11:
4116 // A template parameter of a deduction guide template that does not have a
4117 // default-argument shall be deducible from the parameter-type-list of the
4118 // deduction guide template.
4119 auto *TemplateParams = TD->getTemplateParameters();
4120 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4121 MarkDeducedTemplateParameters(TD, DeducibleParams);
4122 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4123 // A parameter pack is deducible (to an empty pack).
4124 auto *Param = TemplateParams->getParam(I);
4125 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4126 DeducibleParams[I] = true;
4127 }
4128
4129 if (!DeducibleParams.all()) {
4130 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4131 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4132 << (NumNonDeducible > 1);
4133 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4134 }
4135}
4136
4139 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4141 // D must be variable template id.
4142 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4143 "Variable template specialization is declared with a template id.");
4144
4145 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4146 TemplateArgumentListInfo TemplateArgs =
4147 makeTemplateArgumentListInfo(*this, *TemplateId);
4148 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4149 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4150 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4151
4152 TemplateName Name = TemplateId->Template.get();
4153
4154 // The template-id must name a variable template.
4156 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4157 if (!VarTemplate) {
4158 NamedDecl *FnTemplate;
4159 if (auto *OTS = Name.getAsOverloadedTemplate())
4160 FnTemplate = *OTS->begin();
4161 else
4162 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4163 if (FnTemplate)
4164 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4165 << FnTemplate->getDeclName();
4166 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4168 }
4169
4170 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4171 auto Message = DSA->getMessage();
4172 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4173 << VarTemplate << !Message.empty() << Message;
4174 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4175 }
4176
4177 // Check for unexpanded parameter packs in any of the template arguments.
4178 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4179 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4183 return true;
4184
4185 // Check that the template argument list is well-formed for this
4186 // template.
4187 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4188 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4189 /*DefaultArgs=*/{}, false, SugaredConverted,
4190 CanonicalConverted,
4191 /*UpdateArgsWithConversions=*/true))
4192 return true;
4193
4194 // Find the variable template (partial) specialization declaration that
4195 // corresponds to these arguments.
4198 TemplateArgs.size(),
4199 CanonicalConverted))
4200 return true;
4201
4202 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4203 // also do them during instantiation.
4204 if (!Name.isDependent() &&
4206 TemplateArgs, CanonicalConverted)) {
4207 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4208 << VarTemplate->getDeclName();
4210 }
4211
4212 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4213 CanonicalConverted) &&
4214 (!Context.getLangOpts().CPlusPlus20 ||
4215 !TemplateParams->hasAssociatedConstraints())) {
4216 // C++ [temp.class.spec]p9b3:
4217 //
4218 // -- The argument list of the specialization shall not be identical
4219 // to the implicit argument list of the primary template.
4220 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4221 << /*variable template*/ 1
4222 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4223 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4224 // FIXME: Recover from this by treating the declaration as a redeclaration
4225 // of the primary template.
4226 return true;
4227 }
4228 }
4229
4230 void *InsertPos = nullptr;
4231 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4232
4234 PrevDecl = VarTemplate->findPartialSpecialization(
4235 CanonicalConverted, TemplateParams, InsertPos);
4236 else
4237 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4238
4240
4241 // Check whether we can declare a variable template specialization in
4242 // the current scope.
4243 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4244 TemplateNameLoc,
4246 return true;
4247
4248 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4249 // Since the only prior variable template specialization with these
4250 // arguments was referenced but not declared, reuse that
4251 // declaration node as our own, updating its source location and
4252 // the list of outer template parameters to reflect our new declaration.
4253 Specialization = PrevDecl;
4254 Specialization->setLocation(TemplateNameLoc);
4255 PrevDecl = nullptr;
4256 } else if (IsPartialSpecialization) {
4257 // Create a new class template partial specialization declaration node.
4259 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4262 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4263 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4264 CanonicalConverted);
4265 Partial->setTemplateArgsAsWritten(TemplateArgs);
4266
4267 if (!PrevPartial)
4268 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4269 Specialization = Partial;
4270
4271 // If we are providing an explicit specialization of a member variable
4272 // template specialization, make a note of that.
4273 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4274 PrevPartial->setMemberSpecialization();
4275
4277 } else {
4278 // Create a new class template specialization declaration node for
4279 // this explicit specialization or friend declaration.
4281 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4282 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4283 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4284
4285 if (!PrevDecl)
4286 VarTemplate->AddSpecialization(Specialization, InsertPos);
4287 }
4288
4289 // C++ [temp.expl.spec]p6:
4290 // If a template, a member template or the member of a class template is
4291 // explicitly specialized then that specialization shall be declared
4292 // before the first use of that specialization that would cause an implicit
4293 // instantiation to take place, in every translation unit in which such a
4294 // use occurs; no diagnostic is required.
4295 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4296 bool Okay = false;
4297 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4298 // Is there any previous explicit specialization declaration?
4300 Okay = true;
4301 break;
4302 }
4303 }
4304
4305 if (!Okay) {
4306 SourceRange Range(TemplateNameLoc, RAngleLoc);
4307 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4308 << Name << Range;
4309
4310 Diag(PrevDecl->getPointOfInstantiation(),
4311 diag::note_instantiation_required_here)
4312 << (PrevDecl->getTemplateSpecializationKind() !=
4314 return true;
4315 }
4316 }
4317
4318 Specialization->setLexicalDeclContext(CurContext);
4319
4320 // Add the specialization into its lexical context, so that it can
4321 // be seen when iterating through the list of declarations in that
4322 // context. However, specializations are not found by name lookup.
4324
4325 // Note that this is an explicit specialization.
4326 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4327
4328 Previous.clear();
4329 if (PrevDecl)
4330 Previous.addDecl(PrevDecl);
4331 else if (Specialization->isStaticDataMember() &&
4332 Specialization->isOutOfLine())
4333 Specialization->setAccess(VarTemplate->getAccess());
4334
4335 return Specialization;
4336}
4337
4338namespace {
4339/// A partial specialization whose template arguments have matched
4340/// a given template-id.
4341struct PartialSpecMatchResult {
4344};
4345} // end anonymous namespace
4346
4349 SourceLocation TemplateNameLoc,
4350 const TemplateArgumentListInfo &TemplateArgs) {
4351 assert(Template && "A variable template id without template?");
4352
4353 // Check that the template argument list is well-formed for this template.
4354 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4356 Template, TemplateNameLoc,
4357 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4358 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4359 /*UpdateArgsWithConversions=*/true))
4360 return true;
4361
4362 // Produce a placeholder value if the specialization is dependent.
4363 if (Template->getDeclContext()->isDependentContext() ||
4365 TemplateArgs, CanonicalConverted))
4366 return DeclResult();
4367
4368 // Find the variable template specialization declaration that
4369 // corresponds to these arguments.
4370 void *InsertPos = nullptr;
4372 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4373 checkSpecializationReachability(TemplateNameLoc, Spec);
4374 // If we already have a variable template specialization, return it.
4375 return Spec;
4376 }
4377
4378 // This is the first time we have referenced this variable template
4379 // specialization. Create the canonical declaration and add it to
4380 // the set of specializations, based on the closest partial specialization
4381 // that it represents. That is,
4382 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4383 const TemplateArgumentList *PartialSpecArgs = nullptr;
4384 bool AmbiguousPartialSpec = false;
4385 typedef PartialSpecMatchResult MatchResult;
4387 SourceLocation PointOfInstantiation = TemplateNameLoc;
4388 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4389 /*ForTakingAddress=*/false);
4390
4391 // 1. Attempt to find the closest partial specialization that this
4392 // specializes, if any.
4393 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4394 // Perhaps better after unification of DeduceTemplateArguments() and
4395 // getMoreSpecializedPartialSpecialization().
4397 Template->getPartialSpecializations(PartialSpecs);
4398
4399 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4400 // C++ [temp.spec.partial.member]p2:
4401 // If the primary member template is explicitly specialized for a given
4402 // (implicit) specialization of the enclosing class template, the partial
4403 // specializations of the member template are ignored for this
4404 // specialization of the enclosing class template. If a partial
4405 // specialization of the member template is explicitly specialized for a
4406 // given (implicit) specialization of the enclosing class template, the
4407 // primary member template and its other partial specializations are still
4408 // considered for this specialization of the enclosing class template.
4409 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4410 !Partial->getMostRecentDecl()->isMemberSpecialization())
4411 continue;
4412
4413 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4414
4416 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4418 // Store the failed-deduction information for use in diagnostics, later.
4419 // TODO: Actually use the failed-deduction info?
4420 FailedCandidates.addCandidate().set(
4421 DeclAccessPair::make(Template, AS_public), Partial,
4423 (void)Result;
4424 } else {
4425 Matched.push_back(PartialSpecMatchResult());
4426 Matched.back().Partial = Partial;
4427 Matched.back().Args = Info.takeSugared();
4428 }
4429 }
4430
4431 if (Matched.size() >= 1) {
4432 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4433 if (Matched.size() == 1) {
4434 // -- If exactly one matching specialization is found, the
4435 // instantiation is generated from that specialization.
4436 // We don't need to do anything for this.
4437 } else {
4438 // -- If more than one matching specialization is found, the
4439 // partial order rules (14.5.4.2) are used to determine
4440 // whether one of the specializations is more specialized
4441 // than the others. If none of the specializations is more
4442 // specialized than all of the other matching
4443 // specializations, then the use of the variable template is
4444 // ambiguous and the program is ill-formed.
4446 PEnd = Matched.end();
4447 P != PEnd; ++P) {
4448 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4449 PointOfInstantiation) ==
4450 P->Partial)
4451 Best = P;
4452 }
4453
4454 // Determine if the best partial specialization is more specialized than
4455 // the others.
4456 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4457 PEnd = Matched.end();
4458 P != PEnd; ++P) {
4460 P->Partial, Best->Partial,
4461 PointOfInstantiation) != Best->Partial) {
4462 AmbiguousPartialSpec = true;
4463 break;
4464 }
4465 }
4466 }
4467
4468 // Instantiate using the best variable template partial specialization.
4469 InstantiationPattern = Best->Partial;
4470 PartialSpecArgs = Best->Args;
4471 } else {
4472 // -- If no match is found, the instantiation is generated
4473 // from the primary template.
4474 // InstantiationPattern = Template->getTemplatedDecl();
4475 }
4476
4477 // 2. Create the canonical declaration.
4478 // Note that we do not instantiate a definition until we see an odr-use
4479 // in DoMarkVarDeclReferenced().
4480 // FIXME: LateAttrs et al.?
4482 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4483 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4484 if (!Decl)
4485 return true;
4486
4487 if (AmbiguousPartialSpec) {
4488 // Partial ordering did not produce a clear winner. Complain.
4490 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4491 << Decl;
4492
4493 // Print the matching partial specializations.
4494 for (MatchResult P : Matched)
4495 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4496 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4497 *P.Args);
4498 return true;
4499 }
4500
4502 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4503 Decl->setInstantiationOf(D, PartialSpecArgs);
4504
4505 checkSpecializationReachability(TemplateNameLoc, Decl);
4506
4507 assert(Decl && "No variable template specialization?");
4508 return Decl;
4509}
4510
4512 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4513 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4514 const TemplateArgumentListInfo *TemplateArgs) {
4515
4516 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4517 *TemplateArgs);
4518 if (Decl.isInvalid())
4519 return ExprError();
4520
4521 if (!Decl.get())
4522 return ExprResult();
4523
4524 VarDecl *Var = cast<VarDecl>(Decl.get());
4527 NameInfo.getLoc());
4528
4529 // Build an ordinary singleton decl ref.
4530 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4531}
4532
4535 Diag(Loc, diag::err_template_missing_args)
4536 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4537 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4538 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4539 }
4540}
4541
4543 bool TemplateKeyword,
4544 TemplateDecl *TD,
4547 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4549}
4550
4553 SourceLocation TemplateKWLoc,
4554 const DeclarationNameInfo &ConceptNameInfo,
4555 NamedDecl *FoundDecl,
4556 ConceptDecl *NamedConcept,
4557 const TemplateArgumentListInfo *TemplateArgs) {
4558 assert(NamedConcept && "A concept template id without a template?");
4559
4560 if (NamedConcept->isInvalidDecl())
4561 return ExprError();
4562
4563 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4565 NamedConcept, ConceptNameInfo.getLoc(),
4566 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4567 /*DefaultArgs=*/{},
4568 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4569 /*UpdateArgsWithConversions=*/false))
4570 return ExprError();
4571
4572 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4573
4575 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4576 CanonicalConverted);
4577 ConstraintSatisfaction Satisfaction;
4578 bool AreArgsDependent =
4580 *TemplateArgs, CanonicalConverted);
4581 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4582 /*Final=*/false);
4584
4587
4588 if (!AreArgsDependent &&
4590 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4591 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4592 TemplateArgs->getRAngleLoc()),
4593 Satisfaction))
4594 return ExprError();
4595 auto *CL = ConceptReference::Create(
4596 Context,
4598 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4601 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4602}
4603
4605 SourceLocation TemplateKWLoc,
4606 LookupResult &R,
4607 bool RequiresADL,
4608 const TemplateArgumentListInfo *TemplateArgs) {
4609 // FIXME: Can we do any checking at this point? I guess we could check the
4610 // template arguments that we have against the template name, if the template
4611 // name refers to a single template. That's not a terribly common case,
4612 // though.
4613 // foo<int> could identify a single function unambiguously
4614 // This approach does NOT work, since f<int>(1);
4615 // gets resolved prior to resorting to overload resolution
4616 // i.e., template<class T> void f(double);
4617 // vs template<class T, class U> void f(U);
4618
4619 // These should be filtered out by our callers.
4620 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4621
4622 // Non-function templates require a template argument list.
4623 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4624 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4626 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4627 return ExprError();
4628 }
4629 }
4630 bool KnownDependent = false;
4631 // In C++1y, check variable template ids.
4632 if (R.getAsSingle<VarTemplateDecl>()) {
4635 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4636 if (Res.isInvalid() || Res.isUsable())
4637 return Res;
4638 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4639 KnownDependent = true;
4640 }
4641
4642 if (R.getAsSingle<ConceptDecl>()) {
4643 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4645 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4646 }
4647
4648 // We don't want lookup warnings at this point.
4650
4653 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4654 R.begin(), R.end(), KnownDependent,
4655 /*KnownInstantiationDependent=*/false);
4656
4657 // Model the templates with UnresolvedTemplateTy. The expression should then
4658 // either be transformed in an instantiation or be diagnosed in
4659 // CheckPlaceholderExpr.
4660 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4663
4664 return ULE;
4665}
4666
4668 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4669 const DeclarationNameInfo &NameInfo,
4670 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4671 assert(TemplateArgs || TemplateKWLoc.isValid());
4672
4673 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4674 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4675 /*EnteringContext=*/false, TemplateKWLoc))
4676 return ExprError();
4677
4678 if (R.isAmbiguous())
4679 return ExprError();
4680
4682 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4683
4684 if (R.empty()) {
4686 Diag(NameInfo.getLoc(), diag::err_no_member)
4687 << NameInfo.getName() << DC << SS.getRange();
4688 return ExprError();
4689 }
4690
4691 // If necessary, build an implicit class member access.
4692 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4693 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4694 /*S=*/nullptr);
4695
4696 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4697}
4698
4700 CXXScopeSpec &SS,
4701 SourceLocation TemplateKWLoc,
4702 const UnqualifiedId &Name,
4703 ParsedType ObjectType,
4704 bool EnteringContext,
4706 bool AllowInjectedClassName) {
4707 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4708 Diag(TemplateKWLoc,
4710 diag::warn_cxx98_compat_template_outside_of_template :
4711 diag::ext_template_outside_of_template)
4712 << FixItHint::CreateRemoval(TemplateKWLoc);
4713
4714 if (SS.isInvalid())
4715 return TNK_Non_template;
4716
4717 // Figure out where isTemplateName is going to look.
4718 DeclContext *LookupCtx = nullptr;
4719 if (SS.isNotEmpty())
4720 LookupCtx = computeDeclContext(SS, EnteringContext);
4721 else if (ObjectType)
4722 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4723
4724 // C++0x [temp.names]p5:
4725 // If a name prefixed by the keyword template is not the name of
4726 // a template, the program is ill-formed. [Note: the keyword
4727 // template may not be applied to non-template members of class
4728 // templates. -end note ] [ Note: as is the case with the
4729 // typename prefix, the template prefix is allowed in cases
4730 // where it is not strictly necessary; i.e., when the
4731 // nested-name-specifier or the expression on the left of the ->
4732 // or . is not dependent on a template-parameter, or the use
4733 // does not appear in the scope of a template. -end note]
4734 //
4735 // Note: C++03 was more strict here, because it banned the use of
4736 // the "template" keyword prior to a template-name that was not a
4737 // dependent name. C++ DR468 relaxed this requirement (the
4738 // "template" keyword is now permitted). We follow the C++0x
4739 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4740 bool MemberOfUnknownSpecialization;
4741 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4742 ObjectType, EnteringContext, Result,
4743 MemberOfUnknownSpecialization);
4744 if (TNK != TNK_Non_template) {
4745 // We resolved this to a (non-dependent) template name. Return it.
4746 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4747 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4748 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4749 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4750 // C++14 [class.qual]p2:
4751 // In a lookup in which function names are not ignored and the
4752 // nested-name-specifier nominates a class C, if the name specified
4753 // [...] is the injected-class-name of C, [...] the name is instead
4754 // considered to name the constructor
4755 //
4756 // We don't get here if naming the constructor would be valid, so we
4757 // just reject immediately and recover by treating the
4758 // injected-class-name as naming the template.
4759 Diag(Name.getBeginLoc(),
4760 diag::ext_out_of_line_qualified_id_type_names_constructor)
4761 << Name.Identifier
4762 << 0 /*injected-class-name used as template name*/
4763 << TemplateKWLoc.isValid();
4764 }
4765 return TNK;
4766 }
4767
4768 if (!MemberOfUnknownSpecialization) {
4769 // Didn't find a template name, and the lookup wasn't dependent.
4770 // Do the lookup again to determine if this is a "nothing found" case or
4771 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4772 // need to do this.
4774 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4776 // Tell LookupTemplateName that we require a template so that it diagnoses
4777 // cases where it finds a non-template.
4778 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4779 ? RequiredTemplateKind(TemplateKWLoc)
4781 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4782 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4783 !R.isAmbiguous()) {
4784 if (LookupCtx)
4785 Diag(Name.getBeginLoc(), diag::err_no_member)
4786 << DNI.getName() << LookupCtx << SS.getRange();
4787 else
4788 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4789 << DNI.getName() << SS.getRange();
4790 }
4791 return TNK_Non_template;
4792 }
4793
4794 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4795
4796 switch (Name.getKind()) {
4799 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4801
4804 Qualifier, Name.OperatorFunctionId.Operator));
4805 return TNK_Function_template;
4806
4808 // This is a kind of template name, but can never occur in a dependent
4809 // scope (literal operators can only be declared at namespace scope).
4810 break;
4811
4812 default:
4813 break;
4814 }
4815
4816 // This name cannot possibly name a dependent template. Diagnose this now
4817 // rather than building a dependent template name that can never be valid.
4818 Diag(Name.getBeginLoc(),
4819 diag::err_template_kw_refers_to_dependent_non_template)
4820 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4821 << TemplateKWLoc.isValid() << TemplateKWLoc;
4822 return TNK_Non_template;
4823}
4824
4827 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4828 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4829 const TemplateArgument &Arg = AL.getArgument();
4830 QualType ArgType;
4831 TypeSourceInfo *TSI = nullptr;
4832
4833 // Check template type parameter.
4834 switch(Arg.getKind()) {
4836 // C++ [temp.arg.type]p1:
4837 // A template-argument for a template-parameter which is a
4838 // type shall be a type-id.
4839 ArgType = Arg.getAsType();
4840 TSI = AL.getTypeSourceInfo();
4841 break;
4844 // We have a template type parameter but the template argument
4845 // is a template without any arguments.
4846 SourceRange SR = AL.getSourceRange();
4849 return true;
4850 }
4852 // We have a template type parameter but the template argument is an
4853 // expression; see if maybe it is missing the "typename" keyword.
4854 CXXScopeSpec SS;
4855 DeclarationNameInfo NameInfo;
4856
4857 if (DependentScopeDeclRefExpr *ArgExpr =
4858 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4859 SS.Adopt(ArgExpr->getQualifierLoc());
4860 NameInfo = ArgExpr->getNameInfo();
4861 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4862 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4863 if (ArgExpr->isImplicitAccess()) {
4864 SS.Adopt(ArgExpr->getQualifierLoc());
4865 NameInfo = ArgExpr->getMemberNameInfo();
4866 }
4867 }
4868
4869 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4870 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4871 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4872
4873 if (Result.getAsSingle<TypeDecl>() ||
4874 Result.wasNotFoundInCurrentInstantiation()) {
4875 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4876 // Suggest that the user add 'typename' before the NNS.
4878 Diag(Loc, getLangOpts().MSVCCompat
4879 ? diag::ext_ms_template_type_arg_missing_typename
4880 : diag::err_template_arg_must_be_type_suggest)
4881 << FixItHint::CreateInsertion(Loc, "typename ");
4883
4884 // Recover by synthesizing a type using the location information that we
4885 // already have.
4887 SS.getScopeRep(), II);
4888 TypeLocBuilder TLB;
4890 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4892 TL.setNameLoc(NameInfo.getLoc());
4893 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4894
4895 // Overwrite our input TemplateArgumentLoc so that we can recover
4896 // properly.
4899
4900 break;
4901 }
4902 }
4903 // fallthrough
4904 [[fallthrough]];
4905 }
4906 default: {
4907 // We allow instantiateing a template with template argument packs when
4908 // building deduction guides.
4909 if (Arg.getKind() == TemplateArgument::Pack &&
4910 CodeSynthesisContexts.back().Kind ==
4912 SugaredConverted.push_back(Arg);
4913 CanonicalConverted.push_back(Arg);
4914 return false;
4915 }
4916 // We have a template type parameter but the template argument
4917 // is not a type.
4918 SourceRange SR = AL.getSourceRange();
4919 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4921
4922 return true;
4923 }
4924 }
4925
4926 if (CheckTemplateArgument(TSI))
4927 return true;
4928
4929 // Objective-C ARC:
4930 // If an explicitly-specified template argument type is a lifetime type
4931 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4932 if (getLangOpts().ObjCAutoRefCount &&
4933 ArgType->isObjCLifetimeType() &&
4934 !ArgType.getObjCLifetime()) {
4935 Qualifiers Qs;
4937 ArgType = Context.getQualifiedType(ArgType, Qs);
4938 }
4939
4940 SugaredConverted.push_back(TemplateArgument(ArgType));
4941 CanonicalConverted.push_back(
4943 return false;
4944}
4945
4946/// Substitute template arguments into the default template argument for
4947/// the given template type parameter.
4948///
4949/// \param SemaRef the semantic analysis object for which we are performing
4950/// the substitution.
4951///
4952/// \param Template the template that we are synthesizing template arguments
4953/// for.
4954///
4955/// \param TemplateLoc the location of the template name that started the
4956/// template-id we are checking.
4957///
4958/// \param RAngleLoc the location of the right angle bracket ('>') that
4959/// terminates the template-id.
4960///
4961/// \param Param the template template parameter whose default we are
4962/// substituting into.
4963///
4964/// \param Converted the list of template arguments provided for template
4965/// parameters that precede \p Param in the template parameter list.
4966///
4967/// \param Output the resulting substituted template argument.
4968///
4969/// \returns true if an error occurred.
4971 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4972 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4973 ArrayRef<TemplateArgument> SugaredConverted,
4974 ArrayRef<TemplateArgument> CanonicalConverted,
4975 TemplateArgumentLoc &Output) {
4976 Output = Param->getDefaultArgument();
4977
4978 // If the argument type is dependent, instantiate it now based
4979 // on the previously-computed template arguments.
4980 if (Output.getArgument().isInstantiationDependent()) {
4981 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4982 SugaredConverted,
4983 SourceRange(TemplateLoc, RAngleLoc));
4984 if (Inst.isInvalid())
4985 return true;
4986
4987 // Only substitute for the innermost template argument list.
4988 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4989 /*Final=*/true);
4990 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4991 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4992
4993 bool ForLambdaCallOperator = false;
4994 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4995 ForLambdaCallOperator = Rec->isLambda();
4996 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4997 !ForLambdaCallOperator);
4998
4999 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
5000 Param->getDefaultArgumentLoc(),
5001 Param->getDeclName()))
5002 return true;
5003 }
5004
5005 return false;
5006}
5007
5008/// Substitute template arguments into the default template argument for
5009/// the given non-type template parameter.
5010///
5011/// \param SemaRef the semantic analysis object for which we are performing
5012/// the substitution.
5013///
5014/// \param Template the template that we are synthesizing template arguments
5015/// for.
5016///
5017/// \param TemplateLoc the location of the template name that started the
5018/// template-id we are checking.
5019///
5020/// \param RAngleLoc the location of the right angle bracket ('>') that
5021/// terminates the template-id.
5022///
5023/// \param Param the non-type template parameter whose default we are
5024/// substituting into.
5025///
5026/// \param Converted the list of template arguments provided for template
5027/// parameters that precede \p Param in the template parameter list.
5028///
5029/// \returns the substituted template argument, or NULL if an error occurred.
5031 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5032 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5033 ArrayRef<TemplateArgument> SugaredConverted,
5034 ArrayRef<TemplateArgument> CanonicalConverted,
5035 TemplateArgumentLoc &Output) {
5036 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5037 SugaredConverted,
5038 SourceRange(TemplateLoc, RAngleLoc));
5039 if (Inst.isInvalid())
5040 return true;
5041
5042 // Only substitute for the innermost template argument list.
5043 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5044 /*Final=*/true);
5045 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5046 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5047
5048 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5049 EnterExpressionEvaluationContext ConstantEvaluated(
5051 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5052 TemplateArgLists, Output);
5053}
5054
5055/// Substitute template arguments into the default template argument for
5056/// the given template template parameter.
5057///
5058/// \param SemaRef the semantic analysis object for which we are performing
5059/// the substitution.
5060///
5061/// \param Template the template that we are synthesizing template arguments
5062/// for.
5063///
5064/// \param TemplateLoc the location of the template name that started the
5065/// template-id we are checking.
5066///
5067/// \param RAngleLoc the location of the right angle bracket ('>') that
5068/// terminates the template-id.
5069///
5070/// \param Param the template template parameter whose default we are
5071/// substituting into.
5072///
5073/// \param Converted the list of template arguments provided for template
5074/// parameters that precede \p Param in the template parameter list.
5075///
5076/// \param QualifierLoc Will be set to the nested-name-specifier (with
5077/// source-location information) that precedes the template name.
5078///
5079/// \returns the substituted template argument, or NULL if an error occurred.
5081 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5082 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5083 ArrayRef<TemplateArgument> SugaredConverted,
5084 ArrayRef<TemplateArgument> CanonicalConverted,
5085 NestedNameSpecifierLoc &QualifierLoc) {
5087 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5088 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5089 if (Inst.isInvalid())
5090 return TemplateName();
5091
5092 // Only substitute for the innermost template argument list.
5093 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5094 /*Final=*/true);
5095 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5096 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5097
5098 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5099 // Substitute into the nested-name-specifier first,
5100 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5101 if (QualifierLoc) {
5102 QualifierLoc =
5103 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5104 if (!QualifierLoc)
5105 return TemplateName();
5106 }
5107
5108 return SemaRef.SubstTemplateName(
5109 QualifierLoc,
5112 TemplateArgLists);
5113}
5114
5116 TemplateDecl *Template, SourceLocation TemplateLoc,
5117 SourceLocation RAngleLoc, Decl *Param,
5118 ArrayRef<TemplateArgument> SugaredConverted,
5119 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5120 HasDefaultArg = false;
5121
5122 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5123 if (!hasReachableDefaultArgument(TypeParm))
5124 return TemplateArgumentLoc();
5125
5126 HasDefaultArg = true;
5127 TemplateArgumentLoc Output;
5128 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5129 TypeParm, SugaredConverted,
5130 CanonicalConverted, Output))
5131 return TemplateArgumentLoc();
5132 return Output;
5133 }
5134
5135 if (NonTypeTemplateParmDecl *NonTypeParm
5136 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5137 if (!hasReachableDefaultArgument(NonTypeParm))
5138 return TemplateArgumentLoc();
5139
5140 HasDefaultArg = true;
5141 TemplateArgumentLoc Output;
5142 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5143 NonTypeParm, SugaredConverted,
5144 CanonicalConverted, Output))
5145 return TemplateArgumentLoc();
5146 return Output;
5147 }
5148
5149 TemplateTemplateParmDecl *TempTempParm
5150 = cast<TemplateTemplateParmDecl>(Param);
5151 if (!hasReachableDefaultArgument(TempTempParm))
5152 return TemplateArgumentLoc();
5153
5154 HasDefaultArg = true;
5155 NestedNameSpecifierLoc QualifierLoc;
5157 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5158 CanonicalConverted, QualifierLoc);
5159 if (TName.isNull())
5160 return TemplateArgumentLoc();
5161
5162 return TemplateArgumentLoc(
5163 Context, TemplateArgument(TName),
5165 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5166}
5167
5168/// Convert a template-argument that we parsed as a type into a template, if
5169/// possible. C++ permits injected-class-names to perform dual service as
5170/// template template arguments and as template type arguments.
5173 // Extract and step over any surrounding nested-name-specifier.
5174 NestedNameSpecifierLoc QualLoc;
5175 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5176 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5177 return TemplateArgumentLoc();
5178
5179 QualLoc = ETLoc.getQualifierLoc();
5180 TLoc = ETLoc.getNamedTypeLoc();
5181 }
5182 // If this type was written as an injected-class-name, it can be used as a
5183 // template template argument.
5184 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5185 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5186 QualLoc, InjLoc.getNameLoc());
5187
5188 // If this type was written as an injected-class-name, it may have been
5189 // converted to a RecordType during instantiation. If the RecordType is
5190 // *not* wrapped in a TemplateSpecializationType and denotes a class
5191 // template specialization, it must have come from an injected-class-name.
5192 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5193 if (auto *CTSD =
5194 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5195 return TemplateArgumentLoc(Context,
5196 TemplateName(CTSD->getSpecializedTemplate()),
5197 QualLoc, RecLoc.getNameLoc());
5198
5199 return TemplateArgumentLoc();
5200}
5201
5203 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5204 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5205 unsigned ArgumentPackIndex,
5206 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5207 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5209 // Check template type parameters.
5210 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5211 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5212 CanonicalConverted);
5213
5214 // Check non-type template parameters.
5215 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5216 // Do substitution on the type of the non-type template parameter
5217 // with the template arguments we've seen thus far. But if the
5218 // template has a dependent context then we cannot substitute yet.
5219 QualType NTTPType = NTTP->getType();
5220 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5221 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5222
5223 if (NTTPType->isInstantiationDependentType() &&
5224 !isa<TemplateTemplateParmDecl>(Template) &&
5225 !Template->getDeclContext()->isDependentContext()) {
5226 // Do substitution on the type of the non-type template parameter.
5227 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5228 SugaredConverted,
5229 SourceRange(TemplateLoc, RAngleLoc));
5230 if (Inst.isInvalid())
5231 return true;
5232
5233 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5234 /*Final=*/true);
5235 // If the parameter is a pack expansion, expand this slice of the pack.
5236 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5238 ArgumentPackIndex);
5239 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5240 NTTP->getDeclName());
5241 } else {
5242 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5243 NTTP->getDeclName());
5244 }
5245
5246 // If that worked, check the non-type template parameter type
5247 // for validity.
5248 if (!NTTPType.isNull())
5249 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5250 NTTP->getLocation());
5251 if (NTTPType.isNull())
5252 return true;
5253 }
5254
5255 switch (Arg.getArgument().getKind()) {
5257 llvm_unreachable("Should never see a NULL template argument here");
5258
5260 Expr *E = Arg.getArgument().getAsExpr();
5261 TemplateArgument SugaredResult, CanonicalResult;
5262 unsigned CurSFINAEErrors = NumSFINAEErrors;
5263 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5264 CanonicalResult, CTAK);
5265 if (Res.isInvalid())
5266 return true;
5267 // If the current template argument causes an error, give up now.
5268 if (CurSFINAEErrors < NumSFINAEErrors)
5269 return true;
5270
5271 // If the resulting expression is new, then use it in place of the
5272 // old expression in the template argument.
5273 if (Res.get() != E) {
5274 TemplateArgument TA(Res.get());
5275 Arg = TemplateArgumentLoc(TA, Res.get());
5276 }
5277
5278 SugaredConverted.push_back(SugaredResult);
5279 CanonicalConverted.push_back(CanonicalResult);
5280 break;
5281 }
5282
5287 // We've already checked this template argument, so just copy
5288 // it to the list of converted arguments.
5289 SugaredConverted.push_back(Arg.getArgument());
5290 CanonicalConverted.push_back(
5292 break;
5293
5296 // We were given a template template argument. It may not be ill-formed;
5297 // see below.
5298 if (DependentTemplateName *DTN
5301 // We have a template argument such as \c T::template X, which we
5302 // parsed as a template template argument. However, since we now
5303 // know that we need a non-type template argument, convert this
5304 // template name into an expression.
5305
5306 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5307 Arg.getTemplateNameLoc());
5308
5309 CXXScopeSpec SS;
5311 // FIXME: the template-template arg was a DependentTemplateName,
5312 // so it was provided with a template keyword. However, its source
5313 // location is not stored in the template argument structure.
5314 SourceLocation TemplateKWLoc;
5316 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5317 nullptr);
5318
5319 // If we parsed the template argument as a pack expansion, create a
5320 // pack expansion expression.
5323 if (E.isInvalid())
5324 return true;
5325 }
5326
5327 TemplateArgument SugaredResult, CanonicalResult;
5328 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5329 CanonicalResult, CTAK_Specified);
5330 if (E.isInvalid())
5331 return true;
5332
5333 SugaredConverted.push_back(SugaredResult);
5334 CanonicalConverted.push_back(CanonicalResult);
5335 break;
5336 }
5337
5338 // We have a template argument that actually does refer to a class
5339 // template, alias template, or template template parameter, and
5340 // therefore cannot be a non-type template argument.
5341 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5342 << Arg.getSourceRange();
5344
5345 return true;
5346
5348 // We have a non-type template parameter but the template
5349 // argument is a type.
5350
5351 // C++ [temp.arg]p2:
5352 // In a template-argument, an ambiguity between a type-id and
5353 // an expression is resolved to a type-id, regardless of the
5354 // form of the corresponding template-parameter.
5355 //
5356 // We warn specifically about this case, since it can be rather
5357 // confusing for users.
5358 QualType T = Arg.getArgument().getAsType();
5359 SourceRange SR = Arg.getSourceRange();
5360 if (T->isFunctionType())
5361 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5362 else
5363 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5365 return true;
5366 }
5367
5369 llvm_unreachable("Caller must expand template argument packs");
5370 }
5371
5372 return false;
5373 }
5374
5375
5376 // Check template template parameters.
5377 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5378
5379 TemplateParameterList *Params = TempParm->getTemplateParameters();
5380 if (TempParm->isExpandedParameterPack())
5381 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5382
5383 // Substitute into the template parameter list of the template
5384 // template parameter, since previously-supplied template arguments
5385 // may appear within the template template parameter.
5386 //
5387 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5388 {
5389 // Set up a template instantiation context.
5391 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5392 SugaredConverted,
5393 SourceRange(TemplateLoc, RAngleLoc));
5394 if (Inst.isInvalid())
5395 return true;
5396
5397 Params =
5400 Template, SugaredConverted, /*Final=*/true),
5401 /*EvaluateConstraints=*/false);
5402 if (!Params)
5403 return true;
5404 }
5405
5406 // C++1z [temp.local]p1: (DR1004)
5407 // When [the injected-class-name] is used [...] as a template-argument for
5408 // a template template-parameter [...] it refers to the class template
5409 // itself.
5413 if (!ConvertedArg.getArgument().isNull())
5414 Arg = ConvertedArg;
5415 }
5416
5417 switch (Arg.getArgument().getKind()) {
5419 llvm_unreachable("Should never see a NULL template argument here");
5420
5423 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5424 /*IsDeduced=*/CTAK != CTAK_Specified))
5425 return true;
5426
5427 SugaredConverted.push_back(Arg.getArgument());
5428 CanonicalConverted.push_back(
5430 break;
5431
5434 // We have a template template parameter but the template
5435 // argument does not refer to a template.
5436 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5437 << getLangOpts().CPlusPlus11;
5438 return true;
5439
5444 llvm_unreachable("non-type argument with template template parameter");
5445
5447 llvm_unreachable("Caller must expand template argument packs");
5448 }
5449
5450 return false;
5451}
5452
5453/// Diagnose a missing template argument.
5454template<typename TemplateParmDecl>
5456 TemplateDecl *TD,
5457 const TemplateParmDecl *D,
5459 // Dig out the most recent declaration of the template parameter; there may be
5460 // declarations of the template that are more recent than TD.
5461 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5462 ->getTemplateParameters()
5463 ->getParam(D->getIndex()));
5464
5465 // If there's a default argument that's not reachable, diagnose that we're
5466 // missing a module import.
5468 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5469 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5470 D->getDefaultArgumentLoc(), Modules,
5472 /*Recover*/true);
5473 return true;
5474 }
5475
5476 // FIXME: If there's a more recent default argument that *is* visible,
5477 // diagnose that it was declared too late.
5478
5480
5481 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5482 << /*not enough args*/0
5484 << TD;
5485 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5486 return true;
5487}
5488
5489/// Check that the given template argument list is well-formed
5490/// for specializing the given template.
5492 TemplateDecl *Template, SourceLocation TemplateLoc,
5493 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5494 bool PartialTemplateArgs,
5495 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5496 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5497 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5498 bool PartialOrderingTTP) {
5499
5501 *ConstraintsNotSatisfied = false;
5502
5503 // Make a copy of the template arguments for processing. Only make the
5504 // changes at the end when successful in matching the arguments to the
5505 // template.
5506 TemplateArgumentListInfo NewArgs = TemplateArgs;
5507
5509
5510 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5511
5512 // C++ [temp.arg]p1:
5513 // [...] The type and form of each template-argument specified in
5514 // a template-id shall match the type and form specified for the
5515 // corresponding parameter declared by the template in its
5516 // template-parameter-list.
5517 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5518 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5519 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5520 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5521 LocalInstantiationScope InstScope(*this, true);
5522 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5523 ParamEnd = Params->end(),
5524 Param = ParamBegin;
5525 Param != ParamEnd;
5526 /* increment in loop */) {
5527 if (size_t ParamIdx = Param - ParamBegin;
5528 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5529 // All written arguments should have been consumed by this point.
5530 assert(ArgIdx == NumArgs && "bad default argument deduction");
5531 // FIXME: Don't ignore parameter packs.
5532 if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5533 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5534 // Default arguments from a DeducedTemplateName are already converted.
5535 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5536 SugaredConverted.push_back(DefArg);
5537 CanonicalConverted.push_back(
5539 ++Param;
5540 }
5541 continue;
5542 }
5543 }
5544
5545 // If we have an expanded parameter pack, make sure we don't have too
5546 // many arguments.
5547 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5548 if (*Expansions == SugaredArgumentPack.size()) {
5549 // We're done with this parameter pack. Pack up its arguments and add
5550 // them to the list.
5551 SugaredConverted.push_back(
5552 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5553 SugaredArgumentPack.clear();
5554
5555 CanonicalConverted.push_back(
5556 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5557 CanonicalArgumentPack.clear();
5558
5559 // This argument is assigned to the next parameter.
5560 ++Param;
5561 continue;
5562 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5563 // Not enough arguments for this parameter pack.
5564 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5565 << /*not enough args*/0
5567 << Template;
5568 NoteTemplateLocation(*Template, Params->getSourceRange());
5569 return true;
5570 }
5571 }
5572
5573 if (ArgIdx < NumArgs) {
5574 // Check the template argument we were given.
5575 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5576 RAngleLoc, SugaredArgumentPack.size(),
5577 SugaredConverted, CanonicalConverted,
5579 return true;
5580
5581 CanonicalConverted.back().setIsDefaulted(
5583 Context, NewArgs[ArgIdx].getArgument(), *Param,
5584 CanonicalConverted, Params->getDepth()));
5585
5586 bool PackExpansionIntoNonPack =
5587 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5588 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5589 // CWG1430: Don't diagnose this pack expansion when partial
5590 // ordering template template parameters. Some uses of the template could
5591 // be valid, and invalid uses will be diagnosed later during
5592 // instantiation.
5593 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5594 (isa<TypeAliasTemplateDecl>(Template) ||
5595 isa<ConceptDecl>(Template))) {
5596 // CWG1430: we have a pack expansion as an argument to an
5597 // alias template, and it's not part of a parameter pack. This
5598 // can't be canonicalized, so reject it now.
5599 // As for concepts - we cannot normalize constraints where this
5600 // situation exists.
5601 Diag(NewArgs[ArgIdx].getLocation(),
5602 diag::err_template_expansion_into_fixed_list)
5603 << (isa<ConceptDecl>(Template) ? 1 : 0)
5604 << NewArgs[ArgIdx].getSourceRange();
5606 return true;
5607 }
5608
5609 // We're now done with this argument.
5610 ++ArgIdx;
5611
5612 if ((*Param)->isTemplateParameterPack()) {
5613 // The template parameter was a template parameter pack, so take the
5614 // deduced argument and place it on the argument pack. Note that we
5615 // stay on the same template parameter so that we can deduce more
5616 // arguments.
5617 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5618 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5619 } else {
5620 // Move to the next template parameter.
5621 ++Param;
5622 }
5623
5624 // If we just saw a pack expansion into a non-pack, then directly convert
5625 // the remaining arguments, because we don't know what parameters they'll
5626 // match up with.
5627 if (PackExpansionIntoNonPack) {
5628 if (!SugaredArgumentPack.empty()) {
5629 // If we were part way through filling in an expanded parameter pack,
5630 // fall back to just producing individual arguments.
5631 SugaredConverted.insert(SugaredConverted.end(),
5632 SugaredArgumentPack.begin(),
5633 SugaredArgumentPack.end());
5634 SugaredArgumentPack.clear();
5635
5636 CanonicalConverted.insert(CanonicalConverted.end(),
5637 CanonicalArgumentPack.begin(),
5638 CanonicalArgumentPack.end());
5639 CanonicalArgumentPack.clear();
5640 }
5641
5642 while (ArgIdx < NumArgs) {
5643 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5644 SugaredConverted.push_back(Arg);
5645 CanonicalConverted.push_back(
5647 ++ArgIdx;
5648 }
5649
5650 return false;
5651 }
5652
5653 continue;
5654 }
5655
5656 // If we're checking a partial template argument list, we're done.
5657 if (PartialTemplateArgs) {
5658 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5659 SugaredConverted.push_back(
5660 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5661 CanonicalConverted.push_back(
5662 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5663 }
5664 return false;
5665 }
5666
5667 // If we have a template parameter pack with no more corresponding
5668 // arguments, just break out now and we'll fill in the argument pack below.
5669 if ((*Param)->isTemplateParameterPack()) {
5670 assert(!getExpandedPackSize(*Param) &&
5671 "Should have dealt with this already");
5672
5673 // A non-expanded parameter pack before the end of the parameter list
5674 // only occurs for an ill-formed template parameter list, unless we've
5675 // got a partial argument list for a function template, so just bail out.
5676 if (Param + 1 != ParamEnd) {
5677 assert(
5678 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5679 "Concept templates must have parameter packs at the end.");
5680 return true;
5681 }
5682
5683 SugaredConverted.push_back(
5684 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5685 SugaredArgumentPack.clear();
5686
5687 CanonicalConverted.push_back(
5688 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5689 CanonicalArgumentPack.clear();
5690
5691 ++Param;
5692 continue;
5693 }
5694
5695 // Check whether we have a default argument.
5696 bool HasDefaultArg;
5697
5698 // Retrieve the default template argument from the template
5699 // parameter. For each kind of template parameter, we substitute the
5700 // template arguments provided thus far and any "outer" template arguments
5701 // (when the template parameter was part of a nested template) into
5702 // the default argument.
5704 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5705 CanonicalConverted, HasDefaultArg);
5706
5707 if (Arg.getArgument().isNull()) {
5708 if (!HasDefaultArg) {
5709 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5710 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5711 NewArgs);
5712 if (NonTypeTemplateParmDecl *NTTP =
5713 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5714 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5715 NewArgs);
5716 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5717 cast<TemplateTemplateParmDecl>(*Param),
5718 NewArgs);
5719 }
5720 return true;
5721 }
5722
5723 // Introduce an instantiation record that describes where we are using
5724 // the default template argument. We're not actually instantiating a
5725 // template here, we just create this object to put a note into the
5726 // context stack.
5727 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5728 SugaredConverted,
5729 SourceRange(TemplateLoc, RAngleLoc));
5730 if (Inst.isInvalid())
5731 return true;
5732
5733 // Check the default template argument.
5734 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5735 SugaredConverted, CanonicalConverted,
5737 return true;
5738
5739 SugaredConverted.back().setIsDefaulted(true);
5740 CanonicalConverted.back().setIsDefaulted(true);
5741
5742 // Core issue 150 (assumed resolution): if this is a template template
5743 // parameter, keep track of the default template arguments from the
5744 // template definition.
5745 if (isTemplateTemplateParameter)
5746 NewArgs.addArgument(Arg);
5747
5748 // Move to the next template parameter and argument.
5749 ++Param;
5750 ++ArgIdx;
5751 }
5752
5753 // If we're performing a partial argument substitution, allow any trailing
5754 // pack expansions; they might be empty. This can happen even if
5755 // PartialTemplateArgs is false (the list of arguments is complete but
5756 // still dependent).
5757 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5759 while (ArgIdx < NumArgs &&
5760 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5761 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5762 SugaredConverted.push_back(Arg);
5763 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5764 }
5765 }
5766
5767 // If we have any leftover arguments, then there were too many arguments.
5768 // Complain and fail.
5769 if (ArgIdx < NumArgs) {
5770 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5771 << /*too many args*/1
5773 << Template
5774 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5775 NoteTemplateLocation(*Template, Params->getSourceRange());
5776 return true;
5777 }
5778
5779 // No problems found with the new argument list, propagate changes back
5780 // to caller.
5781 if (UpdateArgsWithConversions)
5782 TemplateArgs = std::move(NewArgs);
5783
5784 if (!PartialTemplateArgs) {
5785 // Setup the context/ThisScope for the case where we are needing to
5786 // re-instantiate constraints outside of normal instantiation.
5787 DeclContext *NewContext = Template->getDeclContext();
5788
5789 // If this template is in a template, make sure we extract the templated
5790 // decl.
5791 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5792 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5793 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5794
5795 Qualifiers ThisQuals;
5796 if (const auto *Method =
5797 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5798 ThisQuals = Method->getMethodQualifiers();
5799
5800 ContextRAII Context(*this, NewContext);
5801 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5802
5804 Template, NewContext, /*Final=*/false, CanonicalConverted,
5805 /*RelativeToPrimary=*/true,
5806 /*Pattern=*/nullptr,
5807 /*ForConceptInstantiation=*/true);
5809 Template, MLTAL,
5810 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5813 return true;
5814 }
5815 }
5816
5817 return false;
5818}
5819
5820namespace {
5821 class UnnamedLocalNoLinkageFinder
5822 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5823 {
5824 Sema &S;
5825 SourceRange SR;
5826
5828
5829 public:
5830 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5831
5832 bool Visit(QualType T) {
5833 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5834 }
5835
5836#define TYPE(Class, Parent) \
5837 bool Visit##Class##Type(const Class##Type *);
5838#define ABSTRACT_TYPE(Class, Parent) \
5839 bool Visit##Class##Type(const Class##Type *) { return false; }
5840#define NON_CANONICAL_TYPE(Class, Parent) \
5841 bool Visit##Class##Type(const Class##Type *) { return false; }
5842#include "clang/AST/TypeNodes.inc"
5843
5844 bool VisitTagDecl(const TagDecl *Tag);
5845 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5846 };
5847} // end anonymous namespace
5848
5849bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5850 return false;
5851}
5852
5853bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5854 return Visit(T->getElementType());
5855}
5856
5857bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5858 return Visit(T->getPointeeType());
5859}
5860
5861bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5862 const BlockPointerType* T) {
5863 return Visit(T->getPointeeType());
5864}
5865
5866bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5867 const LValueReferenceType* T) {
5868 return Visit(T->getPointeeType());
5869}
5870
5871bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5872 const RValueReferenceType* T) {
5873 return Visit(T->getPointeeType());
5874}
5875
5876bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5877 const MemberPointerType* T) {
5878 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5879}
5880
5881bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5882 const ConstantArrayType* T) {
5883 return Visit(T->getElementType());
5884}
5885
5886bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5887 const IncompleteArrayType* T) {
5888 return Visit(T->getElementType());
5889}
5890
5891bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5892 const VariableArrayType* T) {
5893 return Visit(T->getElementType());
5894}
5895
5896bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5897 const DependentSizedArrayType* T) {
5898 return Visit(T->getElementType());
5899}
5900
5901bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5903 return Visit(T->getElementType());
5904}
5905
5906bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5907 const DependentSizedMatrixType *T) {
5908 return Visit(T->getElementType());
5909}
5910
5911bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5913 return Visit(T->getPointeeType());
5914}
5915
5916bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5917 return Visit(T->getElementType());
5918}
5919
5920bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5921 const DependentVectorType *T) {
5922 return Visit(T->getElementType());
5923}
5924
5925bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5926 return Visit(T->getElementType());
5927}
5928
5929bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5930 const ConstantMatrixType *T) {
5931 return Visit(T->getElementType());
5932}
5933
5934bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5935 const FunctionProtoType* T) {
5936 for (const auto &A : T->param_types()) {
5937 if (Visit(A))
5938 return true;
5939 }
5940
5941 return Visit(T->getReturnType());
5942}
5943
5944bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5945 const FunctionNoProtoType* T) {
5946 return Visit(T->getReturnType());
5947}
5948
5949bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5950 const UnresolvedUsingType*) {
5951 return false;
5952}
5953
5954bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5955 return false;
5956}
5957
5958bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5959 return Visit(T->getUnmodifiedType());
5960}
5961
5962bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5963 return false;
5964}
5965
5966bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5967 const PackIndexingType *) {
5968 return false;
5969}
5970
5971bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5972 const UnaryTransformType*) {
5973 return false;
5974}
5975
5976bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5977 return Visit(T->getDeducedType());
5978}
5979
5980bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5982 return Visit(T->getDeducedType());
5983}
5984
5985bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5986 return VisitTagDecl(T->getDecl());
5987}
5988
5989bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5990 return VisitTagDecl(T->getDecl());
5991}
5992
5993bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5994 const TemplateTypeParmType*) {
5995 return false;
5996}
5997
5998bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6000 return false;
6001}
6002
6003bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6005 return false;
6006}
6007
6008bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6009 const InjectedClassNameType* T) {
6010 return VisitTagDecl(T->getDecl());
6011}
6012
6013bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6014 const DependentNameType* T) {
6015 return VisitNestedNameSpecifier(T->getQualifier());
6016}
6017
6018bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6020 if (auto *Q = T->getQualifier())
6021 return VisitNestedNameSpecifier(Q);
6022 return false;
6023}
6024
6025bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6026 const PackExpansionType* T) {
6027 return Visit(T->getPattern());
6028}
6029
6030bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6031 return false;
6032}
6033
6034bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6035 const ObjCInterfaceType *) {
6036 return false;
6037}
6038
6039bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6040 const ObjCObjectPointerType *) {
6041 return false;
6042}
6043
6044bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6045 return Visit(T->getValueType());
6046}
6047
6048bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6049 return false;
6050}
6051
6052bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6053 return false;
6054}
6055
6056bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6057 const ArrayParameterType *T) {
6058 return VisitConstantArrayType(T);
6059}
6060
6061bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6062 const DependentBitIntType *T) {
6063 return false;
6064}
6065
6066bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6067 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6068 S.Diag(SR.getBegin(),
6069 S.getLangOpts().CPlusPlus11 ?
6070 diag::warn_cxx98_compat_template_arg_local_type :
6071 diag::ext_template_arg_local_type)
6072 << S.Context.getTypeDeclType(Tag) << SR;
6073 return true;
6074 }
6075
6076 if (!Tag->hasNameForLinkage()) {
6077 S.Diag(SR.getBegin(),
6078 S.getLangOpts().CPlusPlus11 ?
6079 diag::warn_cxx98_compat_template_arg_unnamed_type :
6080 diag::ext_template_arg_unnamed_type) << SR;
6081 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6082 return true;
6083 }
6084
6085 return false;
6086}
6087
6088bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6089 NestedNameSpecifier *NNS) {
6090 assert(NNS);
6091 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6092 return true;
6093
6094 switch (NNS->getKind()) {
6100 return false;
6101
6104 return Visit(QualType(NNS->getAsType(), 0));
6105 }
6106 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6107}
6108
6109bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6111 if (T->hasContainedType() && Visit(T->getContainedType()))
6112 return true;
6113 return Visit(T->getWrappedType());
6114}
6115
6117 assert(ArgInfo && "invalid TypeSourceInfo");
6118 QualType Arg = ArgInfo->getType();
6119 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6120 QualType CanonArg = Context.getCanonicalType(Arg);
6121
6122 if (CanonArg->isVariablyModifiedType()) {
6123 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6125 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6126 }
6127
6128 // C++03 [temp.arg.type]p2:
6129 // A local type, a type with no linkage, an unnamed type or a type
6130 // compounded from any of these types shall not be used as a
6131 // template-argument for a template type-parameter.
6132 //
6133 // C++11 allows these, and even in C++03 we allow them as an extension with
6134 // a warning.
6135 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6136 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6137 (void)Finder.Visit(CanonArg);
6138 }
6139
6140 return false;
6141}
6142
6146 NPV_Error
6148
6149/// Determine whether the given template argument is a null pointer
6150/// value of the appropriate type.
6153 QualType ParamType, Expr *Arg,
6154 Decl *Entity = nullptr) {
6155 if (Arg->isValueDependent() || Arg->isTypeDependent())
6156 return NPV_NotNullPointer;
6157
6158 // dllimport'd entities aren't constant but are available inside of template
6159 // arguments.
6160 if (Entity && Entity->hasAttr<DLLImportAttr>())
6161 return NPV_NotNullPointer;
6162
6163 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6164 llvm_unreachable(
6165 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6166
6167 if (!S.getLangOpts().CPlusPlus11)
6168 return NPV_NotNullPointer;
6169
6170 // Determine whether we have a constant expression.
6172 if (ArgRV.isInvalid())
6173 return NPV_Error;
6174 Arg = ArgRV.get();
6175
6176 Expr::EvalResult EvalResult;
6178 EvalResult.Diag = &Notes;
6179 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6180 EvalResult.HasSideEffects) {
6181 SourceLocation DiagLoc = Arg->getExprLoc();
6182
6183 // If our only note is the usual "invalid subexpression" note, just point
6184 // the caret at its location rather than producing an essentially
6185 // redundant note.
6186 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6187 diag::note_invalid_subexpr_in_const_expr) {
6188 DiagLoc = Notes[0].first;
6189 Notes.clear();
6190 }
6191
6192 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6193 << Arg->getType() << Arg->getSourceRange();
6194 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6195 S.Diag(Notes[I].first, Notes[I].second);
6196
6198 return NPV_Error;
6199 }
6200
6201 // C++11 [temp.arg.nontype]p1:
6202 // - an address constant expression of type std::nullptr_t
6203 if (Arg->getType()->isNullPtrType())
6204 return NPV_NullPointer;
6205
6206 // - a constant expression that evaluates to a null pointer value (4.10); or
6207 // - a constant expression that evaluates to a null member pointer value
6208 // (4.11); or
6209 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6210 (EvalResult.Val.isMemberPointer() &&
6211 !EvalResult.Val.getMemberPointerDecl())) {
6212 // If our expression has an appropriate type, we've succeeded.
6213 bool ObjCLifetimeConversion;
6214 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6215 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6216 ObjCLifetimeConversion))
6217 return NPV_NullPointer;
6218
6219 // The types didn't match, but we know we got a null pointer; complain,
6220 // then recover as if the types were correct.
6221 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6222 << Arg->getType() << ParamType << Arg->getSourceRange();
6224 return NPV_NullPointer;
6225 }
6226
6227 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6228 // We found a pointer that isn't null, but doesn't refer to an object.
6229 // We could just return NPV_NotNullPointer, but we can print a better
6230 // message with the information we have here.
6231 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6232 << EvalResult.Val.getAsString(S.Context, ParamType);
6234 return NPV_Error;
6235 }
6236
6237 // If we don't have a null pointer value, but we do have a NULL pointer
6238 // constant, suggest a cast to the appropriate type.
6240 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6241 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6242 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6244 ")");
6246 return NPV_NullPointer;
6247 }
6248
6249 // FIXME: If we ever want to support general, address-constant expressions
6250 // as non-type template arguments, we should return the ExprResult here to
6251 // be interpreted by the caller.
6252 return NPV_NotNullPointer;
6253}
6254
6255/// Checks whether the given template argument is compatible with its
6256/// template parameter.
6258 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6259 Expr *Arg, QualType ArgType) {
6260 bool ObjCLifetimeConversion;
6261 if (ParamType->isPointerType() &&
6262 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6263 S.IsQualificationConversion(ArgType, ParamType, false,
6264 ObjCLifetimeConversion)) {
6265 // For pointer-to-object types, qualification conversions are
6266 // permitted.
6267 } else {
6268 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6269 if (!ParamRef->getPointeeType()->isFunctionType()) {
6270 // C++ [temp.arg.nontype]p5b3:
6271 // For a non-type template-parameter of type reference to
6272 // object, no conversions apply. The type referred to by the
6273 // reference may be more cv-qualified than the (otherwise
6274 // identical) type of the template- argument. The
6275 // template-parameter is bound directly to the
6276 // template-argument, which shall be an lvalue.
6277
6278 // FIXME: Other qualifiers?
6279 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6280 unsigned ArgQuals = ArgType.getCVRQualifiers();
6281
6282 if ((ParamQuals | ArgQuals) != ParamQuals) {
6283 S.Diag(Arg->getBeginLoc(),
6284 diag::err_template_arg_ref_bind_ignores_quals)
6285 << ParamType << Arg->getType() << Arg->getSourceRange();
6287 return true;
6288 }
6289 }
6290 }
6291
6292 // At this point, the template argument refers to an object or
6293 // function with external linkage. We now need to check whether the
6294 // argument and parameter types are compatible.
6295 if (!S.Context.hasSameUnqualifiedType(ArgType,
6296 ParamType.getNonReferenceType())) {
6297 // We can't perform this conversion or binding.
6298 if (ParamType->isReferenceType())
6299 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6300 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6301 else
6302 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6303 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6305 return true;
6306 }
6307 }
6308
6309 return false;
6310}
6311
6312/// Checks whether the given template argument is the address
6313/// of an object or function according to C++ [temp.arg.nontype]p1.
6315 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6316 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6317 bool Invalid = false;
6318 Expr *Arg = ArgIn;
6319 QualType ArgType = Arg->getType();
6320
6321 bool AddressTaken = false;
6322 SourceLocation AddrOpLoc;
6323 if (S.getLangOpts().MicrosoftExt) {
6324 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6325 // dereference and address-of operators.
6326 Arg = Arg->IgnoreParenCasts();
6327
6328 bool ExtWarnMSTemplateArg = false;
6329 UnaryOperatorKind FirstOpKind;
6330 SourceLocation FirstOpLoc;
6331 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6332 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6333 if (UnOpKind == UO_Deref)
6334 ExtWarnMSTemplateArg = true;
6335 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6336 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6337 if (!AddrOpLoc.isValid()) {
6338 FirstOpKind = UnOpKind;
6339 FirstOpLoc = UnOp->getOperatorLoc();
6340 }
6341 } else
6342 break;
6343 }
6344 if (FirstOpLoc.isValid()) {
6345 if (ExtWarnMSTemplateArg)
6346 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6347 << ArgIn->getSourceRange();
6348
6349 if (FirstOpKind == UO_AddrOf)
6350 AddressTaken = true;
6351 else if (Arg->getType()->isPointerType()) {
6352 // We cannot let pointers get dereferenced here, that is obviously not a
6353 // constant expression.
6354 assert(FirstOpKind == UO_Deref);
6355 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6356 << Arg->getSourceRange();
6357 }
6358 }
6359 } else {
6360 // See through any implicit casts we added to fix the type.
6361 Arg = Arg->IgnoreImpCasts();
6362
6363 // C++ [temp.arg.nontype]p1:
6364 //
6365 // A template-argument for a non-type, non-template
6366 // template-parameter shall be one of: [...]
6367 //
6368 // -- the address of an object or function with external
6369 // linkage, including function templates and function
6370 // template-ids but excluding non-static class members,
6371 // expressed as & id-expression where the & is optional if
6372 // the name refers to a function or array, or if the
6373 // corresponding template-parameter is a reference; or
6374
6375 // In C++98/03 mode, give an extension warning on any extra parentheses.
6376 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6377 bool ExtraParens = false;
6378 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6379 if (!Invalid && !ExtraParens) {
6380 S.Diag(Arg->getBeginLoc(),
6381 S.getLangOpts().CPlusPlus11
6382 ? diag::warn_cxx98_compat_template_arg_extra_parens
6383 : diag::ext_template_arg_extra_parens)
6384 << Arg->getSourceRange();
6385 ExtraParens = true;
6386 }
6387
6388 Arg = Parens->getSubExpr();
6389 }
6390
6391 while (SubstNonTypeTemplateParmExpr *subst =
6392 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6393 Arg = subst->getReplacement()->IgnoreImpCasts();
6394
6395 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6396 if (UnOp->getOpcode() == UO_AddrOf) {
6397 Arg = UnOp->getSubExpr();
6398 AddressTaken = true;
6399 AddrOpLoc = UnOp->getOperatorLoc();
6400 }
6401 }
6402
6403 while (SubstNonTypeTemplateParmExpr *subst =
6404 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6405 Arg = subst->getReplacement()->IgnoreImpCasts();
6406 }
6407
6408 ValueDecl *Entity = nullptr;
6409 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6410 Entity = DRE->getDecl();
6411 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6412 Entity = CUE->getGuidDecl();
6413
6414 // If our parameter has pointer type, check for a null template value.
6415 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6416 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6417 Entity)) {
6418 case NPV_NullPointer:
6419 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6420 SugaredConverted = TemplateArgument(ParamType,
6421 /*isNullPtr=*/true);
6422 CanonicalConverted =
6424 /*isNullPtr=*/true);
6425 return false;
6426
6427 case NPV_Error:
6428 return true;
6429
6430 case NPV_NotNullPointer:
6431 break;
6432 }
6433 }
6434
6435 // Stop checking the precise nature of the argument if it is value dependent,
6436 // it should be checked when instantiated.
6437 if (Arg->isValueDependent()) {
6438 SugaredConverted = TemplateArgument(ArgIn);
6439 CanonicalConverted =
6440 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6441 return false;
6442 }
6443
6444 if (!Entity) {
6445 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6446 << Arg->getSourceRange();
6448 return true;
6449 }
6450
6451 // Cannot refer to non-static data members
6452 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6453 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6454 << Entity << Arg->getSourceRange();
6456 return true;
6457 }
6458
6459 // Cannot refer to non-static member functions
6460 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6461 if (!Method->isStatic()) {
6462 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6463 << Method << Arg->getSourceRange();
6465 return true;
6466 }
6467 }
6468
6469 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6470 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6471 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6472
6473 // A non-type template argument must refer to an object or function.
6474 if (!Func && !Var && !Guid) {
6475 // We found something, but we don't know specifically what it is.
6476 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6477 << Arg->getSourceRange();
6478 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6479 return true;
6480 }
6481
6482 // Address / reference template args must have external linkage in C++98.
6483 if (Entity->getFormalLinkage() == Linkage::Internal) {
6484 S.Diag(Arg->getBeginLoc(),
6485 S.getLangOpts().CPlusPlus11
6486 ? diag::warn_cxx98_compat_template_arg_object_internal
6487 : diag::ext_template_arg_object_internal)
6488 << !Func << Entity << Arg->getSourceRange();
6489 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6490 << !Func;
6491 } else if (!Entity->hasLinkage()) {
6492 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6493 << !Func << Entity << Arg->getSourceRange();
6494 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6495 << !Func;
6496 return true;
6497 }
6498
6499 if (Var) {
6500 // A value of reference type is not an object.
6501 if (Var->getType()->isReferenceType()) {
6502 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6503 << Var->getType() << Arg->getSourceRange();
6505 return true;
6506 }
6507
6508 // A template argument must have static storage duration.
6509 if (Var->getTLSKind()) {
6510 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6511 << Arg->getSourceRange();
6512 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6513 return true;
6514 }
6515 }
6516
6517 if (AddressTaken && ParamType->isReferenceType()) {
6518 // If we originally had an address-of operator, but the
6519 // parameter has reference type, complain and (if things look
6520 // like they will work) drop the address-of operator.
6521 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6522 ParamType.getNonReferenceType())) {
6523 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6524 << ParamType;
6526 return true;
6527 }
6528
6529 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6530 << ParamType
6531 << FixItHint::CreateRemoval(AddrOpLoc);
6533
6534 ArgType = Entity->getType();
6535 }
6536
6537 // If the template parameter has pointer type, either we must have taken the
6538 // address or the argument must decay to a pointer.
6539 if (!AddressTaken && ParamType->isPointerType()) {
6540 if (Func) {
6541 // Function-to-pointer decay.
6542 ArgType = S.Context.getPointerType(Func->getType());
6543 } else if (Entity->getType()->isArrayType()) {
6544 // Array-to-pointer decay.
6545 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6546 } else {
6547 // If the template parameter has pointer type but the address of
6548 // this object was not taken, complain and (possibly) recover by
6549 // taking the address of the entity.
6550 ArgType = S.Context.getPointerType(Entity->getType());
6551 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6552 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6553 << ParamType;
6555 return true;
6556 }
6557
6558 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6559 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6560
6562 }
6563 }
6564
6565 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6566 Arg, ArgType))
6567 return true;
6568
6569 // Create the template argument.
6570 SugaredConverted = TemplateArgument(Entity, ParamType);
6571 CanonicalConverted =
6572 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6573 S.Context.getCanonicalType(ParamType));
6574 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6575 return false;
6576}
6577
6578/// Checks whether the given template argument is a pointer to
6579/// member constant according to C++ [temp.arg.nontype]p1.
6580static bool
6582 QualType ParamType, Expr *&ResultArg,
6583 TemplateArgument &SugaredConverted,
6584 TemplateArgument &CanonicalConverted) {
6585 bool Invalid = false;
6586
6587 Expr *Arg = ResultArg;
6588 bool ObjCLifetimeConversion;
6589
6590 // C++ [temp.arg.nontype]p1:
6591 //
6592 // A template-argument for a non-type, non-template
6593 // template-parameter shall be one of: [...]
6594 //
6595 // -- a pointer to member expressed as described in 5.3.1.
6596 DeclRefExpr *DRE = nullptr;
6597
6598 // In C++98/03 mode, give an extension warning on any extra parentheses.
6599 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6600 bool ExtraParens = false;
6601 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6602 if (!Invalid && !ExtraParens) {
6603 S.Diag(Arg->getBeginLoc(),
6604 S.getLangOpts().CPlusPlus11
6605 ? diag::warn_cxx98_compat_template_arg_extra_parens
6606 : diag::ext_template_arg_extra_parens)
6607 << Arg->getSourceRange();
6608 ExtraParens = true;
6609 }
6610
6611 Arg = Parens->getSubExpr();
6612 }
6613
6614 while (SubstNonTypeTemplateParmExpr *subst =
6615 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6616 Arg = subst->getReplacement()->IgnoreImpCasts();
6617
6618 // A pointer-to-member constant written &Class::member.
6619 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6620 if (UnOp->getOpcode() == UO_AddrOf) {
6621 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6622 if (DRE && !DRE->getQualifier())
6623 DRE = nullptr;
6624 }
6625 }
6626 // A constant of pointer-to-member type.
6627 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6628 ValueDecl *VD = DRE->getDecl();
6629 if (VD->getType()->isMemberPointerType()) {
6630 if (isa<NonTypeTemplateParmDecl>(VD)) {
6631 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6632 SugaredConverted = TemplateArgument(Arg);
6633 CanonicalConverted =
6634 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6635 } else {
6636 SugaredConverted = TemplateArgument(VD, ParamType);
6637 CanonicalConverted =
6638 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6639 S.Context.getCanonicalType(ParamType));
6640 }
6641 return Invalid;
6642 }
6643 }
6644
6645 DRE = nullptr;
6646 }
6647
6648 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6649
6650 // Check for a null pointer value.
6651 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6652 Entity)) {
6653 case NPV_Error:
6654 return true;
6655 case NPV_NullPointer:
6656 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6657 SugaredConverted = TemplateArgument(ParamType,
6658 /*isNullPtr*/ true);
6659 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6660 /*isNullPtr*/ true);
6661 return false;
6662 case NPV_NotNullPointer:
6663 break;
6664 }
6665
6666 if (S.IsQualificationConversion(ResultArg->getType(),
6667 ParamType.getNonReferenceType(), false,
6668 ObjCLifetimeConversion)) {
6669 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6670 ResultArg->getValueKind())
6671 .get();
6672 } else if (!S.Context.hasSameUnqualifiedType(
6673 ResultArg->getType(), ParamType.getNonReferenceType())) {
6674 // We can't perform this conversion.
6675 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6676 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6678 return true;
6679 }
6680
6681 if (!DRE)
6682 return S.Diag(Arg->getBeginLoc(),
6683 diag::err_template_arg_not_pointer_to_member_form)
6684 << Arg->getSourceRange();
6685
6686 if (isa<FieldDecl>(DRE->getDecl()) ||
6687 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6688 isa<CXXMethodDecl>(DRE->getDecl())) {
6689 assert((isa<FieldDecl>(DRE->getDecl()) ||
6690 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6691 cast<CXXMethodDecl>(DRE->getDecl())
6692 ->isImplicitObjectMemberFunction()) &&
6693 "Only non-static member pointers can make it here");
6694
6695 // Okay: this is the address of a non-static member, and therefore
6696 // a member pointer constant.
6697 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6698 SugaredConverted = TemplateArgument(Arg);
6699 CanonicalConverted =
6700 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6701 } else {
6702 ValueDecl *D = DRE->getDecl();
6703 SugaredConverted = TemplateArgument(D, ParamType);
6704 CanonicalConverted =
6705 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6706 S.Context.getCanonicalType(ParamType));
6707 }
6708 return Invalid;
6709 }
6710
6711 // We found something else, but we don't know specifically what it is.
6712 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6713 << Arg->getSourceRange();
6714 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6715 return true;
6716}
6717
6719 QualType ParamType, Expr *Arg,
6720 TemplateArgument &SugaredConverted,
6721 TemplateArgument &CanonicalConverted,
6723 SourceLocation StartLoc = Arg->getBeginLoc();
6724
6725 // If the parameter type somehow involves auto, deduce the type now.
6726 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6727 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6728 // During template argument deduction, we allow 'decltype(auto)' to
6729 // match an arbitrary dependent argument.
6730 // FIXME: The language rules don't say what happens in this case.
6731 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6732 // expression is merely instantiation-dependent; is this enough?
6733 if (Arg->isTypeDependent()) {
6734 auto *AT = dyn_cast<AutoType>(DeducedT);
6735 if (AT && AT->isDecltypeAuto()) {
6736 SugaredConverted = TemplateArgument(Arg);
6737 CanonicalConverted = TemplateArgument(
6738 Context.getCanonicalTemplateArgument(SugaredConverted));
6739 return Arg;
6740 }
6741 }
6742
6743 // When checking a deduced template argument, deduce from its type even if
6744 // the type is dependent, in order to check the types of non-type template
6745 // arguments line up properly in partial ordering.
6746 Expr *DeductionArg = Arg;
6747 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6748 DeductionArg = PE->getPattern();
6749 TypeSourceInfo *TSI =
6750 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6751 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6752 InitializedEntity Entity =
6755 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6756 Expr *Inits[1] = {DeductionArg};
6757 ParamType =
6758 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6759 if (ParamType.isNull())
6760 return ExprError();
6761 } else {
6762 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6763 Param->getDepth() + 1);
6764 ParamType = QualType();
6766 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6767 /*DependentDeduction=*/true,
6768 // We do not check constraints right now because the
6769 // immediately-declared constraint of the auto type is
6770 // also an associated constraint, and will be checked
6771 // along with the other associated constraints after
6772 // checking the template argument list.
6773 /*IgnoreConstraints=*/true);
6775 if (ParamType.isNull())
6776 return ExprError();
6778 Diag(Arg->getExprLoc(),
6779 diag::err_non_type_template_parm_type_deduction_failure)
6780 << Param->getDeclName() << Param->getType() << Arg->getType()
6781 << Arg->getSourceRange();
6783 return ExprError();
6784 }
6785 }
6786 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6787 // an error. The error message normally references the parameter
6788 // declaration, but here we'll pass the argument location because that's
6789 // where the parameter type is deduced.
6790 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6791 if (ParamType.isNull()) {
6793 return ExprError();
6794 }
6795 }
6796
6797 // We should have already dropped all cv-qualifiers by now.
6798 assert(!ParamType.hasQualifiers() &&
6799 "non-type template parameter type cannot be qualified");
6800
6801 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6802 if (CTAK == CTAK_Deduced &&
6803 (ParamType->isReferenceType()
6805 Arg->getType())
6806 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6807 // FIXME: If either type is dependent, we skip the check. This isn't
6808 // correct, since during deduction we're supposed to have replaced each
6809 // template parameter with some unique (non-dependent) placeholder.
6810 // FIXME: If the argument type contains 'auto', we carry on and fail the
6811 // type check in order to force specific types to be more specialized than
6812 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6813 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6814 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6815 !Arg->getType()->getContainedDeducedType()) {
6816 SugaredConverted = TemplateArgument(Arg);
6817 CanonicalConverted = TemplateArgument(
6818 Context.getCanonicalTemplateArgument(SugaredConverted));
6819 return Arg;
6820 }
6821 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6822 // we should actually be checking the type of the template argument in P,
6823 // not the type of the template argument deduced from A, against the
6824 // template parameter type.
6825 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6826 << Arg->getType()
6827 << ParamType.getUnqualifiedType();
6829 return ExprError();
6830 }
6831
6832 // If either the parameter has a dependent type or the argument is
6833 // type-dependent, there's nothing we can check now.
6834 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6835 // Force the argument to the type of the parameter to maintain invariants.
6836 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6837 if (PE)
6838 Arg = PE->getPattern();
6840 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6841 ParamType->isLValueReferenceType() ? VK_LValue
6842 : ParamType->isRValueReferenceType() ? VK_XValue
6843 : VK_PRValue);
6844 if (E.isInvalid())
6845 return ExprError();
6846 if (PE) {
6847 // Recreate a pack expansion if we unwrapped one.
6848 E = new (Context)
6849 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6850 PE->getNumExpansions());
6851 }
6852 SugaredConverted = TemplateArgument(E.get());
6853 CanonicalConverted = TemplateArgument(
6854 Context.getCanonicalTemplateArgument(SugaredConverted));
6855 return E;
6856 }
6857
6858 QualType CanonParamType = Context.getCanonicalType(ParamType);
6859 // Avoid making a copy when initializing a template parameter of class type
6860 // from a template parameter object of the same type. This is going beyond
6861 // the standard, but is required for soundness: in
6862 // template<A a> struct X { X *p; X<a> *q; };
6863 // ... we need p and q to have the same type.
6864 //
6865 // Similarly, don't inject a call to a copy constructor when initializing
6866 // from a template parameter of the same type.
6867 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6868 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6869 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6870 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6871 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6872
6873 SugaredConverted = TemplateArgument(TPO, ParamType);
6874 CanonicalConverted =
6875 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6876 return Arg;
6877 }
6878 if (isa<NonTypeTemplateParmDecl>(ND)) {
6879 SugaredConverted = TemplateArgument(Arg);
6880 CanonicalConverted =
6881 Context.getCanonicalTemplateArgument(SugaredConverted);
6882 return Arg;
6883 }
6884 }
6885
6886 // The initialization of the parameter from the argument is
6887 // a constant-evaluated context.
6890
6891 bool IsConvertedConstantExpression = true;
6892 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6894 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6895 Expr *Inits[1] = {Arg};
6896 InitializedEntity Entity =
6898 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6899 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6900 if (Result.isInvalid() || !Result.get())
6901 return ExprError();
6903 if (Result.isInvalid() || !Result.get())
6904 return ExprError();
6905 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6906 /*DiscardedValue=*/false,
6907 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6908 .get();
6909 IsConvertedConstantExpression = false;
6910 }
6911
6912 if (getLangOpts().CPlusPlus17) {
6913 // C++17 [temp.arg.nontype]p1:
6914 // A template-argument for a non-type template parameter shall be
6915 // a converted constant expression of the type of the template-parameter.
6916 APValue Value;
6917 ExprResult ArgResult;
6918 if (IsConvertedConstantExpression) {
6919 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6920 CCEK_TemplateArg, Param);
6921 if (ArgResult.isInvalid())
6922 return ExprError();
6923 } else {
6924 ArgResult = Arg;
6925 }
6926
6927 // For a value-dependent argument, CheckConvertedConstantExpression is
6928 // permitted (and expected) to be unable to determine a value.
6929 if (ArgResult.get()->isValueDependent()) {
6930 SugaredConverted = TemplateArgument(ArgResult.get());
6931 CanonicalConverted =
6932 Context.getCanonicalTemplateArgument(SugaredConverted);
6933 return ArgResult;
6934 }
6935
6936 APValue PreNarrowingValue;
6938 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6939 false, PreNarrowingValue);
6940 if (ArgResult.isInvalid())
6941 return ExprError();
6942
6943 if (Value.isLValue()) {
6944 APValue::LValueBase Base = Value.getLValueBase();
6945 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6946 // For a non-type template-parameter of pointer or reference type,
6947 // the value of the constant expression shall not refer to
6948 assert(ParamType->isPointerOrReferenceType() ||
6949 ParamType->isNullPtrType());
6950 // -- a temporary object
6951 // -- a string literal
6952 // -- the result of a typeid expression, or
6953 // -- a predefined __func__ variable
6954 if (Base &&
6955 (!VD ||
6956 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6957 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6958 << Arg->getSourceRange();
6959 return ExprError();
6960 }
6961
6962 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6963 VD->getType()->isArrayType() &&
6964 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6965 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6966 SugaredConverted = TemplateArgument(VD, ParamType);
6967 CanonicalConverted = TemplateArgument(
6968 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6969 return ArgResult.get();
6970 }
6971
6972 // -- a subobject [until C++20]
6973 if (!getLangOpts().CPlusPlus20) {
6974 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6975 Value.isLValueOnePastTheEnd()) {
6976 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6977 << Value.getAsString(Context, ParamType);
6978 return ExprError();
6979 }
6980 assert((VD || !ParamType->isReferenceType()) &&
6981 "null reference should not be a constant expression");
6982 assert((!VD || !ParamType->isNullPtrType()) &&
6983 "non-null value of type nullptr_t?");
6984 }
6985 }
6986
6987 if (Value.isAddrLabelDiff())
6988 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6989
6990 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6991 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6992 return ArgResult.get();
6993 }
6994
6995 // C++ [temp.arg.nontype]p5:
6996 // The following conversions are performed on each expression used
6997 // as a non-type template-argument. If a non-type
6998 // template-argument cannot be converted to the type of the
6999 // corresponding template-parameter then the program is
7000 // ill-formed.
7001 if (ParamType->isIntegralOrEnumerationType()) {
7002 // C++11:
7003 // -- for a non-type template-parameter of integral or
7004 // enumeration type, conversions permitted in a converted
7005 // constant expression are applied.
7006 //
7007 // C++98:
7008 // -- for a non-type template-parameter of integral or
7009 // enumeration type, integral promotions (4.5) and integral
7010 // conversions (4.7) are applied.
7011
7012 if (getLangOpts().CPlusPlus11) {
7013 // C++ [temp.arg.nontype]p1:
7014 // A template-argument for a non-type, non-template template-parameter
7015 // shall be one of:
7016 //
7017 // -- for a non-type template-parameter of integral or enumeration
7018 // type, a converted constant expression of the type of the
7019 // template-parameter; or
7020 llvm::APSInt Value;
7021 ExprResult ArgResult =
7024 if (ArgResult.isInvalid())
7025 return ExprError();
7026
7027 // We can't check arbitrary value-dependent arguments.
7028 if (ArgResult.get()->isValueDependent()) {
7029 SugaredConverted = TemplateArgument(ArgResult.get());
7030 CanonicalConverted =
7031 Context.getCanonicalTemplateArgument(SugaredConverted);
7032 return ArgResult;
7033 }
7034
7035 // Widen the argument value to sizeof(parameter type). This is almost
7036 // always a no-op, except when the parameter type is bool. In
7037 // that case, this may extend the argument from 1 bit to 8 bits.
7038 QualType IntegerType = ParamType;
7039 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7040 IntegerType = Enum->getDecl()->getIntegerType();
7041 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7042 ? Context.getIntWidth(IntegerType)
7043 : Context.getTypeSize(IntegerType));
7044
7045 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7046 CanonicalConverted =
7048 return ArgResult;
7049 }
7050
7051 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7052 if (ArgResult.isInvalid())
7053 return ExprError();
7054 Arg = ArgResult.get();
7055
7056 QualType ArgType = Arg->getType();
7057
7058 // C++ [temp.arg.nontype]p1:
7059 // A template-argument for a non-type, non-template
7060 // template-parameter shall be one of:
7061 //
7062 // -- an integral constant-expression of integral or enumeration
7063 // type; or
7064 // -- the name of a non-type template-parameter; or
7065 llvm::APSInt Value;
7066 if (!ArgType->isIntegralOrEnumerationType()) {
7067 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7068 << ArgType << Arg->getSourceRange();
7070 return ExprError();
7071 } else if (!Arg->isValueDependent()) {
7072 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7073 QualType T;
7074
7075 public:
7076 TmplArgICEDiagnoser(QualType T) : T(T) { }
7077
7078 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7079 SourceLocation Loc) override {
7080 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7081 }
7082 } Diagnoser(ArgType);
7083
7084 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7085 if (!Arg)
7086 return ExprError();
7087 }
7088
7089 // From here on out, all we care about is the unqualified form
7090 // of the argument type.
7091 ArgType = ArgType.getUnqualifiedType();
7092
7093 // Try to convert the argument to the parameter's type.
7094 if (Context.hasSameType(ParamType, ArgType)) {
7095 // Okay: no conversion necessary
7096 } else if (ParamType->isBooleanType()) {
7097 // This is an integral-to-boolean conversion.
7098 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7099 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7100 !ParamType->isEnumeralType()) {
7101 // This is an integral promotion or conversion.
7102 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7103 } else {
7104 // We can't perform this conversion.
7105 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7106 << Arg->getType() << ParamType << Arg->getSourceRange();
7108 return ExprError();
7109 }
7110
7111 // Add the value of this argument to the list of converted
7112 // arguments. We use the bitwidth and signedness of the template
7113 // parameter.
7114 if (Arg->isValueDependent()) {
7115 // The argument is value-dependent. Create a new
7116 // TemplateArgument with the converted expression.
7117 SugaredConverted = TemplateArgument(Arg);
7118 CanonicalConverted =
7119 Context.getCanonicalTemplateArgument(SugaredConverted);
7120 return Arg;
7121 }
7122
7123 QualType IntegerType = ParamType;
7124 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7125 IntegerType = Enum->getDecl()->getIntegerType();
7126 }
7127
7128 if (ParamType->isBooleanType()) {
7129 // Value must be zero or one.
7130 Value = Value != 0;
7131 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7132 if (Value.getBitWidth() != AllowedBits)
7133 Value = Value.extOrTrunc(AllowedBits);
7134 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7135 } else {
7136 llvm::APSInt OldValue = Value;
7137
7138 // Coerce the template argument's value to the value it will have
7139 // based on the template parameter's type.
7140 unsigned AllowedBits = IntegerType->isBitIntType()
7141 ? Context.getIntWidth(IntegerType)
7142 : Context.getTypeSize(IntegerType);
7143 if (Value.getBitWidth() != AllowedBits)
7144 Value = Value.extOrTrunc(AllowedBits);
7145 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7146
7147 // Complain if an unsigned parameter received a negative value.
7148 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7149 (OldValue.isSigned() && OldValue.isNegative())) {
7150 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7151 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7152 << Arg->getSourceRange();
7154 }
7155
7156 // Complain if we overflowed the template parameter's type.
7157 unsigned RequiredBits;
7158 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7159 RequiredBits = OldValue.getActiveBits();
7160 else if (OldValue.isUnsigned())
7161 RequiredBits = OldValue.getActiveBits() + 1;
7162 else
7163 RequiredBits = OldValue.getSignificantBits();
7164 if (RequiredBits > AllowedBits) {
7165 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7166 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7167 << Arg->getSourceRange();
7169 }
7170 }
7171
7172 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7173 SugaredConverted = TemplateArgument(Context, Value, T);
7174 CanonicalConverted =
7176 return Arg;
7177 }
7178
7179 QualType ArgType = Arg->getType();
7180 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7181
7182 // Handle pointer-to-function, reference-to-function, and
7183 // pointer-to-member-function all in (roughly) the same way.
7184 if (// -- For a non-type template-parameter of type pointer to
7185 // function, only the function-to-pointer conversion (4.3) is
7186 // applied. If the template-argument represents a set of
7187 // overloaded functions (or a pointer to such), the matching
7188 // function is selected from the set (13.4).
7189 (ParamType->isPointerType() &&
7190 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7191 // -- For a non-type template-parameter of type reference to
7192 // function, no conversions apply. If the template-argument
7193 // represents a set of overloaded functions, the matching
7194 // function is selected from the set (13.4).
7195 (ParamType->isReferenceType() &&
7196 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7197 // -- For a non-type template-parameter of type pointer to
7198 // member function, no conversions apply. If the
7199 // template-argument represents a set of overloaded member
7200 // functions, the matching member function is selected from
7201 // the set (13.4).
7202 (ParamType->isMemberPointerType() &&
7203 ParamType->castAs<MemberPointerType>()->getPointeeType()
7204 ->isFunctionType())) {
7205
7206 if (Arg->getType() == Context.OverloadTy) {
7207 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7208 true,
7209 FoundResult)) {
7210 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7211 return ExprError();
7212
7213 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7214 if (Res.isInvalid())
7215 return ExprError();
7216 Arg = Res.get();
7217 ArgType = Arg->getType();
7218 } else
7219 return ExprError();
7220 }
7221
7222 if (!ParamType->isMemberPointerType()) {
7224 *this, Param, ParamType, Arg, SugaredConverted,
7225 CanonicalConverted))
7226 return ExprError();
7227 return Arg;
7228 }
7229
7231 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7232 return ExprError();
7233 return Arg;
7234 }
7235
7236 if (ParamType->isPointerType()) {
7237 // -- for a non-type template-parameter of type pointer to
7238 // object, qualification conversions (4.4) and the
7239 // array-to-pointer conversion (4.2) are applied.
7240 // C++0x also allows a value of std::nullptr_t.
7241 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7242 "Only object pointers allowed here");
7243
7245 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7246 return ExprError();
7247 return Arg;
7248 }
7249
7250 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7251 // -- For a non-type template-parameter of type reference to
7252 // object, no conversions apply. The type referred to by the
7253 // reference may be more cv-qualified than the (otherwise
7254 // identical) type of the template-argument. The
7255 // template-parameter is bound directly to the
7256 // template-argument, which must be an lvalue.
7257 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7258 "Only object references allowed here");
7259
7260 if (Arg->getType() == Context.OverloadTy) {
7262 ParamRefType->getPointeeType(),
7263 true,
7264 FoundResult)) {
7265 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7266 return ExprError();
7267 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7268 if (Res.isInvalid())
7269 return ExprError();
7270 Arg = Res.get();
7271 ArgType = Arg->getType();
7272 } else
7273 return ExprError();
7274 }
7275
7277 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7278 return ExprError();
7279 return Arg;
7280 }
7281
7282 // Deal with parameters of type std::nullptr_t.
7283 if (ParamType->isNullPtrType()) {
7284 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7285 SugaredConverted = TemplateArgument(Arg);
7286 CanonicalConverted =
7287 Context.getCanonicalTemplateArgument(SugaredConverted);
7288 return Arg;
7289 }
7290
7291 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7292 case NPV_NotNullPointer:
7293 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7294 << Arg->getType() << ParamType;
7296 return ExprError();
7297
7298 case NPV_Error:
7299 return ExprError();
7300
7301 case NPV_NullPointer:
7302 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7303 SugaredConverted = TemplateArgument(ParamType,
7304 /*isNullPtr=*/true);
7305 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7306 /*isNullPtr=*/true);
7307 return Arg;
7308 }
7309 }
7310
7311 // -- For a non-type template-parameter of type pointer to data
7312 // member, qualification conversions (4.4) are applied.
7313 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7314
7316 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7317 return ExprError();
7318 return Arg;
7319}
7320
7324
7326 TemplateParameterList *Params,
7328 bool IsDeduced) {
7330 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7331 if (!Template) {
7332 // Any dependent template name is fine.
7333 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7334 return false;
7335 }
7336
7337 if (Template->isInvalidDecl())
7338 return true;
7339
7340 // C++0x [temp.arg.template]p1:
7341 // A template-argument for a template template-parameter shall be
7342 // the name of a class template or an alias template, expressed as an
7343 // id-expression. When the template-argument names a class template, only
7344 // primary class templates are considered when matching the
7345 // template template argument with the corresponding parameter;
7346 // partial specializations are not considered even if their
7347 // parameter lists match that of the template template parameter.
7348 //
7349 // Note that we also allow template template parameters here, which
7350 // will happen when we are dealing with, e.g., class template
7351 // partial specializations.
7352 if (!isa<ClassTemplateDecl>(Template) &&
7353 !isa<TemplateTemplateParmDecl>(Template) &&
7354 !isa<TypeAliasTemplateDecl>(Template) &&
7355 !isa<BuiltinTemplateDecl>(Template)) {
7356 assert(isa<FunctionTemplateDecl>(Template) &&
7357 "Only function templates are possible here");
7358 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7359 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7360 << Template;
7361 }
7362
7363 // C++1z [temp.arg.template]p3: (DR 150)
7364 // A template-argument matches a template template-parameter P when P
7365 // is at least as specialized as the template-argument A.
7366 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7367 // Quick check for the common case:
7368 // If P contains a parameter pack, then A [...] matches P if each of A's
7369 // template parameters matches the corresponding template parameter in
7370 // the template-parameter-list of P.
7372 Template->getTemplateParameters(), Params, false,
7374 // If the argument has no associated constraints, then the parameter is
7375 // definitely at least as specialized as the argument.
7376 // Otherwise - we need a more thorough check.
7377 !Template->hasAssociatedConstraints())
7378 return false;
7379
7381 Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7382 // P2113
7383 // C++20[temp.func.order]p2
7384 // [...] If both deductions succeed, the partial ordering selects the
7385 // more constrained template (if one exists) as determined below.
7386 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7387 Params->getAssociatedConstraints(ParamsAC);
7388 // C++2a[temp.arg.template]p3
7389 // [...] In this comparison, if P is unconstrained, the constraints on A
7390 // are not considered.
7391 if (ParamsAC.empty())
7392 return false;
7393
7394 Template->getAssociatedConstraints(TemplateAC);
7395
7396 bool IsParamAtLeastAsConstrained;
7397 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7398 IsParamAtLeastAsConstrained))
7399 return true;
7400 if (!IsParamAtLeastAsConstrained) {
7401 Diag(Arg.getLocation(),
7402 diag::err_template_template_parameter_not_at_least_as_constrained)
7403 << Template << Param << Arg.getSourceRange();
7404 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7405 Diag(Template->getLocation(), diag::note_entity_declared_at)
7406 << Template;
7407 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7408 TemplateAC);
7409 return true;
7410 }
7411 return false;
7412 }
7413 // FIXME: Produce better diagnostics for deduction failures.
7414 }
7415
7416 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7417 Params,
7418 true,
7420 Arg.getLocation());
7421}
7422
7424 unsigned HereDiagID,
7425 unsigned ExternalDiagID) {
7426 if (Decl.getLocation().isValid())
7427 return S.Diag(Decl.getLocation(), HereDiagID);
7428
7429 SmallString<128> Str;
7430 llvm::raw_svector_ostream Out(Str);
7432 PP.TerseOutput = 1;
7433 Decl.print(Out, PP);
7434 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7435}
7436
7438 std::optional<SourceRange> ParamRange) {
7440 noteLocation(*this, Decl, diag::note_template_decl_here,
7441 diag::note_template_decl_external);
7442 if (ParamRange && ParamRange->isValid()) {
7443 assert(Decl.getLocation().isValid() &&
7444 "Parameter range has location when Decl does not");
7445 DB << *ParamRange;
7446 }
7447}
7448
7450 noteLocation(*this, Decl, diag::note_template_param_here,
7451 diag::note_template_param_external);
7452}
7453
7455 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7457 // C++ [temp.param]p8:
7458 //
7459 // A non-type template-parameter of type "array of T" or
7460 // "function returning T" is adjusted to be of type "pointer to
7461 // T" or "pointer to function returning T", respectively.
7462 if (ParamType->isArrayType())
7463 ParamType = Context.getArrayDecayedType(ParamType);
7464 else if (ParamType->isFunctionType())
7465 ParamType = Context.getPointerType(ParamType);
7466
7467 // For a NULL non-type template argument, return nullptr casted to the
7468 // parameter's type.
7469 if (Arg.getKind() == TemplateArgument::NullPtr) {
7470 return ImpCastExprToType(
7472 ParamType,
7473 ParamType->getAs<MemberPointerType>()
7474 ? CK_NullToMemberPointer
7475 : CK_NullToPointer);
7476 }
7477 assert(Arg.getKind() == TemplateArgument::Declaration &&
7478 "Only declaration template arguments permitted here");
7479
7480 ValueDecl *VD = Arg.getAsDecl();
7481
7482 CXXScopeSpec SS;
7483 if (ParamType->isMemberPointerType()) {
7484 // If this is a pointer to member, we need to use a qualified name to
7485 // form a suitable pointer-to-member constant.
7486 assert(VD->getDeclContext()->isRecord() &&
7487 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7488 isa<IndirectFieldDecl>(VD)));
7489 QualType ClassType
7490 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7491 NestedNameSpecifier *Qualifier
7492 = NestedNameSpecifier::Create(Context, nullptr, false,
7493 ClassType.getTypePtr());
7494 SS.MakeTrivial(Context, Qualifier, Loc);
7495 }
7496
7498 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7499 if (RefExpr.isInvalid())
7500 return ExprError();
7501
7502 // For a pointer, the argument declaration is the pointee. Take its address.
7503 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7504 if (ParamType->isPointerType() && !ElemT.isNull() &&
7505 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7506 // Decay an array argument if we want a pointer to its first element.
7507 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7508 if (RefExpr.isInvalid())
7509 return ExprError();
7510 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7511 // For any other pointer, take the address (or form a pointer-to-member).
7512 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7513 if (RefExpr.isInvalid())
7514 return ExprError();
7515 } else if (ParamType->isRecordType()) {
7516 assert(isa<TemplateParamObjectDecl>(VD) &&
7517 "arg for class template param not a template parameter object");
7518 // No conversions apply in this case.
7519 return RefExpr;
7520 } else {
7521 assert(ParamType->isReferenceType() &&
7522 "unexpected type for decl template argument");
7523 if (NonTypeTemplateParmDecl *NTTP =
7524 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7525 QualType TemplateParamType = NTTP->getType();
7526 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7527 if (AT && AT->isDecltypeAuto()) {
7529 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7530 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7531 /*PackIndex=*/std::nullopt,
7532 /*RefParam=*/true);
7533 }
7534 }
7535 }
7536
7537 // At this point we should have the right value category.
7538 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7539 "value kind mismatch for non-type template argument");
7540
7541 // The type of the template parameter can differ from the type of the
7542 // argument in various ways; convert it now if necessary.
7543 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7544 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7545 CastKind CK;
7546 QualType Ignored;
7547 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7548 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7549 CK = CK_NoOp;
7550 } else if (ParamType->isVoidPointerType() &&
7551 RefExpr.get()->getType()->isPointerType()) {
7552 CK = CK_BitCast;
7553 } else {
7554 // FIXME: Pointers to members can need conversion derived-to-base or
7555 // base-to-derived conversions. We currently don't retain enough
7556 // information to convert properly (we need to track a cast path or
7557 // subobject number in the template argument).
7558 llvm_unreachable(
7559 "unexpected conversion required for non-type template argument");
7560 }
7561 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7562 RefExpr.get()->getValueKind());
7563 }
7564
7565 return RefExpr;
7566}
7567
7568/// Construct a new expression that refers to the given
7569/// integral template argument with the given source-location
7570/// information.
7571///
7572/// This routine takes care of the mapping from an integral template
7573/// argument (which may have any integral type) to the appropriate
7574/// literal value.
7576 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7577 assert(OrigT->isIntegralOrEnumerationType());
7578
7579 // If this is an enum type that we're instantiating, we need to use an integer
7580 // type the same size as the enumerator. We don't want to build an
7581 // IntegerLiteral with enum type. The integer type of an enum type can be of
7582 // any integral type with C++11 enum classes, make sure we create the right
7583 // type of literal for it.
7584 QualType T = OrigT;
7585 if (const EnumType *ET = OrigT->getAs<EnumType>())
7586 T = ET->getDecl()->getIntegerType();
7587
7588 Expr *E;
7589 if (T->isAnyCharacterType()) {
7591 if (T->isWideCharType())
7593 else if (T->isChar8Type() && S.getLangOpts().Char8)
7595 else if (T->isChar16Type())
7597 else if (T->isChar32Type())
7599 else
7601
7602 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7603 } else if (T->isBooleanType()) {
7604 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7605 } else {
7606 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7607 }
7608
7609 if (OrigT->isEnumeralType()) {
7610 // FIXME: This is a hack. We need a better way to handle substituted
7611 // non-type template parameters.
7612 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7613 nullptr, S.CurFPFeatureOverrides(),
7615 Loc, Loc);
7616 }
7617
7618 return E;
7619}
7620
7622 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7623 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7624 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7625 ILE->setType(T);
7626 return ILE;
7627 };
7628
7629 switch (Val.getKind()) {
7631 // This cannot occur in a template argument at all.
7632 case APValue::Array:
7633 case APValue::Struct:
7634 case APValue::Union:
7635 // These can only occur within a template parameter object, which is
7636 // represented as a TemplateArgument::Declaration.
7637 llvm_unreachable("unexpected template argument value");
7638
7639 case APValue::Int:
7641 Loc);
7642
7643 case APValue::Float:
7644 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7645 T, Loc);
7646
7649 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7650 Val.getFixedPoint().getScale());
7651
7652 case APValue::ComplexInt: {
7653 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7655 S, ElemT, Val.getComplexIntReal(), Loc),
7657 S, ElemT, Val.getComplexIntImag(), Loc)});
7658 }
7659
7660 case APValue::ComplexFloat: {
7661 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7662 return MakeInitList(
7664 ElemT, Loc),
7666 ElemT, Loc)});
7667 }
7668
7669 case APValue::Vector: {
7670 QualType ElemT = T->castAs<VectorType>()->getElementType();
7672 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7674 S, ElemT, Val.getVectorElt(I), Loc));
7675 return MakeInitList(Elts);
7676 }
7677
7678 case APValue::None:
7680 llvm_unreachable("Unexpected APValue kind.");
7681 case APValue::LValue:
7683 // There isn't necessarily a valid equivalent source-level syntax for
7684 // these; in particular, a naive lowering might violate access control.
7685 // So for now we lower to a ConstantExpr holding the value, wrapped around
7686 // an OpaqueValueExpr.
7687 // FIXME: We should have a better representation for this.
7689 if (T->isReferenceType()) {
7690 T = T->getPointeeType();
7691 VK = VK_LValue;
7692 }
7693 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7694 return ConstantExpr::Create(S.Context, OVE, Val);
7695 }
7696 llvm_unreachable("Unhandled APValue::ValueKind enum");
7697}
7698
7702 switch (Arg.getKind()) {
7708 llvm_unreachable("not a non-type template argument");
7709
7711 return Arg.getAsExpr();
7712
7717
7720 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7721
7724 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7725 }
7726 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7727}
7728
7729/// Match two template parameters within template parameter lists.
7731 Sema &S, NamedDecl *New,
7732 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7733 const NamedDecl *OldInstFrom, bool Complain,
7735 // Check the actual kind (type, non-type, template).
7736 if (Old->getKind() != New->getKind()) {
7737 if (Complain) {
7738 unsigned NextDiag = diag::err_template_param_different_kind;
7739 if (TemplateArgLoc.isValid()) {
7740 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7741 NextDiag = diag::note_template_param_different_kind;
7742 }
7743 S.Diag(New->getLocation(), NextDiag)
7744 << (Kind != Sema::TPL_TemplateMatch);
7745 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7746 << (Kind != Sema::TPL_TemplateMatch);
7747 }
7748
7749 return false;
7750 }
7751
7752 // Check that both are parameter packs or neither are parameter packs.
7753 // However, if we are matching a template template argument to a
7754 // template template parameter, the template template parameter can have
7755 // a parameter pack where the template template argument does not.
7756 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7758 Old->isTemplateParameterPack())) {
7759 if (Complain) {
7760 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7761 if (TemplateArgLoc.isValid()) {
7762 S.Diag(TemplateArgLoc,
7763 diag::err_template_arg_template_params_mismatch);
7764 NextDiag = diag::note_template_parameter_pack_non_pack;
7765 }
7766
7767 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7768 : isa<NonTypeTemplateParmDecl>(New)? 1
7769 : 2;
7770 S.Diag(New->getLocation(), NextDiag)
7771 << ParamKind << New->isParameterPack();
7772 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7773 << ParamKind << Old->isParameterPack();
7774 }
7775
7776 return false;
7777 }
7778
7779 // For non-type template parameters, check the type of the parameter.
7780 if (NonTypeTemplateParmDecl *OldNTTP
7781 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7782 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7783
7784 // If we are matching a template template argument to a template
7785 // template parameter and one of the non-type template parameter types
7786 // is dependent, then we must wait until template instantiation time
7787 // to actually compare the arguments.
7789 (!OldNTTP->getType()->isDependentType() &&
7790 !NewNTTP->getType()->isDependentType())) {
7791 // C++20 [temp.over.link]p6:
7792 // Two [non-type] template-parameters are equivalent [if] they have
7793 // equivalent types ignoring the use of type-constraints for
7794 // placeholder types
7795 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7796 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7797 if (!S.Context.hasSameType(OldType, NewType)) {
7798 if (Complain) {
7799 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7800 if (TemplateArgLoc.isValid()) {
7801 S.Diag(TemplateArgLoc,
7802 diag::err_template_arg_template_params_mismatch);
7803 NextDiag = diag::note_template_nontype_parm_different_type;
7804 }
7805 S.Diag(NewNTTP->getLocation(), NextDiag)
7806 << NewNTTP->getType()
7807 << (Kind != Sema::TPL_TemplateMatch);
7808 S.Diag(OldNTTP->getLocation(),
7809 diag::note_template_nontype_parm_prev_declaration)
7810 << OldNTTP->getType();
7811 }
7812
7813 return false;
7814 }
7815 }
7816 }
7817 // For template template parameters, check the template parameter types.
7818 // The template parameter lists of template template
7819 // parameters must agree.
7820 else if (TemplateTemplateParmDecl *OldTTP =
7821 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7822 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7824 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7825 OldTTP->getTemplateParameters(), Complain,
7828 : Kind),
7829 TemplateArgLoc))
7830 return false;
7831 }
7832
7835 !isa<TemplateTemplateParmDecl>(Old)) {
7836 const Expr *NewC = nullptr, *OldC = nullptr;
7837
7838 if (isa<TemplateTypeParmDecl>(New)) {
7839 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7840 NewC = TC->getImmediatelyDeclaredConstraint();
7841 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7842 OldC = TC->getImmediatelyDeclaredConstraint();
7843 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7844 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7845 ->getPlaceholderTypeConstraint())
7846 NewC = E;
7847 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7848 ->getPlaceholderTypeConstraint())
7849 OldC = E;
7850 } else
7851 llvm_unreachable("unexpected template parameter type");
7852
7853 auto Diagnose = [&] {
7854 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7855 diag::err_template_different_type_constraint);
7856 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7857 diag::note_template_prev_declaration) << /*declaration*/0;
7858 };
7859
7860 if (!NewC != !OldC) {
7861 if (Complain)
7862 Diagnose();
7863 return false;
7864 }
7865
7866 if (NewC) {
7867 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7868 NewC)) {
7869 if (Complain)
7870 Diagnose();
7871 return false;
7872 }
7873 }
7874 }
7875
7876 return true;
7877}
7878
7879/// Diagnose a known arity mismatch when comparing template argument
7880/// lists.
7881static
7886 SourceLocation TemplateArgLoc) {
7887 unsigned NextDiag = diag::err_template_param_list_different_arity;
7888 if (TemplateArgLoc.isValid()) {
7889 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7890 NextDiag = diag::note_template_param_list_different_arity;
7891 }
7892 S.Diag(New->getTemplateLoc(), NextDiag)
7893 << (New->size() > Old->size())
7894 << (Kind != Sema::TPL_TemplateMatch)
7895 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7896 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7897 << (Kind != Sema::TPL_TemplateMatch)
7898 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7899}
7900
7902 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7903 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7904 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7905 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7906 if (Complain)
7907 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7908 TemplateArgLoc);
7909
7910 return false;
7911 }
7912
7913 // C++0x [temp.arg.template]p3:
7914 // A template-argument matches a template template-parameter (call it P)
7915 // when each of the template parameters in the template-parameter-list of
7916 // the template-argument's corresponding class template or alias template
7917 // (call it A) matches the corresponding template parameter in the
7918 // template-parameter-list of P. [...]
7919 TemplateParameterList::iterator NewParm = New->begin();
7920 TemplateParameterList::iterator NewParmEnd = New->end();
7921 for (TemplateParameterList::iterator OldParm = Old->begin(),
7922 OldParmEnd = Old->end();
7923 OldParm != OldParmEnd; ++OldParm) {
7925 !(*OldParm)->isTemplateParameterPack()) {
7926 if (NewParm == NewParmEnd) {
7927 if (Complain)
7928 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7929 TemplateArgLoc);
7930
7931 return false;
7932 }
7933
7934 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7935 OldInstFrom, Complain, Kind,
7936 TemplateArgLoc))
7937 return false;
7938
7939 ++NewParm;
7940 continue;
7941 }
7942
7943 // C++0x [temp.arg.template]p3:
7944 // [...] When P's template- parameter-list contains a template parameter
7945 // pack (14.5.3), the template parameter pack will match zero or more
7946 // template parameters or template parameter packs in the
7947 // template-parameter-list of A with the same type and form as the
7948 // template parameter pack in P (ignoring whether those template
7949 // parameters are template parameter packs).
7950 for (; NewParm != NewParmEnd; ++NewParm) {
7951 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7952 OldInstFrom, Complain, Kind,
7953 TemplateArgLoc))
7954 return false;
7955 }
7956 }
7957
7958 // Make sure we exhausted all of the arguments.
7959 if (NewParm != NewParmEnd) {
7960 if (Complain)
7961 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7962 TemplateArgLoc);
7963
7964 return false;
7965 }
7966
7969 const Expr *NewRC = New->getRequiresClause();
7970 const Expr *OldRC = Old->getRequiresClause();
7971
7972 auto Diagnose = [&] {
7973 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7974 diag::err_template_different_requires_clause);
7975 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7976 diag::note_template_prev_declaration) << /*declaration*/0;
7977 };
7978
7979 if (!NewRC != !OldRC) {
7980 if (Complain)
7981 Diagnose();
7982 return false;
7983 }
7984
7985 if (NewRC) {
7986 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7987 NewRC)) {
7988 if (Complain)
7989 Diagnose();
7990 return false;
7991 }
7992 }
7993 }
7994
7995 return true;
7996}
7997
7998bool
8000 if (!S)
8001 return false;
8002
8003 // Find the nearest enclosing declaration scope.
8004 S = S->getDeclParent();
8005
8006 // C++ [temp.pre]p6: [P2096]
8007 // A template, explicit specialization, or partial specialization shall not
8008 // have C linkage.
8009 DeclContext *Ctx = S->getEntity();
8010 if (Ctx && Ctx->isExternCContext()) {
8011 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8012 << TemplateParams->getSourceRange();
8013 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8014 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8015 return true;
8016 }
8017 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8018
8019 // C++ [temp]p2:
8020 // A template-declaration can appear only as a namespace scope or
8021 // class scope declaration.
8022 // C++ [temp.expl.spec]p3:
8023 // An explicit specialization may be declared in any scope in which the
8024 // corresponding primary template may be defined.
8025 // C++ [temp.class.spec]p6: [P2096]
8026 // A partial specialization may be declared in any scope in which the
8027 // corresponding primary template may be defined.
8028 if (Ctx) {
8029 if (Ctx->isFileContext())
8030 return false;
8031 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8032 // C++ [temp.mem]p2:
8033 // A local class shall not have member templates.
8034 if (RD->isLocalClass())
8035 return Diag(TemplateParams->getTemplateLoc(),
8036 diag::err_template_inside_local_class)
8037 << TemplateParams->getSourceRange();
8038 else
8039 return false;
8040 }
8041 }
8042
8043 return Diag(TemplateParams->getTemplateLoc(),
8044 diag::err_template_outside_namespace_or_class_scope)
8045 << TemplateParams->getSourceRange();
8046}
8047
8048/// Determine what kind of template specialization the given declaration
8049/// is.
8051 if (!D)
8052 return TSK_Undeclared;
8053
8054 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8055 return Record->getTemplateSpecializationKind();
8056 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8057 return Function->getTemplateSpecializationKind();
8058 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8059 return Var->getTemplateSpecializationKind();
8060
8061 return TSK_Undeclared;
8062}
8063
8064/// Check whether a specialization is well-formed in the current
8065/// context.
8066///
8067/// This routine determines whether a template specialization can be declared
8068/// in the current context (C++ [temp.expl.spec]p2).
8069///
8070/// \param S the semantic analysis object for which this check is being
8071/// performed.
8072///
8073/// \param Specialized the entity being specialized or instantiated, which
8074/// may be a kind of template (class template, function template, etc.) or
8075/// a member of a class template (member function, static data member,
8076/// member class).
8077///
8078/// \param PrevDecl the previous declaration of this entity, if any.
8079///
8080/// \param Loc the location of the explicit specialization or instantiation of
8081/// this entity.
8082///
8083/// \param IsPartialSpecialization whether this is a partial specialization of
8084/// a class template.
8085///
8086/// \returns true if there was an error that we cannot recover from, false
8087/// otherwise.
8089 NamedDecl *Specialized,
8090 NamedDecl *PrevDecl,
8093 // Keep these "kind" numbers in sync with the %select statements in the
8094 // various diagnostics emitted by this routine.
8095 int EntityKind = 0;
8096 if (isa<ClassTemplateDecl>(Specialized))
8097 EntityKind = IsPartialSpecialization? 1 : 0;
8098 else if (isa<VarTemplateDecl>(Specialized))
8099 EntityKind = IsPartialSpecialization ? 3 : 2;
8100 else if (isa<FunctionTemplateDecl>(Specialized))
8101 EntityKind = 4;
8102 else if (isa<CXXMethodDecl>(Specialized))
8103 EntityKind = 5;
8104 else if (isa<VarDecl>(Specialized))
8105 EntityKind = 6;
8106 else if (isa<RecordDecl>(Specialized))
8107 EntityKind = 7;
8108 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8109 EntityKind = 8;
8110 else {
8111 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8112 << S.getLangOpts().CPlusPlus11;
8113 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8114 return true;
8115 }
8116
8117 // C++ [temp.expl.spec]p2:
8118 // An explicit specialization may be declared in any scope in which
8119 // the corresponding primary template may be defined.
8121 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8122 << Specialized;
8123 return true;
8124 }
8125
8126 // C++ [temp.class.spec]p6:
8127 // A class template partial specialization may be declared in any
8128 // scope in which the primary template may be defined.
8129 DeclContext *SpecializedContext =
8130 Specialized->getDeclContext()->getRedeclContext();
8132
8133 // Make sure that this redeclaration (or definition) occurs in the same
8134 // scope or an enclosing namespace.
8135 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8136 : DC->Equals(SpecializedContext))) {
8137 if (isa<TranslationUnitDecl>(SpecializedContext))
8138 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8139 << EntityKind << Specialized;
8140 else {
8141 auto *ND = cast<NamedDecl>(SpecializedContext);
8142 int Diag = diag::err_template_spec_redecl_out_of_scope;
8143 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8144 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8145 S.Diag(Loc, Diag) << EntityKind << Specialized
8146 << ND << isa<CXXRecordDecl>(ND);
8147 }
8148
8149 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8150
8151 // Don't allow specializing in the wrong class during error recovery.
8152 // Otherwise, things can go horribly wrong.
8153 if (DC->isRecord())
8154 return true;
8155 }
8156
8157 return false;
8158}
8159
8161 if (!E->isTypeDependent())
8162 return SourceLocation();
8163 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8164 Checker.TraverseStmt(E);
8165 if (Checker.MatchLoc.isInvalid())
8166 return E->getSourceRange();
8167 return Checker.MatchLoc;
8168}
8169
8170static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8171 if (!TL.getType()->isDependentType())
8172 return SourceLocation();
8173 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8174 Checker.TraverseTypeLoc(TL);
8175 if (Checker.MatchLoc.isInvalid())
8176 return TL.getSourceRange();
8177 return Checker.MatchLoc;
8178}
8179
8180/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8181/// that checks non-type template partial specialization arguments.
8183 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8184 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8185 for (unsigned I = 0; I != NumArgs; ++I) {
8186 if (Args[I].getKind() == TemplateArgument::Pack) {
8188 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8189 Args[I].pack_size(), IsDefaultArgument))
8190 return true;
8191
8192 continue;
8193 }
8194
8195 if (Args[I].getKind() != TemplateArgument::Expression)
8196 continue;
8197
8198 Expr *ArgExpr = Args[I].getAsExpr();
8199
8200 // We can have a pack expansion of any of the bullets below.
8201 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8202 ArgExpr = Expansion->getPattern();
8203
8204 // Strip off any implicit casts we added as part of type checking.
8205 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8206 ArgExpr = ICE->getSubExpr();
8207
8208 // C++ [temp.class.spec]p8:
8209 // A non-type argument is non-specialized if it is the name of a
8210 // non-type parameter. All other non-type arguments are
8211 // specialized.
8212 //
8213 // Below, we check the two conditions that only apply to
8214 // specialized non-type arguments, so skip any non-specialized
8215 // arguments.
8216 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8217 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8218 continue;
8219
8220 // C++ [temp.class.spec]p9:
8221 // Within the argument list of a class template partial
8222 // specialization, the following restrictions apply:
8223 // -- A partially specialized non-type argument expression
8224 // shall not involve a template parameter of the partial
8225 // specialization except when the argument expression is a
8226 // simple identifier.
8227 // -- The type of a template parameter corresponding to a
8228 // specialized non-type argument shall not be dependent on a
8229 // parameter of the specialization.
8230 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8231 // We implement a compromise between the original rules and DR1315:
8232 // -- A specialized non-type template argument shall not be
8233 // type-dependent and the corresponding template parameter
8234 // shall have a non-dependent type.
8235 SourceRange ParamUseRange =
8236 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8237 if (ParamUseRange.isValid()) {
8238 if (IsDefaultArgument) {
8239 S.Diag(TemplateNameLoc,
8240 diag::err_dependent_non_type_arg_in_partial_spec);
8241 S.Diag(ParamUseRange.getBegin(),
8242 diag::note_dependent_non_type_default_arg_in_partial_spec)
8243 << ParamUseRange;
8244 } else {
8245 S.Diag(ParamUseRange.getBegin(),
8246 diag::err_dependent_non_type_arg_in_partial_spec)
8247 << ParamUseRange;
8248 }
8249 return true;
8250 }
8251
8252 ParamUseRange = findTemplateParameter(
8253 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8254 if (ParamUseRange.isValid()) {
8255 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8256 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8257 << Param->getType();
8259 return true;
8260 }
8261 }
8262
8263 return false;
8264}
8265
8267 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8268 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8269 // We have to be conservative when checking a template in a dependent
8270 // context.
8271 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8272 return false;
8273
8274 TemplateParameterList *TemplateParams =
8275 PrimaryTemplate->getTemplateParameters();
8276 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8278 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8279 if (!Param)
8280 continue;
8281
8282 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8283 Param, &TemplateArgs[I],
8284 1, I >= NumExplicit))
8285 return true;
8286 }
8287
8288 return false;
8289}
8290
8292 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8293 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8295 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8296 assert(TUK != TagUseKind::Reference && "References are not specializations");
8297
8298 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8299 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8300 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8301
8302 // Find the class template we're specializing
8303 TemplateName Name = TemplateId.Template.get();
8305 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8306
8307 if (!ClassTemplate) {
8308 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8309 << (Name.getAsTemplateDecl() &&
8310 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8311 return true;
8312 }
8313
8314 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8315 auto Message = DSA->getMessage();
8316 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8317 << ClassTemplate << !Message.empty() << Message;
8318 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8319 }
8320
8321 if (S->isTemplateParamScope())
8322 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8323
8324 DeclContext *DC = ClassTemplate->getDeclContext();
8325
8326 bool isMemberSpecialization = false;
8327 bool isPartialSpecialization = false;
8328
8329 if (SS.isSet()) {
8330 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8331 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8332 TemplateNameLoc, &TemplateId,
8333 /*IsMemberSpecialization=*/false))
8334 return true;
8335 }
8336
8337 // Check the validity of the template headers that introduce this
8338 // template.
8339 // FIXME: We probably shouldn't complain about these headers for
8340 // friend declarations.
8341 bool Invalid = false;
8342 TemplateParameterList *TemplateParams =
8344 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8345 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8346 if (Invalid)
8347 return true;
8348
8349 // Check that we can declare a template specialization here.
8350 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8351 return true;
8352
8353 if (TemplateParams && DC->isDependentContext()) {
8354 ContextRAII SavedContext(*this, DC);
8356 return true;
8357 }
8358
8359 if (TemplateParams && TemplateParams->size() > 0) {
8360 isPartialSpecialization = true;
8361
8362 if (TUK == TagUseKind::Friend) {
8363 Diag(KWLoc, diag::err_partial_specialization_friend)
8364 << SourceRange(LAngleLoc, RAngleLoc);
8365 return true;
8366 }
8367
8368 // C++ [temp.class.spec]p10:
8369 // The template parameter list of a specialization shall not
8370 // contain default template argument values.
8371 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8372 Decl *Param = TemplateParams->getParam(I);
8373 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8374 if (TTP->hasDefaultArgument()) {
8375 Diag(TTP->getDefaultArgumentLoc(),
8376 diag::err_default_arg_in_partial_spec);
8377 TTP->removeDefaultArgument();
8378 }
8379 } else if (NonTypeTemplateParmDecl *NTTP
8380 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8381 if (NTTP->hasDefaultArgument()) {
8382 Diag(NTTP->getDefaultArgumentLoc(),
8383 diag::err_default_arg_in_partial_spec)
8384 << NTTP->getDefaultArgument().getSourceRange();
8385 NTTP->removeDefaultArgument();
8386 }
8387 } else {
8388 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8389 if (TTP->hasDefaultArgument()) {
8391 diag::err_default_arg_in_partial_spec)
8393 TTP->removeDefaultArgument();
8394 }
8395 }
8396 }
8397 } else if (TemplateParams) {
8398 if (TUK == TagUseKind::Friend)
8399 Diag(KWLoc, diag::err_template_spec_friend)
8401 SourceRange(TemplateParams->getTemplateLoc(),
8402 TemplateParams->getRAngleLoc()))
8403 << SourceRange(LAngleLoc, RAngleLoc);
8404 } else {
8405 assert(TUK == TagUseKind::Friend &&
8406 "should have a 'template<>' for this decl");
8407 }
8408
8409 // Check that the specialization uses the same tag kind as the
8410 // original template.
8412 assert(Kind != TagTypeKind::Enum &&
8413 "Invalid enum tag in class template spec!");
8414 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8415 TUK == TagUseKind::Definition, KWLoc,
8416 ClassTemplate->getIdentifier())) {
8417 Diag(KWLoc, diag::err_use_with_wrong_tag)
8418 << ClassTemplate
8420 ClassTemplate->getTemplatedDecl()->getKindName());
8421 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8422 diag::note_previous_use);
8423 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8424 }
8425
8426 // Translate the parser's template argument list in our AST format.
8427 TemplateArgumentListInfo TemplateArgs =
8428 makeTemplateArgumentListInfo(*this, TemplateId);
8429
8430 // Check for unexpanded parameter packs in any of the template arguments.
8431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8433 isPartialSpecialization
8436 return true;
8437
8438 // Check that the template argument list is well-formed for this
8439 // template.
8440 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8441 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8442 /*DefaultArgs=*/{},
8443 /*PartialTemplateArgs=*/false, SugaredConverted,
8444 CanonicalConverted,
8445 /*UpdateArgsWithConversions=*/true))
8446 return true;
8447
8448 // Find the class template (partial) specialization declaration that
8449 // corresponds to these arguments.
8450 if (isPartialSpecialization) {
8452 TemplateArgs.size(),
8453 CanonicalConverted))
8454 return true;
8455
8456 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8457 // also do it during instantiation.
8458 if (!Name.isDependent() &&
8460 TemplateArgs, CanonicalConverted)) {
8461 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8462 << ClassTemplate->getDeclName();
8463 isPartialSpecialization = false;
8464 Invalid = true;
8465 }
8466 }
8467
8468 void *InsertPos = nullptr;
8469 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8470
8471 if (isPartialSpecialization)
8472 PrevDecl = ClassTemplate->findPartialSpecialization(
8473 CanonicalConverted, TemplateParams, InsertPos);
8474 else
8475 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8476
8478
8479 // Check whether we can declare a class template specialization in
8480 // the current scope.
8481 if (TUK != TagUseKind::Friend &&
8483 TemplateNameLoc,
8484 isPartialSpecialization))
8485 return true;
8486
8487 // The canonical type
8488 QualType CanonType;
8489 if (isPartialSpecialization) {
8490 // Build the canonical type that describes the converted template
8491 // arguments of the class template partial specialization.
8492 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8493 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8494 CanonicalConverted);
8495
8496 if (Context.hasSameType(CanonType,
8497 ClassTemplate->getInjectedClassNameSpecialization()) &&
8498 (!Context.getLangOpts().CPlusPlus20 ||
8499 !TemplateParams->hasAssociatedConstraints())) {
8500 // C++ [temp.class.spec]p9b3:
8501 //
8502 // -- The argument list of the specialization shall not be identical
8503 // to the implicit argument list of the primary template.
8504 //
8505 // This rule has since been removed, because it's redundant given DR1495,
8506 // but we keep it because it produces better diagnostics and recovery.
8507 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8508 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8509 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8510 return CheckClassTemplate(
8511 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8512 TemplateNameLoc, Attr, TemplateParams, AS_none,
8513 /*ModulePrivateLoc=*/SourceLocation(),
8514 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8515 TemplateParameterLists.data());
8516 }
8517
8518 // Create a new class template partial specialization declaration node.
8520 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8523 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8524 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8525 Partial->setTemplateArgsAsWritten(TemplateArgs);
8526 SetNestedNameSpecifier(*this, Partial, SS);
8527 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8529 Context, TemplateParameterLists.drop_back(1));
8530 }
8531
8532 if (!PrevPartial)
8533 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8534 Specialization = Partial;
8535
8536 // If we are providing an explicit specialization of a member class
8537 // template specialization, make a note of that.
8538 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8539 PrevPartial->setMemberSpecialization();
8540
8542 } else {
8543 // Create a new class template specialization declaration node for
8544 // this explicit specialization or friend declaration.
8546 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8547 CanonicalConverted, PrevDecl);
8548 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8550 if (TemplateParameterLists.size() > 0) {
8551 Specialization->setTemplateParameterListsInfo(Context,
8552 TemplateParameterLists);
8553 }
8554
8555 if (!PrevDecl)
8556 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8557
8559 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8560 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8561 CanonicalConverted);
8562 } else {
8564 }
8565 }
8566
8567 // C++ [temp.expl.spec]p6:
8568 // If a template, a member template or the member of a class template is
8569 // explicitly specialized then that specialization shall be declared
8570 // before the first use of that specialization that would cause an implicit
8571 // instantiation to take place, in every translation unit in which such a
8572 // use occurs; no diagnostic is required.
8573 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8574 bool Okay = false;
8575 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8576 // Is there any previous explicit specialization declaration?
8578 Okay = true;
8579 break;
8580 }
8581 }
8582
8583 if (!Okay) {
8584 SourceRange Range(TemplateNameLoc, RAngleLoc);
8585 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8587
8588 Diag(PrevDecl->getPointOfInstantiation(),
8589 diag::note_instantiation_required_here)
8590 << (PrevDecl->getTemplateSpecializationKind()
8592 return true;
8593 }
8594 }
8595
8596 // If this is not a friend, note that this is an explicit specialization.
8597 if (TUK != TagUseKind::Friend)
8598 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8599
8600 // Check that this isn't a redefinition of this specialization.
8601 if (TUK == TagUseKind::Definition) {
8602 RecordDecl *Def = Specialization->getDefinition();
8603 NamedDecl *Hidden = nullptr;
8604 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8605 SkipBody->ShouldSkip = true;
8606 SkipBody->Previous = Def;
8608 } else if (Def) {
8609 SourceRange Range(TemplateNameLoc, RAngleLoc);
8610 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8611 Diag(Def->getLocation(), diag::note_previous_definition);
8612 Specialization->setInvalidDecl();
8613 return true;
8614 }
8615 }
8616
8619
8620 // Add alignment attributes if necessary; these attributes are checked when
8621 // the ASTContext lays out the structure.
8622 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8625 }
8626
8627 if (ModulePrivateLoc.isValid())
8628 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8629 << (isPartialSpecialization? 1 : 0)
8630 << FixItHint::CreateRemoval(ModulePrivateLoc);
8631
8632 // C++ [temp.expl.spec]p9:
8633 // A template explicit specialization is in the scope of the
8634 // namespace in which the template was defined.
8635 //
8636 // We actually implement this paragraph where we set the semantic
8637 // context (in the creation of the ClassTemplateSpecializationDecl),
8638 // but we also maintain the lexical context where the actual
8639 // definition occurs.
8640 Specialization->setLexicalDeclContext(CurContext);
8641
8642 // We may be starting the definition of this specialization.
8643 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8644 Specialization->startDefinition();
8645
8646 if (TUK == TagUseKind::Friend) {
8647 // Build the fully-sugared type for this class template
8648 // specialization as the user wrote in the specialization
8649 // itself. This means that we'll pretty-print the type retrieved
8650 // from the specialization's declaration the way that the user
8651 // actually wrote the specialization, rather than formatting the
8652 // name based on the "canonical" representation used to store the
8653 // template arguments in the specialization.
8655 Name, TemplateNameLoc, TemplateArgs, CanonType);
8657 TemplateNameLoc,
8658 WrittenTy,
8659 /*FIXME:*/KWLoc);
8660 Friend->setAccess(AS_public);
8662 } else {
8663 // Add the specialization into its lexical context, so that it can
8664 // be seen when iterating through the list of declarations in that
8665 // context. However, specializations are not found by name lookup.
8667 }
8668
8669 if (SkipBody && SkipBody->ShouldSkip)
8670 return SkipBody->Previous;
8671
8672 Specialization->setInvalidDecl(Invalid);
8674 return Specialization;
8675}
8676
8678 MultiTemplateParamsArg TemplateParameterLists,
8679 Declarator &D) {
8680 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8681 ActOnDocumentableDecl(NewDecl);
8682 return NewDecl;
8683}
8684
8686 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8687 const IdentifierInfo *Name, SourceLocation NameLoc) {
8688 DeclContext *DC = CurContext;
8689
8690 if (!DC->getRedeclContext()->isFileContext()) {
8691 Diag(NameLoc,
8692 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8693 return nullptr;
8694 }
8695
8696 if (TemplateParameterLists.size() > 1) {
8697 Diag(NameLoc, diag::err_concept_extra_headers);
8698 return nullptr;
8699 }
8700
8701 TemplateParameterList *Params = TemplateParameterLists.front();
8702
8703 if (Params->size() == 0) {
8704 Diag(NameLoc, diag::err_concept_no_parameters);
8705 return nullptr;
8706 }
8707
8708 // Ensure that the parameter pack, if present, is the last parameter in the
8709 // template.
8710 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8711 ParamEnd = Params->end();
8712 ParamIt != ParamEnd; ++ParamIt) {
8713 Decl const *Param = *ParamIt;
8714 if (Param->isParameterPack()) {
8715 if (++ParamIt == ParamEnd)
8716 break;
8717 Diag(Param->getLocation(),
8718 diag::err_template_param_pack_must_be_last_template_parameter);
8719 return nullptr;
8720 }
8721 }
8722
8723 ConceptDecl *NewDecl =
8724 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8725
8726 if (NewDecl->hasAssociatedConstraints()) {
8727 // C++2a [temp.concept]p4:
8728 // A concept shall not have associated constraints.
8729 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8730 NewDecl->setInvalidDecl();
8731 }
8732
8733 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8734 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8736 LookupName(Previous, S);
8737 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8738 /*AllowInlineNamespace*/ false);
8739
8740 // We cannot properly handle redeclarations until we parse the constraint
8741 // expression, so only inject the name if we are sure we are not redeclaring a
8742 // symbol
8743 if (Previous.empty())
8744 PushOnScopeChains(NewDecl, S, true);
8745
8746 return NewDecl;
8747}
8748
8750 bool Found = false;
8752 while (F.hasNext()) {
8753 NamedDecl *D = F.next();
8754 if (D == C) {
8755 F.erase();
8756 Found = true;
8757 break;
8758 }
8759 }
8760 F.done();
8761 return Found;
8762}
8763
8766 Expr *ConstraintExpr,
8767 const ParsedAttributesView &Attrs) {
8768 assert(!C->hasDefinition() && "Concept already defined");
8769 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8770 return nullptr;
8771 C->setDefinition(ConstraintExpr);
8772 ProcessDeclAttributeList(S, C, Attrs);
8773
8774 // Check for conflicting previous declaration.
8775 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8776 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8778 LookupName(Previous, S);
8779 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8780 /*AllowInlineNamespace*/ false);
8781 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8782 bool AddToScope = true;
8783 CheckConceptRedefinition(C, Previous, AddToScope);
8784
8786 if (!WasAlreadyAdded && AddToScope)
8787 PushOnScopeChains(C, S);
8788
8789 return C;
8790}
8791
8793 LookupResult &Previous, bool &AddToScope) {
8794 AddToScope = true;
8795
8796 if (Previous.empty())
8797 return;
8798
8799 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8800 if (!OldConcept) {
8801 auto *Old = Previous.getRepresentativeDecl();
8802 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8803 << NewDecl->getDeclName();
8804 notePreviousDefinition(Old, NewDecl->getLocation());
8805 AddToScope = false;
8806 return;
8807 }
8808 // Check if we can merge with a concept declaration.
8809 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8810 if (!IsSame) {
8811 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8812 << NewDecl->getDeclName();
8813 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8814 AddToScope = false;
8815 return;
8816 }
8817 if (hasReachableDefinition(OldConcept) &&
8818 IsRedefinitionInModule(NewDecl, OldConcept)) {
8819 Diag(NewDecl->getLocation(), diag::err_redefinition)
8820 << NewDecl->getDeclName();
8821 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8822 AddToScope = false;
8823 return;
8824 }
8825 if (!Previous.isSingleResult()) {
8826 // FIXME: we should produce an error in case of ambig and failed lookups.
8827 // Other decls (e.g. namespaces) also have this shortcoming.
8828 return;
8829 }
8830 // We unwrap canonical decl late to check for module visibility.
8831 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8832}
8833
8836 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8837 Diag(Loc, diag::err_recursive_concept) << Concept;
8838 Diag(Concept->getLocation(), diag::note_declared_at);
8839 return true;
8840 }
8841 return false;
8842}
8843
8844/// \brief Strips various properties off an implicit instantiation
8845/// that has just been explicitly specialized.
8846static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8847 if (MinGW || (isa<FunctionDecl>(D) &&
8848 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8849 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8850
8851 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8852 FD->setInlineSpecified(false);
8853}
8854
8855/// Compute the diagnostic location for an explicit instantiation
8856// declaration or definition.
8858 NamedDecl* D, SourceLocation PointOfInstantiation) {
8859 // Explicit instantiations following a specialization have no effect and
8860 // hence no PointOfInstantiation. In that case, walk decl backwards
8861 // until a valid name loc is found.
8862 SourceLocation PrevDiagLoc = PointOfInstantiation;
8863 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8864 Prev = Prev->getPreviousDecl()) {
8865 PrevDiagLoc = Prev->getLocation();
8866 }
8867 assert(PrevDiagLoc.isValid() &&
8868 "Explicit instantiation without point of instantiation?");
8869 return PrevDiagLoc;
8870}
8871
8872bool
8875 NamedDecl *PrevDecl,
8877 SourceLocation PrevPointOfInstantiation,
8878 bool &HasNoEffect) {
8879 HasNoEffect = false;
8880
8881 switch (NewTSK) {
8882 case TSK_Undeclared:
8884 assert(
8885 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8886 "previous declaration must be implicit!");
8887 return false;
8888
8890 switch (PrevTSK) {
8891 case TSK_Undeclared:
8893 // Okay, we're just specializing something that is either already
8894 // explicitly specialized or has merely been mentioned without any
8895 // instantiation.
8896 return false;
8897
8899 if (PrevPointOfInstantiation.isInvalid()) {
8900 // The declaration itself has not actually been instantiated, so it is
8901 // still okay to specialize it.
8903 PrevDecl,
8904 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8905 return false;
8906 }
8907 // Fall through
8908 [[fallthrough]];
8909
8912 assert((PrevTSK == TSK_ImplicitInstantiation ||
8913 PrevPointOfInstantiation.isValid()) &&
8914 "Explicit instantiation without point of instantiation?");
8915
8916 // C++ [temp.expl.spec]p6:
8917 // If a template, a member template or the member of a class template
8918 // is explicitly specialized then that specialization shall be declared
8919 // before the first use of that specialization that would cause an
8920 // implicit instantiation to take place, in every translation unit in
8921 // which such a use occurs; no diagnostic is required.
8922 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8923 // Is there any previous explicit specialization declaration?
8925 return false;
8926 }
8927
8928 Diag(NewLoc, diag::err_specialization_after_instantiation)
8929 << PrevDecl;
8930 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8931 << (PrevTSK != TSK_ImplicitInstantiation);
8932
8933 return true;
8934 }
8935 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8936
8938 switch (PrevTSK) {
8940 // This explicit instantiation declaration is redundant (that's okay).
8941 HasNoEffect = true;
8942 return false;
8943
8944 case TSK_Undeclared:
8946 // We're explicitly instantiating something that may have already been
8947 // implicitly instantiated; that's fine.
8948 return false;
8949
8951 // C++0x [temp.explicit]p4:
8952 // For a given set of template parameters, if an explicit instantiation
8953 // of a template appears after a declaration of an explicit
8954 // specialization for that template, the explicit instantiation has no
8955 // effect.
8956 HasNoEffect = true;
8957 return false;
8958
8960 // C++0x [temp.explicit]p10:
8961 // If an entity is the subject of both an explicit instantiation
8962 // declaration and an explicit instantiation definition in the same
8963 // translation unit, the definition shall follow the declaration.
8964 Diag(NewLoc,
8965 diag::err_explicit_instantiation_declaration_after_definition);
8966
8967 // Explicit instantiations following a specialization have no effect and
8968 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8969 // until a valid name loc is found.
8970 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8971 diag::note_explicit_instantiation_definition_here);
8972 HasNoEffect = true;
8973 return false;
8974 }
8975 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8976
8978 switch (PrevTSK) {
8979 case TSK_Undeclared:
8981 // We're explicitly instantiating something that may have already been
8982 // implicitly instantiated; that's fine.
8983 return false;
8984
8986 // C++ DR 259, C++0x [temp.explicit]p4:
8987 // For a given set of template parameters, if an explicit
8988 // instantiation of a template appears after a declaration of
8989 // an explicit specialization for that template, the explicit
8990 // instantiation has no effect.
8991 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8992 << PrevDecl;
8993 Diag(PrevDecl->getLocation(),
8994 diag::note_previous_template_specialization);
8995 HasNoEffect = true;
8996 return false;
8997
8999 // We're explicitly instantiating a definition for something for which we
9000 // were previously asked to suppress instantiations. That's fine.
9001
9002 // C++0x [temp.explicit]p4:
9003 // For a given set of template parameters, if an explicit instantiation
9004 // of a template appears after a declaration of an explicit
9005 // specialization for that template, the explicit instantiation has no
9006 // effect.
9007 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9008 // Is there any previous explicit specialization declaration?
9010 HasNoEffect = true;
9011 break;
9012 }
9013 }
9014
9015 return false;
9016
9018 // C++0x [temp.spec]p5:
9019 // For a given template and a given set of template-arguments,
9020 // - an explicit instantiation definition shall appear at most once
9021 // in a program,
9022
9023 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9024 Diag(NewLoc, (getLangOpts().MSVCCompat)
9025 ? diag::ext_explicit_instantiation_duplicate
9026 : diag::err_explicit_instantiation_duplicate)
9027 << PrevDecl;
9028 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9029 diag::note_previous_explicit_instantiation);
9030 HasNoEffect = true;
9031 return false;
9032 }
9033 }
9034
9035 llvm_unreachable("Missing specialization/instantiation case?");
9036}
9037
9039 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9041 // Remove anything from Previous that isn't a function template in
9042 // the correct context.
9043 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9044 LookupResult::Filter F = Previous.makeFilter();
9045 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9046 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9047 while (F.hasNext()) {
9049 if (!isa<FunctionTemplateDecl>(D)) {
9050 F.erase();
9051 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9052 continue;
9053 }
9054
9055 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9057 F.erase();
9058 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9059 continue;
9060 }
9061 }
9062 F.done();
9063
9064 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9065 if (Previous.empty()) {
9066 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9067 << IsFriend;
9068 for (auto &P : DiscardedCandidates)
9069 Diag(P.second->getLocation(),
9070 diag::note_dependent_function_template_spec_discard_reason)
9071 << P.first << IsFriend;
9072 return true;
9073 }
9074
9076 ExplicitTemplateArgs);
9077 return false;
9078}
9079
9081 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9082 LookupResult &Previous, bool QualifiedFriend) {
9083 // The set of function template specializations that could match this
9084 // explicit function template specialization.
9085 UnresolvedSet<8> Candidates;
9086 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9087 /*ForTakingAddress=*/false);
9088
9089 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9090 ConvertedTemplateArgs;
9091
9092 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9093 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9094 I != E; ++I) {
9095 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9096 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9097 // Only consider templates found within the same semantic lookup scope as
9098 // FD.
9099 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9101 continue;
9102
9103 QualType FT = FD->getType();
9104 // C++11 [dcl.constexpr]p8:
9105 // A constexpr specifier for a non-static member function that is not
9106 // a constructor declares that member function to be const.
9107 //
9108 // When matching a constexpr member function template specialization
9109 // against the primary template, we don't yet know whether the
9110 // specialization has an implicit 'const' (because we don't know whether
9111 // it will be a static member function until we know which template it
9112 // specializes). This rule was removed in C++14.
9113 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9114 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9115 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9116 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9117 if (OldMD && OldMD->isConst()) {
9118 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9120 EPI.TypeQuals.addConst();
9122 FPT->getParamTypes(), EPI);
9123 }
9124 }
9125
9127 if (ExplicitTemplateArgs)
9128 Args = *ExplicitTemplateArgs;
9129
9130 // C++ [temp.expl.spec]p11:
9131 // A trailing template-argument can be left unspecified in the
9132 // template-id naming an explicit function template specialization
9133 // provided it can be deduced from the function argument type.
9134 // Perform template argument deduction to determine whether we may be
9135 // specializing this template.
9136 // FIXME: It is somewhat wasteful to build
9137 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9138 FunctionDecl *Specialization = nullptr;
9140 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9141 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9143 // Template argument deduction failed; record why it failed, so
9144 // that we can provide nifty diagnostics.
9145 FailedCandidates.addCandidate().set(
9146 I.getPair(), FunTmpl->getTemplatedDecl(),
9147 MakeDeductionFailureInfo(Context, TDK, Info));
9148 (void)TDK;
9149 continue;
9150 }
9151
9152 // Target attributes are part of the cuda function signature, so
9153 // the deduced template's cuda target must match that of the
9154 // specialization. Given that C++ template deduction does not
9155 // take target attributes into account, we reject candidates
9156 // here that have a different target.
9157 if (LangOpts.CUDA &&
9159 /* IgnoreImplicitHDAttr = */ true) !=
9160 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9161 FailedCandidates.addCandidate().set(
9162 I.getPair(), FunTmpl->getTemplatedDecl(),
9165 continue;
9166 }
9167
9168 // Record this candidate.
9169 if (ExplicitTemplateArgs)
9170 ConvertedTemplateArgs[Specialization] = std::move(Args);
9171 Candidates.addDecl(Specialization, I.getAccess());
9172 }
9173 }
9174
9175 // For a qualified friend declaration (with no explicit marker to indicate
9176 // that a template specialization was intended), note all (template and
9177 // non-template) candidates.
9178 if (QualifiedFriend && Candidates.empty()) {
9179 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9180 << FD->getDeclName() << FDLookupContext;
9181 // FIXME: We should form a single candidate list and diagnose all
9182 // candidates at once, to get proper sorting and limiting.
9183 for (auto *OldND : Previous) {
9184 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9185 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9186 }
9187 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9188 return true;
9189 }
9190
9191 // Find the most specialized function template.
9193 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9194 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9195 PDiag(diag::err_function_template_spec_ambiguous)
9196 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9197 PDiag(diag::note_function_template_spec_matched));
9198
9199 if (Result == Candidates.end())
9200 return true;
9201
9202 // Ignore access information; it doesn't figure into redeclaration checking.
9203 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9204
9205 if (const auto *PT = Specialization->getPrimaryTemplate();
9206 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9207 auto Message = DSA->getMessage();
9208 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9209 << PT << !Message.empty() << Message;
9210 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9211 }
9212
9213 // C++23 [except.spec]p13:
9214 // An exception specification is considered to be needed when:
9215 // - [...]
9216 // - the exception specification is compared to that of another declaration
9217 // (e.g., an explicit specialization or an overriding virtual function);
9218 // - [...]
9219 //
9220 // The exception specification of a defaulted function is evaluated as
9221 // described above only when needed; similarly, the noexcept-specifier of a
9222 // specialization of a function template or member function of a class
9223 // template is instantiated only when needed.
9224 //
9225 // The standard doesn't specify what the "comparison with another declaration"
9226 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9227 // not state which properties of an explicit specialization must match the
9228 // primary template.
9229 //
9230 // We assume that an explicit specialization must correspond with (per
9231 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9232 // the declaration produced by substitution into the function template.
9233 //
9234 // Since the determination whether two function declarations correspond does
9235 // not consider exception specification, we only need to instantiate it once
9236 // we determine the primary template when comparing types per
9237 // [basic.link]p11.1.
9238 auto *SpecializationFPT =
9239 Specialization->getType()->castAs<FunctionProtoType>();
9240 // If the function has a dependent exception specification, resolve it after
9241 // we have selected the primary template so we can check whether it matches.
9242 if (getLangOpts().CPlusPlus17 &&
9243 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9244 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9245 return true;
9246
9248 = Specialization->getTemplateSpecializationInfo();
9249 assert(SpecInfo && "Function template specialization info missing?");
9250
9251 // Note: do not overwrite location info if previous template
9252 // specialization kind was explicit.
9254 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9255 Specialization->setLocation(FD->getLocation());
9256 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9257 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9258 // function can differ from the template declaration with respect to
9259 // the constexpr specifier.
9260 // FIXME: We need an update record for this AST mutation.
9261 // FIXME: What if there are multiple such prior declarations (for instance,
9262 // from different modules)?
9263 Specialization->setConstexprKind(FD->getConstexprKind());
9264 }
9265
9266 // FIXME: Check if the prior specialization has a point of instantiation.
9267 // If so, we have run afoul of .
9268
9269 // If this is a friend declaration, then we're not really declaring
9270 // an explicit specialization.
9271 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9272
9273 // Check the scope of this explicit specialization.
9274 if (!isFriend &&
9276 Specialization->getPrimaryTemplate(),
9278 false))
9279 return true;
9280
9281 // C++ [temp.expl.spec]p6:
9282 // If a template, a member template or the member of a class template is
9283 // explicitly specialized then that specialization shall be declared
9284 // before the first use of that specialization that would cause an implicit
9285 // instantiation to take place, in every translation unit in which such a
9286 // use occurs; no diagnostic is required.
9287 bool HasNoEffect = false;
9288 if (!isFriend &&
9293 SpecInfo->getPointOfInstantiation(),
9294 HasNoEffect))
9295 return true;
9296
9297 // Mark the prior declaration as an explicit specialization, so that later
9298 // clients know that this is an explicit specialization.
9299 if (!isFriend) {
9300 // Since explicit specializations do not inherit '=delete' from their
9301 // primary function template - check if the 'specialization' that was
9302 // implicitly generated (during template argument deduction for partial
9303 // ordering) from the most specialized of all the function templates that
9304 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9305 // first check that it was implicitly generated during template argument
9306 // deduction by making sure it wasn't referenced, and then reset the deleted
9307 // flag to not-deleted, so that we can inherit that information from 'FD'.
9308 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9309 !Specialization->getCanonicalDecl()->isReferenced()) {
9310 // FIXME: This assert will not hold in the presence of modules.
9311 assert(
9312 Specialization->getCanonicalDecl() == Specialization &&
9313 "This must be the only existing declaration of this specialization");
9314 // FIXME: We need an update record for this AST mutation.
9315 Specialization->setDeletedAsWritten(false);
9316 }
9317 // FIXME: We need an update record for this AST mutation.
9320 }
9321
9322 // Turn the given function declaration into a function template
9323 // specialization, with the template arguments from the previous
9324 // specialization.
9325 // Take copies of (semantic and syntactic) template argument lists.
9327 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9328 FD->setFunctionTemplateSpecialization(
9329 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9331 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9332
9333 // A function template specialization inherits the target attributes
9334 // of its template. (We require the attributes explicitly in the
9335 // code to match, but a template may have implicit attributes by
9336 // virtue e.g. of being constexpr, and it passes these implicit
9337 // attributes on to its specializations.)
9338 if (LangOpts.CUDA)
9339 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9340
9341 // The "previous declaration" for this function template specialization is
9342 // the prior function template specialization.
9343 Previous.clear();
9344 Previous.addDecl(Specialization);
9345 return false;
9346}
9347
9348bool
9350 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9351 "Only for non-template members");
9352
9353 // Try to find the member we are instantiating.
9354 NamedDecl *FoundInstantiation = nullptr;
9355 NamedDecl *Instantiation = nullptr;
9356 NamedDecl *InstantiatedFrom = nullptr;
9357 MemberSpecializationInfo *MSInfo = nullptr;
9358
9359 if (Previous.empty()) {
9360 // Nowhere to look anyway.
9361 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9362 UnresolvedSet<8> Candidates;
9363 for (NamedDecl *Candidate : Previous) {
9364 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9365 // Ignore any candidates that aren't member functions.
9366 if (!Method)
9367 continue;
9368
9369 QualType Adjusted = Function->getType();
9370 if (!hasExplicitCallingConv(Adjusted))
9371 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9372 // Ignore any candidates with the wrong type.
9373 // This doesn't handle deduced return types, but both function
9374 // declarations should be undeduced at this point.
9375 // FIXME: The exception specification should probably be ignored when
9376 // comparing the types.
9377 if (!Context.hasSameType(Adjusted, Method->getType()))
9378 continue;
9379
9380 // Ignore any candidates with unsatisfied constraints.
9381 if (ConstraintSatisfaction Satisfaction;
9382 Method->getTrailingRequiresClause() &&
9383 (CheckFunctionConstraints(Method, Satisfaction,
9384 /*UsageLoc=*/Member->getLocation(),
9385 /*ForOverloadResolution=*/true) ||
9386 !Satisfaction.IsSatisfied))
9387 continue;
9388
9389 Candidates.addDecl(Candidate);
9390 }
9391
9392 // If we have no viable candidates left after filtering, we are done.
9393 if (Candidates.empty())
9394 return false;
9395
9396 // Find the function that is more constrained than every other function it
9397 // has been compared to.
9398 UnresolvedSetIterator Best = Candidates.begin();
9399 CXXMethodDecl *BestMethod = nullptr;
9400 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9401 I != E; ++I) {
9402 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9403 if (I == Best ||
9404 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9405 Best = I;
9406 BestMethod = Method;
9407 }
9408 }
9409
9410 FoundInstantiation = *Best;
9411 Instantiation = BestMethod;
9412 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9413 MSInfo = BestMethod->getMemberSpecializationInfo();
9414
9415 // Make sure the best candidate is more constrained than all of the others.
9416 bool Ambiguous = false;
9417 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9418 I != E; ++I) {
9419 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9420 if (I != Best &&
9421 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9422 Ambiguous = true;
9423 break;
9424 }
9425 }
9426
9427 if (Ambiguous) {
9428 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9429 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9430 for (NamedDecl *Candidate : Candidates) {
9431 Candidate = Candidate->getUnderlyingDecl();
9432 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9433 << Candidate;
9434 }
9435 return true;
9436 }
9437 } else if (isa<VarDecl>(Member)) {
9438 VarDecl *PrevVar;
9439 if (Previous.isSingleResult() &&
9440 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9441 if (PrevVar->isStaticDataMember()) {
9442 FoundInstantiation = Previous.getRepresentativeDecl();
9443 Instantiation = PrevVar;
9444 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9445 MSInfo = PrevVar->getMemberSpecializationInfo();
9446 }
9447 } else if (isa<RecordDecl>(Member)) {
9448 CXXRecordDecl *PrevRecord;
9449 if (Previous.isSingleResult() &&
9450 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9451 FoundInstantiation = Previous.getRepresentativeDecl();
9452 Instantiation = PrevRecord;
9453 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9454 MSInfo = PrevRecord->getMemberSpecializationInfo();
9455 }
9456 } else if (isa<EnumDecl>(Member)) {
9457 EnumDecl *PrevEnum;
9458 if (Previous.isSingleResult() &&
9459 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9460 FoundInstantiation = Previous.getRepresentativeDecl();
9461 Instantiation = PrevEnum;
9462 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9463 MSInfo = PrevEnum->getMemberSpecializationInfo();
9464 }
9465 }
9466
9467 if (!Instantiation) {
9468 // There is no previous declaration that matches. Since member
9469 // specializations are always out-of-line, the caller will complain about
9470 // this mismatch later.
9471 return false;
9472 }
9473
9474 // A member specialization in a friend declaration isn't really declaring
9475 // an explicit specialization, just identifying a specific (possibly implicit)
9476 // specialization. Don't change the template specialization kind.
9477 //
9478 // FIXME: Is this really valid? Other compilers reject.
9479 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9480 // Preserve instantiation information.
9481 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9482 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9483 cast<CXXMethodDecl>(InstantiatedFrom),
9484 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9485 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9486 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9487 cast<CXXRecordDecl>(InstantiatedFrom),
9488 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9489 }
9490
9491 Previous.clear();
9492 Previous.addDecl(FoundInstantiation);
9493 return false;
9494 }
9495
9496 // Make sure that this is a specialization of a member.
9497 if (!InstantiatedFrom) {
9498 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9499 << Member;
9500 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9501 return true;
9502 }
9503
9504 // C++ [temp.expl.spec]p6:
9505 // If a template, a member template or the member of a class template is
9506 // explicitly specialized then that specialization shall be declared
9507 // before the first use of that specialization that would cause an implicit
9508 // instantiation to take place, in every translation unit in which such a
9509 // use occurs; no diagnostic is required.
9510 assert(MSInfo && "Member specialization info missing?");
9511
9512 bool HasNoEffect = false;
9515 Instantiation,
9517 MSInfo->getPointOfInstantiation(),
9518 HasNoEffect))
9519 return true;
9520
9521 // Check the scope of this explicit specialization.
9523 InstantiatedFrom,
9524 Instantiation, Member->getLocation(),
9525 false))
9526 return true;
9527
9528 // Note that this member specialization is an "instantiation of" the
9529 // corresponding member of the original template.
9530 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9531 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9532 if (InstantiationFunction->getTemplateSpecializationKind() ==
9534 // Explicit specializations of member functions of class templates do not
9535 // inherit '=delete' from the member function they are specializing.
9536 if (InstantiationFunction->isDeleted()) {
9537 // FIXME: This assert will not hold in the presence of modules.
9538 assert(InstantiationFunction->getCanonicalDecl() ==
9539 InstantiationFunction);
9540 // FIXME: We need an update record for this AST mutation.
9541 InstantiationFunction->setDeletedAsWritten(false);
9542 }
9543 }
9544
9545 MemberFunction->setInstantiationOfMemberFunction(
9546 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9547 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9548 MemberVar->setInstantiationOfStaticDataMember(
9549 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9550 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9551 MemberClass->setInstantiationOfMemberClass(
9552 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9553 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9554 MemberEnum->setInstantiationOfMemberEnum(
9555 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9556 } else {
9557 llvm_unreachable("unknown member specialization kind");
9558 }
9559
9560 // Save the caller the trouble of having to figure out which declaration
9561 // this specialization matches.
9562 Previous.clear();
9563 Previous.addDecl(FoundInstantiation);
9564 return false;
9565}
9566
9567/// Complete the explicit specialization of a member of a class template by
9568/// updating the instantiated member to be marked as an explicit specialization.
9569///
9570/// \param OrigD The member declaration instantiated from the template.
9571/// \param Loc The location of the explicit specialization of the member.
9572template<typename DeclT>
9573static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9575 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9576 return;
9577
9578 // FIXME: Inform AST mutation listeners of this AST mutation.
9579 // FIXME: If there are multiple in-class declarations of the member (from
9580 // multiple modules, or a declaration and later definition of a member type),
9581 // should we update all of them?
9582 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9583 OrigD->setLocation(Loc);
9584}
9585
9588 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9589 if (Instantiation == Member)
9590 return;
9591
9592 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9593 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9594 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9595 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9596 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9597 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9598 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9599 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9600 else
9601 llvm_unreachable("unknown member specialization kind");
9602}
9603
9604/// Check the scope of an explicit instantiation.
9605///
9606/// \returns true if a serious error occurs, false otherwise.
9608 SourceLocation InstLoc,
9609 bool WasQualifiedName) {
9611 DeclContext *CurContext = S.CurContext->getRedeclContext();
9612
9613 if (CurContext->isRecord()) {
9614 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9615 << D;
9616 return true;
9617 }
9618
9619 // C++11 [temp.explicit]p3:
9620 // An explicit instantiation shall appear in an enclosing namespace of its
9621 // template. If the name declared in the explicit instantiation is an
9622 // unqualified name, the explicit instantiation shall appear in the
9623 // namespace where its template is declared or, if that namespace is inline
9624 // (7.3.1), any namespace from its enclosing namespace set.
9625 //
9626 // This is DR275, which we do not retroactively apply to C++98/03.
9627 if (WasQualifiedName) {
9628 if (CurContext->Encloses(OrigContext))
9629 return false;
9630 } else {
9631 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9632 return false;
9633 }
9634
9635 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9636 if (WasQualifiedName)
9637 S.Diag(InstLoc,
9638 S.getLangOpts().CPlusPlus11?
9639 diag::err_explicit_instantiation_out_of_scope :
9640 diag::warn_explicit_instantiation_out_of_scope_0x)
9641 << D << NS;
9642 else
9643 S.Diag(InstLoc,
9644 S.getLangOpts().CPlusPlus11?
9645 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9646 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9647 << D << NS;
9648 } else
9649 S.Diag(InstLoc,
9650 S.getLangOpts().CPlusPlus11?
9651 diag::err_explicit_instantiation_must_be_global :
9652 diag::warn_explicit_instantiation_must_be_global_0x)
9653 << D;
9654 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9655 return false;
9656}
9657
9658/// Common checks for whether an explicit instantiation of \p D is valid.
9660 SourceLocation InstLoc,
9661 bool WasQualifiedName,
9663 // C++ [temp.explicit]p13:
9664 // An explicit instantiation declaration shall not name a specialization of
9665 // a template with internal linkage.
9667 D->getFormalLinkage() == Linkage::Internal) {
9668 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9669 return true;
9670 }
9671
9672 // C++11 [temp.explicit]p3: [DR 275]
9673 // An explicit instantiation shall appear in an enclosing namespace of its
9674 // template.
9675 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9676 return true;
9677
9678 return false;
9679}
9680
9681/// Determine whether the given scope specifier has a template-id in it.
9683 if (!SS.isSet())
9684 return false;
9685
9686 // C++11 [temp.explicit]p3:
9687 // If the explicit instantiation is for a member function, a member class
9688 // or a static data member of a class template specialization, the name of
9689 // the class template specialization in the qualified-id for the member
9690 // name shall be a simple-template-id.
9691 //
9692 // C++98 has the same restriction, just worded differently.
9693 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9694 NNS = NNS->getPrefix())
9695 if (const Type *T = NNS->getAsType())
9696 if (isa<TemplateSpecializationType>(T))
9697 return true;
9698
9699 return false;
9700}
9701
9702/// Make a dllexport or dllimport attr on a class template specialization take
9703/// effect.
9706 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9707 assert(A && "dllExportImportClassTemplateSpecialization called "
9708 "on Def without dllexport or dllimport");
9709
9710 // We reject explicit instantiations in class scope, so there should
9711 // never be any delayed exported classes to worry about.
9712 assert(S.DelayedDllExportClasses.empty() &&
9713 "delayed exports present at explicit instantiation");
9715
9716 // Propagate attribute to base class templates.
9717 for (auto &B : Def->bases()) {
9718 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9719 B.getType()->getAsCXXRecordDecl()))
9721 }
9722
9724}
9725
9727 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9728 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9729 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9730 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9731 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9732 // Find the class template we're specializing
9733 TemplateName Name = TemplateD.get();
9734 TemplateDecl *TD = Name.getAsTemplateDecl();
9735 // Check that the specialization uses the same tag kind as the
9736 // original template.
9738 assert(Kind != TagTypeKind::Enum &&
9739 "Invalid enum tag in class template explicit instantiation!");
9740
9741 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9742
9743 if (!ClassTemplate) {
9744 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9745 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9746 << TD << NTK << llvm::to_underlying(Kind);
9747 Diag(TD->getLocation(), diag::note_previous_use);
9748 return true;
9749 }
9750
9751 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9752 Kind, /*isDefinition*/false, KWLoc,
9753 ClassTemplate->getIdentifier())) {
9754 Diag(KWLoc, diag::err_use_with_wrong_tag)
9755 << ClassTemplate
9757 ClassTemplate->getTemplatedDecl()->getKindName());
9758 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9759 diag::note_previous_use);
9760 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9761 }
9762
9763 // C++0x [temp.explicit]p2:
9764 // There are two forms of explicit instantiation: an explicit instantiation
9765 // definition and an explicit instantiation declaration. An explicit
9766 // instantiation declaration begins with the extern keyword. [...]
9767 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9770
9772 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9773 // Check for dllexport class template instantiation declarations,
9774 // except for MinGW mode.
9775 for (const ParsedAttr &AL : Attr) {
9776 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9777 Diag(ExternLoc,
9778 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9779 Diag(AL.getLoc(), diag::note_attribute);
9780 break;
9781 }
9782 }
9783
9784 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9785 Diag(ExternLoc,
9786 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9787 Diag(A->getLocation(), diag::note_attribute);
9788 }
9789 }
9790
9791 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9792 // instantiation declarations for most purposes.
9793 bool DLLImportExplicitInstantiationDef = false;
9796 // Check for dllimport class template instantiation definitions.
9797 bool DLLImport =
9798 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9799 for (const ParsedAttr &AL : Attr) {
9800 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9801 DLLImport = true;
9802 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9803 // dllexport trumps dllimport here.
9804 DLLImport = false;
9805 break;
9806 }
9807 }
9808 if (DLLImport) {
9810 DLLImportExplicitInstantiationDef = true;
9811 }
9812 }
9813
9814 // Translate the parser's template argument list in our AST format.
9815 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9816 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9817
9818 // Check that the template argument list is well-formed for this
9819 // template.
9820 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9821 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9822 /*DefaultArgs=*/{}, false, SugaredConverted,
9823 CanonicalConverted,
9824 /*UpdateArgsWithConversions=*/true))
9825 return true;
9826
9827 // Find the class template specialization declaration that
9828 // corresponds to these arguments.
9829 void *InsertPos = nullptr;
9831 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9832
9833 TemplateSpecializationKind PrevDecl_TSK
9834 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9835
9836 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9837 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9838 // Check for dllexport class template instantiation definitions in MinGW
9839 // mode, if a previous declaration of the instantiation was seen.
9840 for (const ParsedAttr &AL : Attr) {
9841 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9842 Diag(AL.getLoc(),
9843 diag::warn_attribute_dllexport_explicit_instantiation_def);
9844 break;
9845 }
9846 }
9847 }
9848
9849 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9850 SS.isSet(), TSK))
9851 return true;
9852
9854
9855 bool HasNoEffect = false;
9856 if (PrevDecl) {
9857 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9858 PrevDecl, PrevDecl_TSK,
9859 PrevDecl->getPointOfInstantiation(),
9860 HasNoEffect))
9861 return PrevDecl;
9862
9863 // Even though HasNoEffect == true means that this explicit instantiation
9864 // has no effect on semantics, we go on to put its syntax in the AST.
9865
9866 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9867 PrevDecl_TSK == TSK_Undeclared) {
9868 // Since the only prior class template specialization with these
9869 // arguments was referenced but not declared, reuse that
9870 // declaration node as our own, updating the source location
9871 // for the template name to reflect our new declaration.
9872 // (Other source locations will be updated later.)
9873 Specialization = PrevDecl;
9874 Specialization->setLocation(TemplateNameLoc);
9875 PrevDecl = nullptr;
9876 }
9877
9878 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9879 DLLImportExplicitInstantiationDef) {
9880 // The new specialization might add a dllimport attribute.
9881 HasNoEffect = false;
9882 }
9883 }
9884
9885 if (!Specialization) {
9886 // Create a new class template specialization declaration node for
9887 // this explicit specialization.
9889 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9890 ClassTemplate, CanonicalConverted, PrevDecl);
9892
9893 // A MSInheritanceAttr attached to the previous declaration must be
9894 // propagated to the new node prior to instantiation.
9895 if (PrevDecl) {
9896 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9897 auto *Clone = A->clone(getASTContext());
9898 Clone->setInherited(true);
9899 Specialization->addAttr(Clone);
9901 }
9902 }
9903
9904 if (!HasNoEffect && !PrevDecl) {
9905 // Insert the new specialization.
9906 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9907 }
9908 }
9909
9910 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9911
9912 // Set source locations for keywords.
9913 Specialization->setExternKeywordLoc(ExternLoc);
9914 Specialization->setTemplateKeywordLoc(TemplateLoc);
9915 Specialization->setBraceRange(SourceRange());
9916
9917 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9920
9921 // Add the explicit instantiation into its lexical context. However,
9922 // since explicit instantiations are never found by name lookup, we
9923 // just put it into the declaration context directly.
9924 Specialization->setLexicalDeclContext(CurContext);
9926
9927 // Syntax is now OK, so return if it has no other effect on semantics.
9928 if (HasNoEffect) {
9929 // Set the template specialization kind.
9930 Specialization->setTemplateSpecializationKind(TSK);
9931 return Specialization;
9932 }
9933
9934 // C++ [temp.explicit]p3:
9935 // A definition of a class template or class member template
9936 // shall be in scope at the point of the explicit instantiation of
9937 // the class template or class member template.
9938 //
9939 // This check comes when we actually try to perform the
9940 // instantiation.
9942 = cast_or_null<ClassTemplateSpecializationDecl>(
9943 Specialization->getDefinition());
9944 if (!Def)
9946 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9947 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9948 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9949 }
9950
9951 // Instantiate the members of this class template specialization.
9952 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9953 Specialization->getDefinition());
9954 if (Def) {
9956 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9957 // TSK_ExplicitInstantiationDefinition
9958 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9960 DLLImportExplicitInstantiationDef)) {
9961 // FIXME: Need to notify the ASTMutationListener that we did this.
9963
9964 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9966 // An explicit instantiation definition can add a dll attribute to a
9967 // template with a previous instantiation declaration. MinGW doesn't
9968 // allow this.
9969 auto *A = cast<InheritableAttr>(
9971 A->setInherited(true);
9972 Def->addAttr(A);
9974 }
9975 }
9976
9977 // Fix a TSK_ImplicitInstantiation followed by a
9978 // TSK_ExplicitInstantiationDefinition
9979 bool NewlyDLLExported =
9980 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9981 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9983 // An explicit instantiation definition can add a dll attribute to a
9984 // template with a previous implicit instantiation. MinGW doesn't allow
9985 // this. We limit clang to only adding dllexport, to avoid potentially
9986 // strange codegen behavior. For example, if we extend this conditional
9987 // to dllimport, and we have a source file calling a method on an
9988 // implicitly instantiated template class instance and then declaring a
9989 // dllimport explicit instantiation definition for the same template
9990 // class, the codegen for the method call will not respect the dllimport,
9991 // while it will with cl. The Def will already have the DLL attribute,
9992 // since the Def and Specialization will be the same in the case of
9993 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9994 // attribute to the Specialization; we just need to make it take effect.
9995 assert(Def == Specialization &&
9996 "Def and Specialization should match for implicit instantiation");
9998 }
9999
10000 // In MinGW mode, export the template instantiation if the declaration
10001 // was marked dllexport.
10002 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10003 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10004 PrevDecl->hasAttr<DLLExportAttr>()) {
10006 }
10007
10008 // Set the template specialization kind. Make sure it is set before
10009 // instantiating the members which will trigger ASTConsumer callbacks.
10010 Specialization->setTemplateSpecializationKind(TSK);
10011 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10012 } else {
10013
10014 // Set the template specialization kind.
10015 Specialization->setTemplateSpecializationKind(TSK);
10016 }
10017
10018 return Specialization;
10019}
10020
10023 SourceLocation TemplateLoc, unsigned TagSpec,
10024 SourceLocation KWLoc, CXXScopeSpec &SS,
10025 IdentifierInfo *Name, SourceLocation NameLoc,
10026 const ParsedAttributesView &Attr) {
10027
10028 bool Owned = false;
10029 bool IsDependent = false;
10030 Decl *TagD =
10031 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10032 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10033 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10034 false, TypeResult(), /*IsTypeSpecifier*/ false,
10035 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10036 .get();
10037 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10038
10039 if (!TagD)
10040 return true;
10041
10042 TagDecl *Tag = cast<TagDecl>(TagD);
10043 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10044
10045 if (Tag->isInvalidDecl())
10046 return true;
10047
10048 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10050 if (!Pattern) {
10051 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10053 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10054 return true;
10055 }
10056
10057 // C++0x [temp.explicit]p2:
10058 // If the explicit instantiation is for a class or member class, the
10059 // elaborated-type-specifier in the declaration shall include a
10060 // simple-template-id.
10061 //
10062 // C++98 has the same restriction, just worded differently.
10064 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10065 << Record << SS.getRange();
10066
10067 // C++0x [temp.explicit]p2:
10068 // There are two forms of explicit instantiation: an explicit instantiation
10069 // definition and an explicit instantiation declaration. An explicit
10070 // instantiation declaration begins with the extern keyword. [...]
10074
10075 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10076
10077 // Verify that it is okay to explicitly instantiate here.
10078 CXXRecordDecl *PrevDecl
10079 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10080 if (!PrevDecl && Record->getDefinition())
10081 PrevDecl = Record;
10082 if (PrevDecl) {
10084 bool HasNoEffect = false;
10085 assert(MSInfo && "No member specialization information?");
10086 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10087 PrevDecl,
10089 MSInfo->getPointOfInstantiation(),
10090 HasNoEffect))
10091 return true;
10092 if (HasNoEffect)
10093 return TagD;
10094 }
10095
10096 CXXRecordDecl *RecordDef
10097 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10098 if (!RecordDef) {
10099 // C++ [temp.explicit]p3:
10100 // A definition of a member class of a class template shall be in scope
10101 // at the point of an explicit instantiation of the member class.
10102 CXXRecordDecl *Def
10103 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10104 if (!Def) {
10105 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10106 << 0 << Record->getDeclName() << Record->getDeclContext();
10107 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10108 << Pattern;
10109 return true;
10110 } else {
10111 if (InstantiateClass(NameLoc, Record, Def,
10113 TSK))
10114 return true;
10115
10116 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10117 if (!RecordDef)
10118 return true;
10119 }
10120 }
10121
10122 // Instantiate all of the members of the class.
10123 InstantiateClassMembers(NameLoc, RecordDef,
10125
10127 MarkVTableUsed(NameLoc, RecordDef, true);
10128
10129 // FIXME: We don't have any representation for explicit instantiations of
10130 // member classes. Such a representation is not needed for compilation, but it
10131 // should be available for clients that want to see all of the declarations in
10132 // the source code.
10133 return TagD;
10134}
10135
10137 SourceLocation ExternLoc,
10138 SourceLocation TemplateLoc,
10139 Declarator &D) {
10140 // Explicit instantiations always require a name.
10141 // TODO: check if/when DNInfo should replace Name.
10143 DeclarationName Name = NameInfo.getName();
10144 if (!Name) {
10145 if (!D.isInvalidType())
10146 Diag(D.getDeclSpec().getBeginLoc(),
10147 diag::err_explicit_instantiation_requires_name)
10148 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10149
10150 return true;
10151 }
10152
10153 // Get the innermost enclosing declaration scope.
10154 S = S->getDeclParent();
10155
10156 // Determine the type of the declaration.
10158 QualType R = T->getType();
10159 if (R.isNull())
10160 return true;
10161
10162 // C++ [dcl.stc]p1:
10163 // A storage-class-specifier shall not be specified in [...] an explicit
10164 // instantiation (14.7.2) directive.
10165 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10166 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10167 << Name;
10168 return true;
10169 } else if (D.getDeclSpec().getStorageClassSpec()
10171 // Complain about then remove the storage class specifier.
10172 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10173 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10174
10175 D.getMutableDeclSpec().ClearStorageClassSpecs();
10176 }
10177
10178 // C++0x [temp.explicit]p1:
10179 // [...] An explicit instantiation of a function template shall not use the
10180 // inline or constexpr specifiers.
10181 // Presumably, this also applies to member functions of class templates as
10182 // well.
10183 if (D.getDeclSpec().isInlineSpecified())
10184 Diag(D.getDeclSpec().getInlineSpecLoc(),
10186 diag::err_explicit_instantiation_inline :
10187 diag::warn_explicit_instantiation_inline_0x)
10188 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10189 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10190 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10191 // not already specified.
10192 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10193 diag::err_explicit_instantiation_constexpr);
10194
10195 // A deduction guide is not on the list of entities that can be explicitly
10196 // instantiated.
10197 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10198 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10199 << /*explicit instantiation*/ 0;
10200 return true;
10201 }
10202
10203 // C++0x [temp.explicit]p2:
10204 // There are two forms of explicit instantiation: an explicit instantiation
10205 // definition and an explicit instantiation declaration. An explicit
10206 // instantiation declaration begins with the extern keyword. [...]
10210
10211 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10212 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10213 /*ObjectType=*/QualType());
10214
10215 if (!R->isFunctionType()) {
10216 // C++ [temp.explicit]p1:
10217 // A [...] static data member of a class template can be explicitly
10218 // instantiated from the member definition associated with its class
10219 // template.
10220 // C++1y [temp.explicit]p1:
10221 // A [...] variable [...] template specialization can be explicitly
10222 // instantiated from its template.
10223 if (Previous.isAmbiguous())
10224 return true;
10225
10226 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10227 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10228
10229 if (!PrevTemplate) {
10230 if (!Prev || !Prev->isStaticDataMember()) {
10231 // We expect to see a static data member here.
10232 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10233 << Name;
10234 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10235 P != PEnd; ++P)
10236 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10237 return true;
10238 }
10239
10241 // FIXME: Check for explicit specialization?
10242 Diag(D.getIdentifierLoc(),
10243 diag::err_explicit_instantiation_data_member_not_instantiated)
10244 << Prev;
10245 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10246 // FIXME: Can we provide a note showing where this was declared?
10247 return true;
10248 }
10249 } else {
10250 // Explicitly instantiate a variable template.
10251
10252 // C++1y [dcl.spec.auto]p6:
10253 // ... A program that uses auto or decltype(auto) in a context not
10254 // explicitly allowed in this section is ill-formed.
10255 //
10256 // This includes auto-typed variable template instantiations.
10257 if (R->isUndeducedType()) {
10258 Diag(T->getTypeLoc().getBeginLoc(),
10259 diag::err_auto_not_allowed_var_inst);
10260 return true;
10261 }
10262
10263 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10264 // C++1y [temp.explicit]p3:
10265 // If the explicit instantiation is for a variable, the unqualified-id
10266 // in the declaration shall be a template-id.
10267 Diag(D.getIdentifierLoc(),
10268 diag::err_explicit_instantiation_without_template_id)
10269 << PrevTemplate;
10270 Diag(PrevTemplate->getLocation(),
10271 diag::note_explicit_instantiation_here);
10272 return true;
10273 }
10274
10275 // Translate the parser's template argument list into our AST format.
10276 TemplateArgumentListInfo TemplateArgs =
10277 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10278
10279 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10280 D.getIdentifierLoc(), TemplateArgs);
10281 if (Res.isInvalid())
10282 return true;
10283
10284 if (!Res.isUsable()) {
10285 // We somehow specified dependent template arguments in an explicit
10286 // instantiation. This should probably only happen during error
10287 // recovery.
10288 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10289 return true;
10290 }
10291
10292 // Ignore access control bits, we don't need them for redeclaration
10293 // checking.
10294 Prev = cast<VarDecl>(Res.get());
10295 }
10296
10297 // C++0x [temp.explicit]p2:
10298 // If the explicit instantiation is for a member function, a member class
10299 // or a static data member of a class template specialization, the name of
10300 // the class template specialization in the qualified-id for the member
10301 // name shall be a simple-template-id.
10302 //
10303 // C++98 has the same restriction, just worded differently.
10304 //
10305 // This does not apply to variable template specializations, where the
10306 // template-id is in the unqualified-id instead.
10307 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10308 Diag(D.getIdentifierLoc(),
10309 diag::ext_explicit_instantiation_without_qualified_id)
10310 << Prev << D.getCXXScopeSpec().getRange();
10311
10312 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10313
10314 // Verify that it is okay to explicitly instantiate here.
10317 bool HasNoEffect = false;
10318 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10319 PrevTSK, POI, HasNoEffect))
10320 return true;
10321
10322 if (!HasNoEffect) {
10323 // Instantiate static data member or variable template.
10324 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10325 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10326 VTSD->setExternKeywordLoc(ExternLoc);
10327 VTSD->setTemplateKeywordLoc(TemplateLoc);
10328 }
10329
10330 // Merge attributes.
10331 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10332 if (PrevTemplate)
10333 ProcessAPINotes(Prev);
10334
10336 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10337 }
10338
10339 // Check the new variable specialization against the parsed input.
10340 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10341 Diag(T->getTypeLoc().getBeginLoc(),
10342 diag::err_invalid_var_template_spec_type)
10343 << 0 << PrevTemplate << R << Prev->getType();
10344 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10345 << 2 << PrevTemplate->getDeclName();
10346 return true;
10347 }
10348
10349 // FIXME: Create an ExplicitInstantiation node?
10350 return (Decl*) nullptr;
10351 }
10352
10353 // If the declarator is a template-id, translate the parser's template
10354 // argument list into our AST format.
10355 bool HasExplicitTemplateArgs = false;
10356 TemplateArgumentListInfo TemplateArgs;
10357 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10358 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10359 HasExplicitTemplateArgs = true;
10360 }
10361
10362 // C++ [temp.explicit]p1:
10363 // A [...] function [...] can be explicitly instantiated from its template.
10364 // A member function [...] of a class template can be explicitly
10365 // instantiated from the member definition associated with its class
10366 // template.
10367 UnresolvedSet<8> TemplateMatches;
10368 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10370 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10371 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10372 P != PEnd; ++P) {
10373 NamedDecl *Prev = *P;
10374 if (!HasExplicitTemplateArgs) {
10375 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10376 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10377 /*AdjustExceptionSpec*/true);
10378 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10379 if (Method->getPrimaryTemplate()) {
10380 TemplateMatches.addDecl(Method, P.getAccess());
10381 } else {
10382 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10383 C.FoundDecl = P.getPair();
10384 C.Function = Method;
10385 C.Viable = true;
10387 if (Method->getTrailingRequiresClause() &&
10388 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10389 /*ForOverloadResolution=*/true) ||
10390 !S.IsSatisfied)) {
10391 C.Viable = false;
10393 }
10394 }
10395 }
10396 }
10397 }
10398
10399 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10400 if (!FunTmpl)
10401 continue;
10402
10403 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10404 FunctionDecl *Specialization = nullptr;
10406 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10407 Specialization, Info);
10409 // Keep track of almost-matches.
10410 FailedTemplateCandidates.addCandidate().set(
10411 P.getPair(), FunTmpl->getTemplatedDecl(),
10412 MakeDeductionFailureInfo(Context, TDK, Info));
10413 (void)TDK;
10414 continue;
10415 }
10416
10417 // Target attributes are part of the cuda function signature, so
10418 // the cuda target of the instantiated function must match that of its
10419 // template. Given that C++ template deduction does not take
10420 // target attributes into account, we reject candidates here that
10421 // have a different target.
10422 if (LangOpts.CUDA &&
10424 /* IgnoreImplicitHDAttr = */ true) !=
10425 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10426 FailedTemplateCandidates.addCandidate().set(
10427 P.getPair(), FunTmpl->getTemplatedDecl(),
10430 continue;
10431 }
10432
10433 TemplateMatches.addDecl(Specialization, P.getAccess());
10434 }
10435
10436 FunctionDecl *Specialization = nullptr;
10437 if (!NonTemplateMatches.empty()) {
10438 unsigned Msg = 0;
10439 OverloadCandidateDisplayKind DisplayKind;
10441 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10442 Best)) {
10443 case OR_Success:
10444 case OR_Deleted:
10445 Specialization = cast<FunctionDecl>(Best->Function);
10446 break;
10447 case OR_Ambiguous:
10448 Msg = diag::err_explicit_instantiation_ambiguous;
10449 DisplayKind = OCD_AmbiguousCandidates;
10450 break;
10452 Msg = diag::err_explicit_instantiation_no_candidate;
10453 DisplayKind = OCD_AllCandidates;
10454 break;
10455 }
10456 if (Msg) {
10457 PartialDiagnostic Diag = PDiag(Msg) << Name;
10458 NonTemplateMatches.NoteCandidates(
10459 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10460 {});
10461 return true;
10462 }
10463 }
10464
10465 if (!Specialization) {
10466 // Find the most specialized function template specialization.
10468 TemplateMatches.begin(), TemplateMatches.end(),
10469 FailedTemplateCandidates, D.getIdentifierLoc(),
10470 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10471 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10472 PDiag(diag::note_explicit_instantiation_candidate));
10473
10474 if (Result == TemplateMatches.end())
10475 return true;
10476
10477 // Ignore access control bits, we don't need them for redeclaration checking.
10478 Specialization = cast<FunctionDecl>(*Result);
10479 }
10480
10481 // C++11 [except.spec]p4
10482 // In an explicit instantiation an exception-specification may be specified,
10483 // but is not required.
10484 // If an exception-specification is specified in an explicit instantiation
10485 // directive, it shall be compatible with the exception-specifications of
10486 // other declarations of that function.
10487 if (auto *FPT = R->getAs<FunctionProtoType>())
10488 if (FPT->hasExceptionSpec()) {
10489 unsigned DiagID =
10490 diag::err_mismatched_exception_spec_explicit_instantiation;
10491 if (getLangOpts().MicrosoftExt)
10492 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10494 PDiag(DiagID) << Specialization->getType(),
10495 PDiag(diag::note_explicit_instantiation_here),
10496 Specialization->getType()->getAs<FunctionProtoType>(),
10497 Specialization->getLocation(), FPT, D.getBeginLoc());
10498 // In Microsoft mode, mismatching exception specifications just cause a
10499 // warning.
10500 if (!getLangOpts().MicrosoftExt && Result)
10501 return true;
10502 }
10503
10504 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10505 Diag(D.getIdentifierLoc(),
10506 diag::err_explicit_instantiation_member_function_not_instantiated)
10508 << (Specialization->getTemplateSpecializationKind() ==
10510 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10511 return true;
10512 }
10513
10514 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10515 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10516 PrevDecl = Specialization;
10517
10518 if (PrevDecl) {
10519 bool HasNoEffect = false;
10520 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10521 PrevDecl,
10523 PrevDecl->getPointOfInstantiation(),
10524 HasNoEffect))
10525 return true;
10526
10527 // FIXME: We may still want to build some representation of this
10528 // explicit specialization.
10529 if (HasNoEffect)
10530 return (Decl*) nullptr;
10531 }
10532
10533 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10534 // functions
10535 // valarray<size_t>::valarray(size_t) and
10536 // valarray<size_t>::~valarray()
10537 // that it declared to have internal linkage with the internal_linkage
10538 // attribute. Ignore the explicit instantiation declaration in this case.
10539 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10541 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10542 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10543 RD->isInStdNamespace())
10544 return (Decl*) nullptr;
10545 }
10546
10547 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10549
10550 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10551 // instantiation declarations.
10553 Specialization->hasAttr<DLLImportAttr>() &&
10556
10557 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10558
10559 if (Specialization->isDefined()) {
10560 // Let the ASTConsumer know that this function has been explicitly
10561 // instantiated now, and its linkage might have changed.
10563 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10564 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10565
10566 // C++0x [temp.explicit]p2:
10567 // If the explicit instantiation is for a member function, a member class
10568 // or a static data member of a class template specialization, the name of
10569 // the class template specialization in the qualified-id for the member
10570 // name shall be a simple-template-id.
10571 //
10572 // C++98 has the same restriction, just worded differently.
10573 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10574 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10575 D.getCXXScopeSpec().isSet() &&
10576 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10577 Diag(D.getIdentifierLoc(),
10578 diag::ext_explicit_instantiation_without_qualified_id)
10579 << Specialization << D.getCXXScopeSpec().getRange();
10580
10582 *this,
10583 FunTmpl ? (NamedDecl *)FunTmpl
10584 : Specialization->getInstantiatedFromMemberFunction(),
10585 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10586
10587 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10588 return (Decl*) nullptr;
10589}
10590
10592 const CXXScopeSpec &SS,
10593 const IdentifierInfo *Name,
10594 SourceLocation TagLoc,
10595 SourceLocation NameLoc) {
10596 // This has to hold, because SS is expected to be defined.
10597 assert(Name && "Expected a name in a dependent tag");
10598
10599 NestedNameSpecifier *NNS = SS.getScopeRep();
10600 if (!NNS)
10601 return true;
10602
10604
10605 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10606 Diag(NameLoc, diag::err_dependent_tag_decl)
10607 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10608 << SS.getRange();
10609 return true;
10610 }
10611
10612 // Create the resulting type.
10614 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10615
10616 // Create type-source location information for this type.
10617 TypeLocBuilder TLB;
10619 TL.setElaboratedKeywordLoc(TagLoc);
10621 TL.setNameLoc(NameLoc);
10623}
10624
10626 const CXXScopeSpec &SS,
10627 const IdentifierInfo &II,
10628 SourceLocation IdLoc,
10629 ImplicitTypenameContext IsImplicitTypename) {
10630 if (SS.isInvalid())
10631 return true;
10632
10633 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10634 Diag(TypenameLoc,
10636 diag::warn_cxx98_compat_typename_outside_of_template :
10637 diag::ext_typename_outside_of_template)
10638 << FixItHint::CreateRemoval(TypenameLoc);
10639
10641 TypeSourceInfo *TSI = nullptr;
10642 QualType T =
10643 CheckTypenameType((TypenameLoc.isValid() ||
10644 IsImplicitTypename == ImplicitTypenameContext::Yes)
10647 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10648 /*DeducedTSTContext=*/true);
10649 if (T.isNull())
10650 return true;
10651 return CreateParsedType(T, TSI);
10652}
10653
10656 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10657 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10658 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10659 ASTTemplateArgsPtr TemplateArgsIn,
10660 SourceLocation RAngleLoc) {
10661 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10662 Diag(TypenameLoc,
10664 diag::warn_cxx98_compat_typename_outside_of_template :
10665 diag::ext_typename_outside_of_template)
10666 << FixItHint::CreateRemoval(TypenameLoc);
10667
10668 // Strangely, non-type results are not ignored by this lookup, so the
10669 // program is ill-formed if it finds an injected-class-name.
10670 if (TypenameLoc.isValid()) {
10671 auto *LookupRD =
10672 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10673 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10674 Diag(TemplateIILoc,
10675 diag::ext_out_of_line_qualified_id_type_names_constructor)
10676 << TemplateII << 0 /*injected-class-name used as template name*/
10677 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10678 }
10679 }
10680
10681 // Translate the parser's template argument list in our AST format.
10682 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10683 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10684
10685 TemplateName Template = TemplateIn.get();
10686 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10687 // Construct a dependent template specialization type.
10688 assert(DTN && "dependent template has non-dependent name?");
10689 assert(DTN->getQualifier() == SS.getScopeRep());
10690
10691 if (!DTN->isIdentifier()) {
10692 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10693 NoteAllFoundTemplates(Template);
10694 return true;
10695 }
10696
10698 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10699 DTN->getIdentifier(), TemplateArgs.arguments());
10700
10701 // Create source-location information for this type.
10702 TypeLocBuilder Builder;
10705 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10707 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10708 SpecTL.setTemplateNameLoc(TemplateIILoc);
10709 SpecTL.setLAngleLoc(LAngleLoc);
10710 SpecTL.setRAngleLoc(RAngleLoc);
10711 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10712 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10713 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10714 }
10715
10716 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10717 if (T.isNull())
10718 return true;
10719
10720 // Provide source-location information for the template specialization type.
10721 TypeLocBuilder Builder;
10723 = Builder.push<TemplateSpecializationTypeLoc>(T);
10724 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10725 SpecTL.setTemplateNameLoc(TemplateIILoc);
10726 SpecTL.setLAngleLoc(LAngleLoc);
10727 SpecTL.setRAngleLoc(RAngleLoc);
10728 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10729 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10730
10732 SS.getScopeRep(), T);
10733 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10734 TL.setElaboratedKeywordLoc(TypenameLoc);
10736
10737 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10738 return CreateParsedType(T, TSI);
10739}
10740
10741/// Determine whether this failed name lookup should be treated as being
10742/// disabled by a usage of std::enable_if.
10744 SourceRange &CondRange, Expr *&Cond) {
10745 // We must be looking for a ::type...
10746 if (!II.isStr("type"))
10747 return false;
10748
10749 // ... within an explicitly-written template specialization...
10750 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10751 return false;
10752 TypeLoc EnableIfTy = NNS.getTypeLoc();
10753 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10755 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10756 return false;
10757 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10758
10759 // ... which names a complete class template declaration...
10760 const TemplateDecl *EnableIfDecl =
10761 EnableIfTST->getTemplateName().getAsTemplateDecl();
10762 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10763 return false;
10764
10765 // ... called "enable_if".
10766 const IdentifierInfo *EnableIfII =
10767 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10768 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10769 return false;
10770
10771 // Assume the first template argument is the condition.
10772 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10773
10774 // Dig out the condition.
10775 Cond = nullptr;
10776 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10778 return true;
10779
10780 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10781
10782 // Ignore Boolean literals; they add no value.
10783 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10784 Cond = nullptr;
10785
10786 return true;
10787}
10788
10791 SourceLocation KeywordLoc,
10792 NestedNameSpecifierLoc QualifierLoc,
10793 const IdentifierInfo &II,
10794 SourceLocation IILoc,
10795 TypeSourceInfo **TSI,
10796 bool DeducedTSTContext) {
10797 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10798 DeducedTSTContext);
10799 if (T.isNull())
10800 return QualType();
10801
10803 if (isa<DependentNameType>(T)) {
10805 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10806 TL.setElaboratedKeywordLoc(KeywordLoc);
10807 TL.setQualifierLoc(QualifierLoc);
10808 TL.setNameLoc(IILoc);
10809 } else {
10810 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10811 TL.setElaboratedKeywordLoc(KeywordLoc);
10812 TL.setQualifierLoc(QualifierLoc);
10813 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10814 }
10815 return T;
10816}
10817
10818/// Build the type that describes a C++ typename specifier,
10819/// e.g., "typename T::type".
10822 SourceLocation KeywordLoc,
10823 NestedNameSpecifierLoc QualifierLoc,
10824 const IdentifierInfo &II,
10825 SourceLocation IILoc, bool DeducedTSTContext) {
10826 CXXScopeSpec SS;
10827 SS.Adopt(QualifierLoc);
10828
10829 DeclContext *Ctx = nullptr;
10830 if (QualifierLoc) {
10831 Ctx = computeDeclContext(SS);
10832 if (!Ctx) {
10833 // If the nested-name-specifier is dependent and couldn't be
10834 // resolved to a type, build a typename type.
10835 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10836 return Context.getDependentNameType(Keyword,
10837 QualifierLoc.getNestedNameSpecifier(),
10838 &II);
10839 }
10840
10841 // If the nested-name-specifier refers to the current instantiation,
10842 // the "typename" keyword itself is superfluous. In C++03, the
10843 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10844 // allows such extraneous "typename" keywords, and we retroactively
10845 // apply this DR to C++03 code with only a warning. In any case we continue.
10846
10847 if (RequireCompleteDeclContext(SS, Ctx))
10848 return QualType();
10849 }
10850
10851 DeclarationName Name(&II);
10852 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10853 if (Ctx)
10854 LookupQualifiedName(Result, Ctx, SS);
10855 else
10856 LookupName(Result, CurScope);
10857 unsigned DiagID = 0;
10858 Decl *Referenced = nullptr;
10859 switch (Result.getResultKind()) {
10861 // If we're looking up 'type' within a template named 'enable_if', produce
10862 // a more specific diagnostic.
10863 SourceRange CondRange;
10864 Expr *Cond = nullptr;
10865 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10866 // If we have a condition, narrow it down to the specific failed
10867 // condition.
10868 if (Cond) {
10869 Expr *FailedCond;
10870 std::string FailedDescription;
10871 std::tie(FailedCond, FailedDescription) =
10873
10874 Diag(FailedCond->getExprLoc(),
10875 diag::err_typename_nested_not_found_requirement)
10876 << FailedDescription
10877 << FailedCond->getSourceRange();
10878 return QualType();
10879 }
10880
10881 Diag(CondRange.getBegin(),
10882 diag::err_typename_nested_not_found_enable_if)
10883 << Ctx << CondRange;
10884 return QualType();
10885 }
10886
10887 DiagID = Ctx ? diag::err_typename_nested_not_found
10888 : diag::err_unknown_typename;
10889 break;
10890 }
10891
10893 // We found a using declaration that is a value. Most likely, the using
10894 // declaration itself is meant to have the 'typename' keyword.
10895 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10896 IILoc);
10897 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10898 << Name << Ctx << FullRange;
10899 if (UnresolvedUsingValueDecl *Using
10900 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10901 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10902 Diag(Loc, diag::note_using_value_decl_missing_typename)
10903 << FixItHint::CreateInsertion(Loc, "typename ");
10904 }
10905 }
10906 // Fall through to create a dependent typename type, from which we can recover
10907 // better.
10908 [[fallthrough]];
10909
10911 // Okay, it's a member of an unknown instantiation.
10912 return Context.getDependentNameType(Keyword,
10913 QualifierLoc.getNestedNameSpecifier(),
10914 &II);
10915
10917 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10918 // C++ [class.qual]p2:
10919 // In a lookup in which function names are not ignored and the
10920 // nested-name-specifier nominates a class C, if the name specified
10921 // after the nested-name-specifier, when looked up in C, is the
10922 // injected-class-name of C [...] then the name is instead considered
10923 // to name the constructor of class C.
10924 //
10925 // Unlike in an elaborated-type-specifier, function names are not ignored
10926 // in typename-specifier lookup. However, they are ignored in all the
10927 // contexts where we form a typename type with no keyword (that is, in
10928 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10929 //
10930 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10931 // ignore functions, but that appears to be an oversight.
10932 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10933 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10934 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10935 FoundRD->isInjectedClassName() &&
10936 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10937 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10938 << &II << 1 << 0 /*'typename' keyword used*/;
10939
10940 // We found a type. Build an ElaboratedType, since the
10941 // typename-specifier was just sugar.
10942 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10943 return Context.getElaboratedType(Keyword,
10944 QualifierLoc.getNestedNameSpecifier(),
10946 }
10947
10948 // C++ [dcl.type.simple]p2:
10949 // A type-specifier of the form
10950 // typename[opt] nested-name-specifier[opt] template-name
10951 // is a placeholder for a deduced class type [...].
10952 if (getLangOpts().CPlusPlus17) {
10953 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10954 if (!DeducedTSTContext) {
10955 QualType T(QualifierLoc
10956 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10957 : nullptr, 0);
10958 if (!T.isNull())
10959 Diag(IILoc, diag::err_dependent_deduced_tst)
10961 else
10962 Diag(IILoc, diag::err_deduced_tst)
10965 return QualType();
10966 }
10968 Keyword, QualifierLoc.getNestedNameSpecifier(),
10970 QualType(), false));
10971 }
10972 }
10973
10974 DiagID = Ctx ? diag::err_typename_nested_not_type
10975 : diag::err_typename_not_type;
10976 Referenced = Result.getFoundDecl();
10977 break;
10978
10980 DiagID = Ctx ? diag::err_typename_nested_not_type
10981 : diag::err_typename_not_type;
10982 Referenced = *Result.begin();
10983 break;
10984
10986 return QualType();
10987 }
10988
10989 // If we get here, it's because name lookup did not find a
10990 // type. Emit an appropriate diagnostic and return an error.
10991 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10992 IILoc);
10993 if (Ctx)
10994 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10995 else
10996 Diag(IILoc, DiagID) << FullRange << Name;
10997 if (Referenced)
10998 Diag(Referenced->getLocation(),
10999 Ctx ? diag::note_typename_member_refers_here
11000 : diag::note_typename_refers_here)
11001 << Name;
11002 return QualType();
11003}
11004
11005namespace {
11006 // See Sema::RebuildTypeInCurrentInstantiation
11007 class CurrentInstantiationRebuilder
11008 : public TreeTransform<CurrentInstantiationRebuilder> {
11010 DeclarationName Entity;
11011
11012 public:
11014
11015 CurrentInstantiationRebuilder(Sema &SemaRef,
11017 DeclarationName Entity)
11018 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11019 Loc(Loc), Entity(Entity) { }
11020
11021 /// Determine whether the given type \p T has already been
11022 /// transformed.
11023 ///
11024 /// For the purposes of type reconstruction, a type has already been
11025 /// transformed if it is NULL or if it is not dependent.
11026 bool AlreadyTransformed(QualType T) {
11027 return T.isNull() || !T->isInstantiationDependentType();
11028 }
11029
11030 /// Returns the location of the entity whose type is being
11031 /// rebuilt.
11032 SourceLocation getBaseLocation() { return Loc; }
11033
11034 /// Returns the name of the entity whose type is being rebuilt.
11035 DeclarationName getBaseEntity() { return Entity; }
11036
11037 /// Sets the "base" location and entity when that
11038 /// information is known based on another transformation.
11039 void setBase(SourceLocation Loc, DeclarationName Entity) {
11040 this->Loc = Loc;
11041 this->Entity = Entity;
11042 }
11043
11044 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11045 // Lambdas never need to be transformed.
11046 return E;
11047 }
11048 };
11049} // end anonymous namespace
11050
11053 DeclarationName Name) {
11054 if (!T || !T->getType()->isInstantiationDependentType())
11055 return T;
11056
11057 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11058 return Rebuilder.TransformType(T);
11059}
11060
11062 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11063 DeclarationName());
11064 return Rebuilder.TransformExpr(E);
11065}
11066
11068 if (SS.isInvalid())
11069 return true;
11070
11072 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11073 DeclarationName());
11075 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11076 if (!Rebuilt)
11077 return true;
11078
11079 SS.Adopt(Rebuilt);
11080 return false;
11081}
11082
11084 TemplateParameterList *Params) {
11085 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11086 Decl *Param = Params->getParam(I);
11087
11088 // There is nothing to rebuild in a type parameter.
11089 if (isa<TemplateTypeParmDecl>(Param))
11090 continue;
11091
11092 // Rebuild the template parameter list of a template template parameter.
11094 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11096 TTP->getTemplateParameters()))
11097 return true;
11098
11099 continue;
11100 }
11101
11102 // Rebuild the type of a non-type template parameter.
11103 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11104 TypeSourceInfo *NewTSI
11106 NTTP->getLocation(),
11107 NTTP->getDeclName());
11108 if (!NewTSI)
11109 return true;
11110
11111 if (NewTSI->getType()->isUndeducedType()) {
11112 // C++17 [temp.dep.expr]p3:
11113 // An id-expression is type-dependent if it contains
11114 // - an identifier associated by name lookup with a non-type
11115 // template-parameter declared with a type that contains a
11116 // placeholder type (7.1.7.4),
11117 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11118 }
11119
11120 if (NewTSI != NTTP->getTypeSourceInfo()) {
11121 NTTP->setTypeSourceInfo(NewTSI);
11122 NTTP->setType(NewTSI->getType());
11123 }
11124 }
11125
11126 return false;
11127}
11128
11129std::string
11131 const TemplateArgumentList &Args) {
11132 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11133}
11134
11135std::string
11137 const TemplateArgument *Args,
11138 unsigned NumArgs) {
11139 SmallString<128> Str;
11140 llvm::raw_svector_ostream Out(Str);
11141
11142 if (!Params || Params->size() == 0 || NumArgs == 0)
11143 return std::string();
11144
11145 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11146 if (I >= NumArgs)
11147 break;
11148
11149 if (I == 0)
11150 Out << "[with ";
11151 else
11152 Out << ", ";
11153
11154 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11155 Out << Id->getName();
11156 } else {
11157 Out << '$' << I;
11158 }
11159
11160 Out << " = ";
11161 Args[I].print(getPrintingPolicy(), Out,
11163 getPrintingPolicy(), Params, I));
11164 }
11165
11166 Out << ']';
11167 return std::string(Out.str());
11168}
11169
11171 CachedTokens &Toks) {
11172 if (!FD)
11173 return;
11174
11175 auto LPT = std::make_unique<LateParsedTemplate>();
11176
11177 // Take tokens to avoid allocations
11178 LPT->Toks.swap(Toks);
11179 LPT->D = FnD;
11180 LPT->FPO = getCurFPFeatures();
11181 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11182
11183 FD->setLateTemplateParsed(true);
11184}
11185
11187 if (!FD)
11188 return;
11189 FD->setLateTemplateParsed(false);
11190}
11191
11193 DeclContext *DC = CurContext;
11194
11195 while (DC) {
11196 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11197 const FunctionDecl *FD = RD->isLocalClass();
11198 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11199 } else if (DC->isTranslationUnit() || DC->isNamespace())
11200 return false;
11201
11202 DC = DC->getParent();
11203 }
11204 return false;
11205}
11206
11207namespace {
11208/// Walk the path from which a declaration was instantiated, and check
11209/// that every explicit specialization along that path is visible. This enforces
11210/// C++ [temp.expl.spec]/6:
11211///
11212/// If a template, a member template or a member of a class template is
11213/// explicitly specialized then that specialization shall be declared before
11214/// the first use of that specialization that would cause an implicit
11215/// instantiation to take place, in every translation unit in which such a
11216/// use occurs; no diagnostic is required.
11217///
11218/// and also C++ [temp.class.spec]/1:
11219///
11220/// A partial specialization shall be declared before the first use of a
11221/// class template specialization that would make use of the partial
11222/// specialization as the result of an implicit or explicit instantiation
11223/// in every translation unit in which such a use occurs; no diagnostic is
11224/// required.
11225class ExplicitSpecializationVisibilityChecker {
11226 Sema &S;
11230
11231public:
11232 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11234 : S(S), Loc(Loc), Kind(Kind) {}
11235
11236 void check(NamedDecl *ND) {
11237 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11238 return checkImpl(FD);
11239 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11240 return checkImpl(RD);
11241 if (auto *VD = dyn_cast<VarDecl>(ND))
11242 return checkImpl(VD);
11243 if (auto *ED = dyn_cast<EnumDecl>(ND))
11244 return checkImpl(ED);
11245 }
11246
11247private:
11248 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11249 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11250 : Sema::MissingImportKind::ExplicitSpecialization;
11251 const bool Recover = true;
11252
11253 // If we got a custom set of modules (because only a subset of the
11254 // declarations are interesting), use them, otherwise let
11255 // diagnoseMissingImport intelligently pick some.
11256 if (Modules.empty())
11257 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11258 else
11259 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11260 }
11261
11262 bool CheckMemberSpecialization(const NamedDecl *D) {
11263 return Kind == Sema::AcceptableKind::Visible
11266 }
11267
11268 bool CheckExplicitSpecialization(const NamedDecl *D) {
11269 return Kind == Sema::AcceptableKind::Visible
11272 }
11273
11274 bool CheckDeclaration(const NamedDecl *D) {
11275 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11277 }
11278
11279 // Check a specific declaration. There are three problematic cases:
11280 //
11281 // 1) The declaration is an explicit specialization of a template
11282 // specialization.
11283 // 2) The declaration is an explicit specialization of a member of an
11284 // templated class.
11285 // 3) The declaration is an instantiation of a template, and that template
11286 // is an explicit specialization of a member of a templated class.
11287 //
11288 // We don't need to go any deeper than that, as the instantiation of the
11289 // surrounding class / etc is not triggered by whatever triggered this
11290 // instantiation, and thus should be checked elsewhere.
11291 template<typename SpecDecl>
11292 void checkImpl(SpecDecl *Spec) {
11293 bool IsHiddenExplicitSpecialization = false;
11294 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11295 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11296 ? !CheckMemberSpecialization(Spec)
11297 : !CheckExplicitSpecialization(Spec);
11298 } else {
11299 checkInstantiated(Spec);
11300 }
11301
11302 if (IsHiddenExplicitSpecialization)
11303 diagnose(Spec->getMostRecentDecl(), false);
11304 }
11305
11306 void checkInstantiated(FunctionDecl *FD) {
11307 if (auto *TD = FD->getPrimaryTemplate())
11308 checkTemplate(TD);
11309 }
11310
11311 void checkInstantiated(CXXRecordDecl *RD) {
11312 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11313 if (!SD)
11314 return;
11315
11316 auto From = SD->getSpecializedTemplateOrPartial();
11317 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11318 checkTemplate(TD);
11319 else if (auto *TD =
11320 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11321 if (!CheckDeclaration(TD))
11322 diagnose(TD, true);
11323 checkTemplate(TD);
11324 }
11325 }
11326
11327 void checkInstantiated(VarDecl *RD) {
11328 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11329 if (!SD)
11330 return;
11331
11332 auto From = SD->getSpecializedTemplateOrPartial();
11333 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11334 checkTemplate(TD);
11335 else if (auto *TD =
11336 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11337 if (!CheckDeclaration(TD))
11338 diagnose(TD, true);
11339 checkTemplate(TD);
11340 }
11341 }
11342
11343 void checkInstantiated(EnumDecl *FD) {}
11344
11345 template<typename TemplDecl>
11346 void checkTemplate(TemplDecl *TD) {
11347 if (TD->isMemberSpecialization()) {
11348 if (!CheckMemberSpecialization(TD))
11349 diagnose(TD->getMostRecentDecl(), false);
11350 }
11351 }
11352};
11353} // end anonymous namespace
11354
11356 if (!getLangOpts().Modules)
11357 return;
11358
11359 ExplicitSpecializationVisibilityChecker(*this, Loc,
11361 .check(Spec);
11362}
11363
11365 NamedDecl *Spec) {
11366 if (!getLangOpts().CPlusPlusModules)
11367 return checkSpecializationVisibility(Loc, Spec);
11368
11369 ExplicitSpecializationVisibilityChecker(*this, Loc,
11371 .check(Spec);
11372}
11373
11376 return N->getLocation();
11377 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11379 return FD->getLocation();
11382 return N->getLocation();
11383 }
11384 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11385 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11386 continue;
11387 return CSC.PointOfInstantiation;
11388 }
11389 return N->getLocation();
11390}
Defines the clang::ASTContext interface.
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
Defines enum values for all the target-independent builtin functions.
const Decl * D
enum clang::sema::@1724::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1172
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
MatchFinder::MatchResult MatchResult
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6834
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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 SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, TemplateArgumentLoc &Output)
Substitute template arguments into the default template argument for the given template type paramete...
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
static 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 QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate, SourceLocation TemplateLoc, ArrayRef< TemplateArgument > Ts)
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 bool RemoveLookupResult(LookupResult &R, NamedDecl *C)
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter,...
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
NullPointerValueKind
@ NPV_Error
@ NPV_NotNullPointer
@ NPV_NullPointer
static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName, TemplateSpecializationKind TSK)
Common checks for whether an explicit instantiation of D is valid.
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
static 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.
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:973
APSInt & getInt()
Definition: APValue.h:465
APSInt & getComplexIntImag()
Definition: APValue.h:503
ValueKind getKind() const
Definition: APValue.h:437
APFixedPoint & getFixedPoint()
Definition: APValue.h:487
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1056
APValue & getVectorElt(unsigned I)
Definition: APValue.h:539
unsigned getVectorLength() const
Definition: APValue.h:547
bool isLValue() const
Definition: APValue.h:448
bool isMemberPointer() const
Definition: APValue.h:453
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:1009
APSInt & getComplexIntReal()
Definition: APValue.h:495
APFloat & getComplexFloatImag()
Definition: APValue.h:519
APFloat & getComplexFloatReal()
Definition: APValue.h:511
APFloat & getFloat()
Definition: APValue.h:479
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
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:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
TemplateName getCanonicalTemplateName(TemplateName Name, bool IgnoreDeduced=false) const
Retrieves the "canonical" template name that refers to a given template.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1187
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:1703
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
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
CanQualType BoolTy
Definition: ASTContext.h:1161
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1188
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:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1188
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
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:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
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...
void setPrimaryMergedDecl(Decl *D, Decl *Primary)
Definition: ASTContext.h:1101
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:3747
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:43
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2220
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2238
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2288
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2262
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2281
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2256
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2268
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6561
bool isDecltypeAuto() const
Definition: Type.h:6584
A fixed int type of a specified bitwidth.
Definition: Type.h:7819
Pointer to a block type.
Definition: Type.h:3408
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:3034
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:2120
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3683
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:1533
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:541
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:1970
base_class_range bases()
Definition: DeclCXX.h:620
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
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:131
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1995
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1977
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2010
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:532
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
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...
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
void setMemberSpecialization()
Note that this member template is a specialization.
Represents a class template specialization, which refers to a class template with a given set of temp...
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)
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr=nullptr)
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:87
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:3615
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
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:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isFileContext() const
Definition: DeclBase.h:2160
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2045
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1368
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
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:2027
bool isNamespace() const
Definition: DeclBase.h:2178
bool isTranslationUnit() const
Definition: DeclBase.h:2165
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2008
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1285
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1385
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1389
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1404
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool isVirtualSpecified() const
Definition: DeclSpec.h:648
bool isNoreturnSpecified() const
Definition: DeclSpec.h:661
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:510
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:662
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:654
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:502
bool isInlineSpecified() const
Definition: DeclSpec.h:637
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:511
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:649
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:836
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:640
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:651
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:837
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:1050
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1010
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:239
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1206
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:281
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:835
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:246
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:805
void dropAttrs()
Definition: DeclBase.cpp:1003
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1051
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:1169
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2766
bool isInvalidDecl() const
Definition: DeclBase.h:591
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:505
SourceLocation getLocation() const
Definition: DeclBase.h:442
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:229
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:434
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:907
bool hasAttr() const
Definition: DeclBase.h:580
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:359
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:769
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents the type decltype(expr) (C++11).
Definition: Type.h:5879
Represents a C++17 deduced template specialization type.
Definition: Type.h:6609
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6527
bool isDeduced() const
Definition: Type.h:6549
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3920
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2454
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2434
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2443
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:7029
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3323
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:531
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3862
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4291
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:548
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:607
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:604
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:610
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2503
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2523
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2491
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2547
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2539
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2555
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2531
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:7081
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4086
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTypeLoc(TypeLoc TL)
Recursively visit a type with location, by dispatching to Traverse*TypeLoc() based on the argument ty...
virtual bool TraverseStmt(Stmt *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
bool isEmpty() const
Definition: TypeLoc.h:2396
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2392
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3861
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4120
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4963
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
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:3102
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:3097
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:822
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:3077
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:3970
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents a member of a struct/union/class.
Definition: Decl.h:3033
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:1002
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1081
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, SourceLocation EllipsisLoc={}, ArrayRef< TemplateParameterList * > FriendTypeTPLists={})
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1935
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2404
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4370
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4031
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3623
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:4003
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:4236
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2297
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4276
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3133
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4024
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4686
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5367
ArrayRef< QualType > param_types() const
Definition: Type.h:5516
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:472
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:547
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:558
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:530
QualType getReturnType() const
Definition: Type.h:4648
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:3724
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3764
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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:7579
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:6798
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:980
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3483
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Represents a linkage specification.
Definition: DeclCXX.h:2957
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
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:605
void setTemplateNameLookup(bool TemplateName)
Sets whether this is a template-name lookup.
Definition: Lookup.h:318
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
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:4312
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:642
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:660
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:240
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
NamedDecl * getMostRecentDecl()
Definition: Decl.h:480
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:699
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1919
Represent a C++ namespace.
Definition: Decl.h:551
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.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
void setPlaceholderTypeConstraint(Expr *E)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7529
Represents a pointer to an Objective C object.
Definition: Type.h:7585
Represents a class type in Objective C.
Definition: Type.h:7331
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:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition: Overload.h:1209
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:116
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4180
Represents a pack expansion of types.
Definition: Type.h:7146
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:255
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
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:7785
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:138
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:929
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8025
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
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:8139
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
void * getAsOpaquePtr() const
Definition: Type.h:976
QualType getNonPackExpansionType() const
Remove an outer pack expansion type (if any) from this type.
Definition: Type.cpp:3514
bool isCanonical() const
Definition: Type.h:7993
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
The collection of all-type qualifiers we support.
Definition: Type.h:324
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
void addConst()
Definition: Type.h:453
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:541
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3501
Represents a struct/union/class.
Definition: Decl.h:4162
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4353
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:6077
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:859
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:864
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:203
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4995
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
QualType getPointeeType() const
Definition: Type.h:3457
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:263
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:271
@ 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:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1060
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13200
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
Whether and why a template name is required in this lookup.
Definition: Sema.h:11090
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11098
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12116
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7229
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9258
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6395
VarTemplateSpecializationDecl * BuildVarTemplateInstantiation(VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList *PartialSpecArgs, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl< TemplateArgument > &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *StartingScope=nullptr)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
ConceptDecl * ActOnStartConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13134
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
sema::CapturingScopeInfo * getEnclosingLambdaOrBlock() const
Get the innermost lambda or block enclosing the current location, if any.
Definition: Sema.cpp:2388
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false) const
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1561
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15498
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8986
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8998
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8993
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19654
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:36
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
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:6102
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)
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:9300
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6087
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:1071
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 ...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void referenceDLLExportedClassMethods()
static NamedDecl * getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates=true, bool AllowDependent=true)
Try to interpret the lookup result D as a template-name.
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:6230
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:17152
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 ...
ConceptDecl * ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1665
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11061
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11635
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11638
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11642
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:909
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
bool ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend, unsigned TemplateDepth, const Expr *Constraint)
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5794
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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:1499
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:532
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool IsRedefinitionInModule(const NamedDecl *New, const NamedDecl *Old) const
Check the redefinition in C++20 Modules.
Definition: SemaDecl.cpp:1715
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:692
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool IsDeduced)
Check a template argument against its corresponding template template parameter.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9486
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
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:16932
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
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:11051
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11781
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11799
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11810
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11789
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11820
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:11111
@ 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:11044
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:527
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
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:13945
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13933
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13942
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13936
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13960
const LangOptions & getLangOpts() const
Definition: Sema.h:525
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1390
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Preprocessor & PP
Definition: Sema.h:908
ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, std::optional< unsigned > NumExpansions)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
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:14375
const LangOptions & LangOpts
Definition: Sema.h:907
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
std::pair< Expr *, std::string > findFailedBooleanCondition(Expr *Cond)
Find the failed Boolean condition within a given Boolean constant expression, and describe it with a ...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20066
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:8978
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:9582
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:8166
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:16907
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1324
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:9783
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:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
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:1044
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14911
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5799
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
Definition: SemaType.cpp:9816
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1291
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4719
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:9241
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3842
@ NTK_TypeAliasTemplate
Definition: Sema.h:3850
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
Get the specialization of the given variable template corresponding to the specified argument list,...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
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:216
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:14945
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:9384
RedeclarationKind forRedeclarationInCurContext() const
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
@ CCEK_TemplateArg
Value of a non-type template parameter.
Definition: Sema.h:10001
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:3095
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:1895
ASTConsumer & Consumer
Definition: Sema.h:910
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand)
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr)
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8403
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:9704
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:5704
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:17116
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:9119
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New)
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
@ TemplateNameIsRequired
Definition: Sema.h:11088
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:516
NamedDecl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:14946
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:11277
@ TPC_ClassTemplate
Definition: Sema.h:11278
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11283
@ TPC_ClassTemplateMember
Definition: Sema.h:11281
@ TPC_FunctionTemplate
Definition: Sema.h:11280
@ TPC_FriendClassTemplate
Definition: Sema.h:11282
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11284
@ TPC_TypeAliasTemplate
Definition: Sema.h:11285
@ TPC_VarTemplate
Definition: Sema.h:11279
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:1581
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:1566
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
@ OOK_Outside
Definition: Sema.h:3868
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5809
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody=nullptr)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21168
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced)
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
A wrapper function for checking the semantic restrictions of a redeclaration within a module.
Definition: SemaDecl.cpp:1705
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2751
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:3003
ArrayRef< sema::FunctionScopeInfo * > getFunctionScopes() const
Definition: Sema.h:11053
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.
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:9309
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12487
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6048
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:317
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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:357
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:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6469
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6388
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
StringRef getKindName() const
Definition: Decl.h:3769
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4762
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4845
TagKind getTagKind() const
Definition: Decl.h:3773
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4126
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:1262
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1300
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:250
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:289
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h: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...
bool isInstantiationDependent() const
Whether this template argument is dependent on a template parameter.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h: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:399
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:431
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
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:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:132
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
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:205
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1718
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1694
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1726
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1735
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1702
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1710
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6732
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4332
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.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, 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 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)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
unsigned getIndex() const
Definition: Type.h:6348
unsigned getDepth() const
Definition: Type.h:6347
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:3549
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
Represents a declaration of a type.
Definition: Decl.h:3384
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3412
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
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:749
bool isNull() const
Definition: TypeLoc.h:121
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:5802
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5852
A container of type source information.
Definition: Type.h:7907
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:7918
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
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:3196
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3178
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBooleanType() const
Definition: Type.h:8643
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isRValueReferenceType() const
Definition: Type.h:8217
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8263
bool isPointerType() const
Definition: Type.h:8191
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isScalarType() const
Definition: Type.h:8614
bool isChar8Type() const
Definition: Type.cpp:2139
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
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:460
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8341
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2811
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8213
bool isBitIntType() const
Definition: Type.h:8429
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8287
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:3002
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isChar16Type() const
Definition: Type.cpp:2145
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
QualType getCanonicalTypeInternal() const
Definition: Type.h:2989
bool isMemberPointerType() const
Definition: Type.h:8245
bool isChar32Type() const
Definition: Type.cpp:2151
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8649
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4653
bool isPointerOrReferenceType() const
Definition: Type.h:8195
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isVectorType() const
Definition: Type.h:8303
bool isWideCharType() const
Definition: Type.cpp:2132
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
QualType getUnderlyingType() const
Definition: Decl.h:3482
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:2232
A unary type transform, which is a type constructed from another.
Definition: Type.h:5994
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:419
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
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:5672
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3885
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3343
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3407
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
TLSKind getTLSKind() const
Definition: Decl.cpp:2157
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
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:2883
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:2776
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:2755
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
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...
VarTemplateDecl * getMostRecentDecl()
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
void setMemberSpecialization()
Note that this member template is a specialization.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Represents a variable template specialization, which refers to a variable template with a given set o...
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Represents a GCC generic vector type.
Definition: Type.h:4034
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
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:1886
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus17
Definition: LangStandard.h:58
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition: Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition: Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition: Overload.h:55
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition: Overload.h:859
OverloadCandidateDisplayKind
Definition: Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ 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:248
@ SC_Extern
Definition: Specifiers.h:251
@ TSCS_unspecified
Definition: Specifiers.h:236
@ 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:50
TagUseKind
Definition: Sema.h:447
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
@ 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:313
@ BTK__builtin_common_type
This names the __builtin_common_type BuiltinTemplateDecl.
Definition: Builtins.h:316
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:310
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1274
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:365
@ 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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6851
@ 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:1589
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_none
Definition: Specifiers.h:127
#define false
Definition: stdbool.h:26
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.
SourceLocation getEndLoc() const LLVM_READONLY
ArrayRef< TemplateArgument > Args
Definition: TemplateName.h:187
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:5192
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
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:12660
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12767
A stack object to be created when performing template instantiation.
Definition: Sema.h:12845
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12999
NamedDecl * Previous
Definition: Sema.h:352
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.