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
2149 if (PrevClassTemplate)
2150 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2151
2155
2156 if (TUK != TagUseKind::Friend) {
2157 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2158 Scope *Outer = S;
2159 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2160 Outer = Outer->getParent();
2161 PushOnScopeChains(NewTemplate, Outer);
2162 } else {
2163 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2164 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2165 NewClass->setAccess(PrevClassTemplate->getAccess());
2166 }
2167
2168 NewTemplate->setObjectOfFriendDecl();
2169
2170 // Friend templates are visible in fairly strange ways.
2172 DeclContext *DC = SemanticContext->getRedeclContext();
2173 DC->makeDeclVisibleInContext(NewTemplate);
2174 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2175 PushOnScopeChains(NewTemplate, EnclosingScope,
2176 /* AddToContext = */ false);
2177 }
2178
2180 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2181 Friend->setAccess(AS_public);
2183 }
2184
2185 if (PrevClassTemplate)
2186 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2187
2188 if (Invalid) {
2189 NewTemplate->setInvalidDecl();
2190 NewClass->setInvalidDecl();
2191 }
2192
2193 ActOnDocumentableDecl(NewTemplate);
2194
2195 if (SkipBody && SkipBody->ShouldSkip)
2196 return SkipBody->Previous;
2197
2198 return NewTemplate;
2199}
2200
2201/// Diagnose the presence of a default template argument on a
2202/// template parameter, which is ill-formed in certain contexts.
2203///
2204/// \returns true if the default template argument should be dropped.
2207 SourceLocation ParamLoc,
2208 SourceRange DefArgRange) {
2209 switch (TPC) {
2213 return false;
2214
2217 // C++ [temp.param]p9:
2218 // A default template-argument shall not be specified in a
2219 // function template declaration or a function template
2220 // definition [...]
2221 // If a friend function template declaration specifies a default
2222 // template-argument, that declaration shall be a definition and shall be
2223 // the only declaration of the function template in the translation unit.
2224 // (C++98/03 doesn't have this wording; see DR226).
2225 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2226 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2227 : diag::ext_template_parameter_default_in_function_template)
2228 << DefArgRange;
2229 return false;
2230
2232 // C++0x [temp.param]p9:
2233 // A default template-argument shall not be specified in the
2234 // template-parameter-lists of the definition of a member of a
2235 // class template that appears outside of the member's class.
2236 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2237 << DefArgRange;
2238 return true;
2239
2242 // C++ [temp.param]p9:
2243 // A default template-argument shall not be specified in a
2244 // friend template declaration.
2245 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2246 << DefArgRange;
2247 return true;
2248
2249 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2250 // for friend function templates if there is only a single
2251 // declaration (and it is a definition). Strange!
2252 }
2253
2254 llvm_unreachable("Invalid TemplateParamListContext!");
2255}
2256
2257/// Check for unexpanded parameter packs within the template parameters
2258/// of a template template parameter, recursively.
2261 // A template template parameter which is a parameter pack is also a pack
2262 // expansion.
2263 if (TTP->isParameterPack())
2264 return false;
2265
2267 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2268 NamedDecl *P = Params->getParam(I);
2269 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2270 if (!TTP->isParameterPack())
2271 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2272 if (TC->hasExplicitTemplateArgs())
2273 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2276 return true;
2277 continue;
2278 }
2279
2280 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2281 if (!NTTP->isParameterPack() &&
2282 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2283 NTTP->getTypeSourceInfo(),
2285 return true;
2286
2287 continue;
2288 }
2289
2290 if (TemplateTemplateParmDecl *InnerTTP
2291 = dyn_cast<TemplateTemplateParmDecl>(P))
2292 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2293 return true;
2294 }
2295
2296 return false;
2297}
2298
2300 TemplateParameterList *OldParams,
2302 SkipBodyInfo *SkipBody) {
2303 bool Invalid = false;
2304
2305 // C++ [temp.param]p10:
2306 // The set of default template-arguments available for use with a
2307 // template declaration or definition is obtained by merging the
2308 // default arguments from the definition (if in scope) and all
2309 // declarations in scope in the same way default function
2310 // arguments are (8.3.6).
2311 bool SawDefaultArgument = false;
2312 SourceLocation PreviousDefaultArgLoc;
2313
2314 // Dummy initialization to avoid warnings.
2315 TemplateParameterList::iterator OldParam = NewParams->end();
2316 if (OldParams)
2317 OldParam = OldParams->begin();
2318
2319 bool RemoveDefaultArguments = false;
2320 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2321 NewParamEnd = NewParams->end();
2322 NewParam != NewParamEnd; ++NewParam) {
2323 // Whether we've seen a duplicate default argument in the same translation
2324 // unit.
2325 bool RedundantDefaultArg = false;
2326 // Whether we've found inconsis inconsitent default arguments in different
2327 // translation unit.
2328 bool InconsistentDefaultArg = false;
2329 // The name of the module which contains the inconsistent default argument.
2330 std::string PrevModuleName;
2331
2332 SourceLocation OldDefaultLoc;
2333 SourceLocation NewDefaultLoc;
2334
2335 // Variable used to diagnose missing default arguments
2336 bool MissingDefaultArg = false;
2337
2338 // Variable used to diagnose non-final parameter packs
2339 bool SawParameterPack = false;
2340
2341 if (TemplateTypeParmDecl *NewTypeParm
2342 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2343 // Check the presence of a default argument here.
2344 if (NewTypeParm->hasDefaultArgument() &&
2346 *this, TPC, NewTypeParm->getLocation(),
2347 NewTypeParm->getDefaultArgument().getSourceRange()))
2348 NewTypeParm->removeDefaultArgument();
2349
2350 // Merge default arguments for template type parameters.
2351 TemplateTypeParmDecl *OldTypeParm
2352 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2353 if (NewTypeParm->isParameterPack()) {
2354 assert(!NewTypeParm->hasDefaultArgument() &&
2355 "Parameter packs can't have a default argument!");
2356 SawParameterPack = true;
2357 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2358 NewTypeParm->hasDefaultArgument() &&
2359 (!SkipBody || !SkipBody->ShouldSkip)) {
2360 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2361 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2362 SawDefaultArgument = true;
2363
2364 if (!OldTypeParm->getOwningModule())
2365 RedundantDefaultArg = true;
2366 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2367 NewTypeParm)) {
2368 InconsistentDefaultArg = true;
2369 PrevModuleName =
2371 }
2372 PreviousDefaultArgLoc = NewDefaultLoc;
2373 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2374 // Merge the default argument from the old declaration to the
2375 // new declaration.
2376 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2377 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2378 } else if (NewTypeParm->hasDefaultArgument()) {
2379 SawDefaultArgument = true;
2380 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2381 } else if (SawDefaultArgument)
2382 MissingDefaultArg = true;
2383 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2384 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2385 // Check for unexpanded parameter packs.
2386 if (!NewNonTypeParm->isParameterPack() &&
2387 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2388 NewNonTypeParm->getTypeSourceInfo(),
2390 Invalid = true;
2391 continue;
2392 }
2393
2394 // Check the presence of a default argument here.
2395 if (NewNonTypeParm->hasDefaultArgument() &&
2397 *this, TPC, NewNonTypeParm->getLocation(),
2398 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2399 NewNonTypeParm->removeDefaultArgument();
2400 }
2401
2402 // Merge default arguments for non-type template parameters
2403 NonTypeTemplateParmDecl *OldNonTypeParm
2404 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2405 if (NewNonTypeParm->isParameterPack()) {
2406 assert(!NewNonTypeParm->hasDefaultArgument() &&
2407 "Parameter packs can't have a default argument!");
2408 if (!NewNonTypeParm->isPackExpansion())
2409 SawParameterPack = true;
2410 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2411 NewNonTypeParm->hasDefaultArgument() &&
2412 (!SkipBody || !SkipBody->ShouldSkip)) {
2413 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2414 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2415 SawDefaultArgument = true;
2416 if (!OldNonTypeParm->getOwningModule())
2417 RedundantDefaultArg = true;
2418 else if (!getASTContext().isSameDefaultTemplateArgument(
2419 OldNonTypeParm, NewNonTypeParm)) {
2420 InconsistentDefaultArg = true;
2421 PrevModuleName =
2422 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2423 }
2424 PreviousDefaultArgLoc = NewDefaultLoc;
2425 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2426 // Merge the default argument from the old declaration to the
2427 // new declaration.
2428 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2429 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2430 } else if (NewNonTypeParm->hasDefaultArgument()) {
2431 SawDefaultArgument = true;
2432 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2433 } else if (SawDefaultArgument)
2434 MissingDefaultArg = true;
2435 } else {
2436 TemplateTemplateParmDecl *NewTemplateParm
2437 = cast<TemplateTemplateParmDecl>(*NewParam);
2438
2439 // Check for unexpanded parameter packs, recursively.
2440 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2441 Invalid = true;
2442 continue;
2443 }
2444
2445 // Check the presence of a default argument here.
2446 if (NewTemplateParm->hasDefaultArgument() &&
2448 NewTemplateParm->getLocation(),
2449 NewTemplateParm->getDefaultArgument().getSourceRange()))
2450 NewTemplateParm->removeDefaultArgument();
2451
2452 // Merge default arguments for template template parameters
2453 TemplateTemplateParmDecl *OldTemplateParm
2454 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2455 if (NewTemplateParm->isParameterPack()) {
2456 assert(!NewTemplateParm->hasDefaultArgument() &&
2457 "Parameter packs can't have a default argument!");
2458 if (!NewTemplateParm->isPackExpansion())
2459 SawParameterPack = true;
2460 } else if (OldTemplateParm &&
2461 hasVisibleDefaultArgument(OldTemplateParm) &&
2462 NewTemplateParm->hasDefaultArgument() &&
2463 (!SkipBody || !SkipBody->ShouldSkip)) {
2464 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2465 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2466 SawDefaultArgument = true;
2467 if (!OldTemplateParm->getOwningModule())
2468 RedundantDefaultArg = true;
2469 else if (!getASTContext().isSameDefaultTemplateArgument(
2470 OldTemplateParm, NewTemplateParm)) {
2471 InconsistentDefaultArg = true;
2472 PrevModuleName =
2473 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2474 }
2475 PreviousDefaultArgLoc = NewDefaultLoc;
2476 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2477 // Merge the default argument from the old declaration to the
2478 // new declaration.
2479 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2480 PreviousDefaultArgLoc
2481 = OldTemplateParm->getDefaultArgument().getLocation();
2482 } else if (NewTemplateParm->hasDefaultArgument()) {
2483 SawDefaultArgument = true;
2484 PreviousDefaultArgLoc
2485 = NewTemplateParm->getDefaultArgument().getLocation();
2486 } else if (SawDefaultArgument)
2487 MissingDefaultArg = true;
2488 }
2489
2490 // C++11 [temp.param]p11:
2491 // If a template parameter of a primary class template or alias template
2492 // is a template parameter pack, it shall be the last template parameter.
2493 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2494 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2495 TPC == TPC_TypeAliasTemplate)) {
2496 Diag((*NewParam)->getLocation(),
2497 diag::err_template_param_pack_must_be_last_template_parameter);
2498 Invalid = true;
2499 }
2500
2501 // [basic.def.odr]/13:
2502 // There can be more than one definition of a
2503 // ...
2504 // default template argument
2505 // ...
2506 // in a program provided that each definition appears in a different
2507 // translation unit and the definitions satisfy the [same-meaning
2508 // criteria of the ODR].
2509 //
2510 // Simply, the design of modules allows the definition of template default
2511 // argument to be repeated across translation unit. Note that the ODR is
2512 // checked elsewhere. But it is still not allowed to repeat template default
2513 // argument in the same translation unit.
2514 if (RedundantDefaultArg) {
2515 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2516 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2517 Invalid = true;
2518 } else if (InconsistentDefaultArg) {
2519 // We could only diagnose about the case that the OldParam is imported.
2520 // The case NewParam is imported should be handled in ASTReader.
2521 Diag(NewDefaultLoc,
2522 diag::err_template_param_default_arg_inconsistent_redefinition);
2523 Diag(OldDefaultLoc,
2524 diag::note_template_param_prev_default_arg_in_other_module)
2525 << PrevModuleName;
2526 Invalid = true;
2527 } else if (MissingDefaultArg &&
2528 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2529 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2530 // C++ 23[temp.param]p14:
2531 // If a template-parameter of a class template, variable template, or
2532 // alias template has a default template argument, each subsequent
2533 // template-parameter shall either have a default template argument
2534 // supplied or be a template parameter pack.
2535 Diag((*NewParam)->getLocation(),
2536 diag::err_template_param_default_arg_missing);
2537 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2538 Invalid = true;
2539 RemoveDefaultArguments = true;
2540 }
2541
2542 // If we have an old template parameter list that we're merging
2543 // in, move on to the next parameter.
2544 if (OldParams)
2545 ++OldParam;
2546 }
2547
2548 // We were missing some default arguments at the end of the list, so remove
2549 // all of the default arguments.
2550 if (RemoveDefaultArguments) {
2551 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2552 NewParamEnd = NewParams->end();
2553 NewParam != NewParamEnd; ++NewParam) {
2554 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2555 TTP->removeDefaultArgument();
2556 else if (NonTypeTemplateParmDecl *NTTP
2557 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2558 NTTP->removeDefaultArgument();
2559 else
2560 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2561 }
2562 }
2563
2564 return Invalid;
2565}
2566
2567namespace {
2568
2569/// A class which looks for a use of a certain level of template
2570/// parameter.
2571struct DependencyChecker : DynamicRecursiveASTVisitor {
2572 unsigned Depth;
2573
2574 // Whether we're looking for a use of a template parameter that makes the
2575 // overall construct type-dependent / a dependent type. This is strictly
2576 // best-effort for now; we may fail to match at all for a dependent type
2577 // in some cases if this is set.
2578 bool IgnoreNonTypeDependent;
2579
2580 bool Match;
2581 SourceLocation MatchLoc;
2582
2583 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2584 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2585 Match(false) {}
2586
2587 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2588 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2589 NamedDecl *ND = Params->getParam(0);
2590 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2591 Depth = PD->getDepth();
2592 } else if (NonTypeTemplateParmDecl *PD =
2593 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2594 Depth = PD->getDepth();
2595 } else {
2596 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2597 }
2598 }
2599
2600 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2601 if (ParmDepth >= Depth) {
2602 Match = true;
2603 MatchLoc = Loc;
2604 return true;
2605 }
2606 return false;
2607 }
2608
2609 bool TraverseStmt(Stmt *S) override {
2610 // Prune out non-type-dependent expressions if requested. This can
2611 // sometimes result in us failing to find a template parameter reference
2612 // (if a value-dependent expression creates a dependent type), but this
2613 // mode is best-effort only.
2614 if (auto *E = dyn_cast_or_null<Expr>(S))
2615 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2616 return true;
2618 }
2619
2620 bool TraverseTypeLoc(TypeLoc TL) override {
2621 if (IgnoreNonTypeDependent && !TL.isNull() &&
2622 !TL.getType()->isDependentType())
2623 return true;
2625 }
2626
2627 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2628 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2629 }
2630
2631 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2632 // For a best-effort search, keep looking until we find a location.
2633 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2634 }
2635
2636 bool TraverseTemplateName(TemplateName N) override {
2637 if (TemplateTemplateParmDecl *PD =
2638 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2639 if (Matches(PD->getDepth()))
2640 return false;
2642 }
2643
2644 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2645 if (NonTypeTemplateParmDecl *PD =
2646 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2647 if (Matches(PD->getDepth(), E->getExprLoc()))
2648 return false;
2649 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2650 }
2651
2652 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2653 return TraverseType(T->getReplacementType());
2654 }
2655
2656 bool VisitSubstTemplateTypeParmPackType(
2657 SubstTemplateTypeParmPackType *T) override {
2658 return TraverseTemplateArgument(T->getArgumentPack());
2659 }
2660
2661 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2662 return TraverseType(T->getInjectedSpecializationType());
2663 }
2664};
2665} // end anonymous namespace
2666
2667/// Determines whether a given type depends on the given parameter
2668/// list.
2669static bool
2671 if (!Params->size())
2672 return false;
2673
2674 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2675 Checker.TraverseType(T);
2676 return Checker.Match;
2677}
2678
2679// Find the source range corresponding to the named type in the given
2680// nested-name-specifier, if any.
2682 QualType T,
2683 const CXXScopeSpec &SS) {
2685 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2686 if (const Type *CurType = NNS->getAsType()) {
2687 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2688 return NNSLoc.getTypeLoc().getSourceRange();
2689 } else
2690 break;
2691
2692 NNSLoc = NNSLoc.getPrefix();
2693 }
2694
2695 return SourceRange();
2696}
2697
2699 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2700 TemplateIdAnnotation *TemplateId,
2701 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2702 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2703 IsMemberSpecialization = false;
2704 Invalid = false;
2705
2706 // The sequence of nested types to which we will match up the template
2707 // parameter lists. We first build this list by starting with the type named
2708 // by the nested-name-specifier and walking out until we run out of types.
2709 SmallVector<QualType, 4> NestedTypes;
2710 QualType T;
2711 if (SS.getScopeRep()) {
2713 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2715 else
2716 T = QualType(SS.getScopeRep()->getAsType(), 0);
2717 }
2718
2719 // If we found an explicit specialization that prevents us from needing
2720 // 'template<>' headers, this will be set to the location of that
2721 // explicit specialization.
2722 SourceLocation ExplicitSpecLoc;
2723
2724 while (!T.isNull()) {
2725 NestedTypes.push_back(T);
2726
2727 // Retrieve the parent of a record type.
2729 // If this type is an explicit specialization, we're done.
2731 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2732 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2733 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2734 ExplicitSpecLoc = Spec->getLocation();
2735 break;
2736 }
2737 } else if (Record->getTemplateSpecializationKind()
2739 ExplicitSpecLoc = Record->getLocation();
2740 break;
2741 }
2742
2743 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2745 else
2746 T = QualType();
2747 continue;
2748 }
2749
2750 if (const TemplateSpecializationType *TST
2752 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2753 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2755 else
2756 T = QualType();
2757 continue;
2758 }
2759 }
2760
2761 // Look one step prior in a dependent template specialization type.
2762 if (const DependentTemplateSpecializationType *DependentTST
2764 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2765 T = QualType(NNS->getAsType(), 0);
2766 else
2767 T = QualType();
2768 continue;
2769 }
2770
2771 // Look one step prior in a dependent name type.
2772 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2773 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2774 T = QualType(NNS->getAsType(), 0);
2775 else
2776 T = QualType();
2777 continue;
2778 }
2779
2780 // Retrieve the parent of an enumeration type.
2781 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2782 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2783 // check here.
2784 EnumDecl *Enum = EnumT->getDecl();
2785
2786 // Get to the parent type.
2787 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2789 else
2790 T = QualType();
2791 continue;
2792 }
2793
2794 T = QualType();
2795 }
2796 // Reverse the nested types list, since we want to traverse from the outermost
2797 // to the innermost while checking template-parameter-lists.
2798 std::reverse(NestedTypes.begin(), NestedTypes.end());
2799
2800 // C++0x [temp.expl.spec]p17:
2801 // A member or a member template may be nested within many
2802 // enclosing class templates. In an explicit specialization for
2803 // such a member, the member declaration shall be preceded by a
2804 // template<> for each enclosing class template that is
2805 // explicitly specialized.
2806 bool SawNonEmptyTemplateParameterList = false;
2807
2808 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2809 if (SawNonEmptyTemplateParameterList) {
2810 if (!SuppressDiagnostic)
2811 Diag(DeclLoc, diag::err_specialize_member_of_template)
2812 << !Recovery << Range;
2813 Invalid = true;
2814 IsMemberSpecialization = false;
2815 return true;
2816 }
2817
2818 return false;
2819 };
2820
2821 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2822 // Check that we can have an explicit specialization here.
2823 if (CheckExplicitSpecialization(Range, true))
2824 return true;
2825
2826 // We don't have a template header, but we should.
2827 SourceLocation ExpectedTemplateLoc;
2828 if (!ParamLists.empty())
2829 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2830 else
2831 ExpectedTemplateLoc = DeclStartLoc;
2832
2833 if (!SuppressDiagnostic)
2834 Diag(DeclLoc, diag::err_template_spec_needs_header)
2835 << Range
2836 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2837 return false;
2838 };
2839
2840 unsigned ParamIdx = 0;
2841 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2842 ++TypeIdx) {
2843 T = NestedTypes[TypeIdx];
2844
2845 // Whether we expect a 'template<>' header.
2846 bool NeedEmptyTemplateHeader = false;
2847
2848 // Whether we expect a template header with parameters.
2849 bool NeedNonemptyTemplateHeader = false;
2850
2851 // For a dependent type, the set of template parameters that we
2852 // expect to see.
2853 TemplateParameterList *ExpectedTemplateParams = nullptr;
2854
2855 // C++0x [temp.expl.spec]p15:
2856 // A member or a member template may be nested within many enclosing
2857 // class templates. In an explicit specialization for such a member, the
2858 // member declaration shall be preceded by a template<> for each
2859 // enclosing class template that is explicitly specialized.
2862 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2863 ExpectedTemplateParams = Partial->getTemplateParameters();
2864 NeedNonemptyTemplateHeader = true;
2865 } else if (Record->isDependentType()) {
2866 if (Record->getDescribedClassTemplate()) {
2867 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2868 ->getTemplateParameters();
2869 NeedNonemptyTemplateHeader = true;
2870 }
2871 } else if (ClassTemplateSpecializationDecl *Spec
2872 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2873 // C++0x [temp.expl.spec]p4:
2874 // Members of an explicitly specialized class template are defined
2875 // in the same manner as members of normal classes, and not using
2876 // the template<> syntax.
2877 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2878 NeedEmptyTemplateHeader = true;
2879 else
2880 continue;
2881 } else if (Record->getTemplateSpecializationKind()) {
2882 if (Record->getTemplateSpecializationKind()
2884 TypeIdx == NumTypes - 1)
2885 IsMemberSpecialization = true;
2886
2887 continue;
2888 }
2889 } else if (const TemplateSpecializationType *TST
2891 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2892 ExpectedTemplateParams = Template->getTemplateParameters();
2893 NeedNonemptyTemplateHeader = true;
2894 }
2896 // FIXME: We actually could/should check the template arguments here
2897 // against the corresponding template parameter list.
2898 NeedNonemptyTemplateHeader = false;
2899 }
2900
2901 // C++ [temp.expl.spec]p16:
2902 // In an explicit specialization declaration for a member of a class
2903 // template or a member template that appears in namespace scope, the
2904 // member template and some of its enclosing class templates may remain
2905 // unspecialized, except that the declaration shall not explicitly
2906 // specialize a class member template if its enclosing class templates
2907 // are not explicitly specialized as well.
2908 if (ParamIdx < ParamLists.size()) {
2909 if (ParamLists[ParamIdx]->size() == 0) {
2910 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2911 false))
2912 return nullptr;
2913 } else
2914 SawNonEmptyTemplateParameterList = true;
2915 }
2916
2917 if (NeedEmptyTemplateHeader) {
2918 // If we're on the last of the types, and we need a 'template<>' header
2919 // here, then it's a member specialization.
2920 if (TypeIdx == NumTypes - 1)
2921 IsMemberSpecialization = true;
2922
2923 if (ParamIdx < ParamLists.size()) {
2924 if (ParamLists[ParamIdx]->size() > 0) {
2925 // The header has template parameters when it shouldn't. Complain.
2926 if (!SuppressDiagnostic)
2927 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2928 diag::err_template_param_list_matches_nontemplate)
2929 << T
2930 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2931 ParamLists[ParamIdx]->getRAngleLoc())
2933 Invalid = true;
2934 return nullptr;
2935 }
2936
2937 // Consume this template header.
2938 ++ParamIdx;
2939 continue;
2940 }
2941
2942 if (!IsFriend)
2943 if (DiagnoseMissingExplicitSpecialization(
2945 return nullptr;
2946
2947 continue;
2948 }
2949
2950 if (NeedNonemptyTemplateHeader) {
2951 // In friend declarations we can have template-ids which don't
2952 // depend on the corresponding template parameter lists. But
2953 // assume that empty parameter lists are supposed to match this
2954 // template-id.
2955 if (IsFriend && T->isDependentType()) {
2956 if (ParamIdx < ParamLists.size() &&
2958 ExpectedTemplateParams = nullptr;
2959 else
2960 continue;
2961 }
2962
2963 if (ParamIdx < ParamLists.size()) {
2964 // Check the template parameter list, if we can.
2965 if (ExpectedTemplateParams &&
2967 ExpectedTemplateParams,
2968 !SuppressDiagnostic, TPL_TemplateMatch))
2969 Invalid = true;
2970
2971 if (!Invalid &&
2972 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2974 Invalid = true;
2975
2976 ++ParamIdx;
2977 continue;
2978 }
2979
2980 if (!SuppressDiagnostic)
2981 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2982 << T
2984 Invalid = true;
2985 continue;
2986 }
2987 }
2988
2989 // If there were at least as many template-ids as there were template
2990 // parameter lists, then there are no template parameter lists remaining for
2991 // the declaration itself.
2992 if (ParamIdx >= ParamLists.size()) {
2993 if (TemplateId && !IsFriend) {
2994 // We don't have a template header for the declaration itself, but we
2995 // should.
2996 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2997 TemplateId->RAngleLoc));
2998
2999 // Fabricate an empty template parameter list for the invented header.
3001 SourceLocation(), {},
3002 SourceLocation(), nullptr);
3003 }
3004
3005 return nullptr;
3006 }
3007
3008 // If there were too many template parameter lists, complain about that now.
3009 if (ParamIdx < ParamLists.size() - 1) {
3010 bool HasAnyExplicitSpecHeader = false;
3011 bool AllExplicitSpecHeaders = true;
3012 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3013 if (ParamLists[I]->size() == 0)
3014 HasAnyExplicitSpecHeader = true;
3015 else
3016 AllExplicitSpecHeaders = false;
3017 }
3018
3019 if (!SuppressDiagnostic)
3020 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3021 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3022 : diag::err_template_spec_extra_headers)
3023 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3024 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3025
3026 // If there was a specialization somewhere, such that 'template<>' is
3027 // not required, and there were any 'template<>' headers, note where the
3028 // specialization occurred.
3029 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3030 !SuppressDiagnostic)
3031 Diag(ExplicitSpecLoc,
3032 diag::note_explicit_template_spec_does_not_need_header)
3033 << NestedTypes.back();
3034
3035 // We have a template parameter list with no corresponding scope, which
3036 // means that the resulting template declaration can't be instantiated
3037 // properly (we'll end up with dependent nodes when we shouldn't).
3038 if (!AllExplicitSpecHeaders)
3039 Invalid = true;
3040 }
3041
3042 // C++ [temp.expl.spec]p16:
3043 // In an explicit specialization declaration for a member of a class
3044 // template or a member template that ap- pears in namespace scope, the
3045 // member template and some of its enclosing class templates may remain
3046 // unspecialized, except that the declaration shall not explicitly
3047 // specialize a class member template if its en- closing class templates
3048 // are not explicitly specialized as well.
3049 if (ParamLists.back()->size() == 0 &&
3050 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3051 false))
3052 return nullptr;
3053
3054 // Return the last template parameter list, which corresponds to the
3055 // entity being declared.
3056 return ParamLists.back();
3057}
3058
3060 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3061 Diag(Template->getLocation(), diag::note_template_declared_here)
3062 << (isa<FunctionTemplateDecl>(Template)
3063 ? 0
3064 : isa<ClassTemplateDecl>(Template)
3065 ? 1
3066 : isa<VarTemplateDecl>(Template)
3067 ? 2
3068 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3069 << Template->getDeclName();
3070 return;
3071 }
3072
3073 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3074 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3075 IEnd = OST->end();
3076 I != IEnd; ++I)
3077 Diag((*I)->getLocation(), diag::note_template_declared_here)
3078 << 0 << (*I)->getDeclName();
3079
3080 return;
3081 }
3082}
3083
3085 SourceLocation TemplateLoc,
3087 auto lookUpCommonType = [&](TemplateArgument T1,
3088 TemplateArgument T2) -> QualType {
3089 // Don't bother looking for other specializations if both types are
3090 // builtins - users aren't allowed to specialize for them
3091 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3092 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3093
3098 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3099
3100 EnterExpressionEvaluationContext UnevaluatedContext(
3102 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3104
3105 QualType BaseTemplateInst =
3106 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3107
3108 if (SFINAE.hasErrorOccurred())
3109 return QualType();
3110
3111 return BaseTemplateInst;
3112 };
3113
3114 // Note A: For the common_type trait applied to a template parameter pack T of
3115 // types, the member type shall be either defined or not present as follows:
3116 switch (Ts.size()) {
3117
3118 // If sizeof...(T) is zero, there shall be no member type.
3119 case 0:
3120 return QualType();
3121
3122 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3123 // pack T. The member typedef-name type shall denote the same type, if any, as
3124 // common_type_t<T0, T0>; otherwise there shall be no member type.
3125 case 1:
3126 return lookUpCommonType(Ts[0], Ts[0]);
3127
3128 // If sizeof...(T) is two, let the first and second types constituting T be
3129 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3130 // as decay_t<T1> and decay_t<T2>, respectively.
3131 case 2: {
3132 QualType T1 = Ts[0].getAsType();
3133 QualType T2 = Ts[1].getAsType();
3134 QualType D1 = S.BuiltinDecay(T1, {});
3135 QualType D2 = S.BuiltinDecay(T2, {});
3136
3137 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3138 // the same type, if any, as common_type_t<D1, D2>.
3139 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3140 return lookUpCommonType(D1, D2);
3141
3142 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3143 // denotes a valid type, let C denote that type.
3144 {
3145 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3146 EnterExpressionEvaluationContext UnevaluatedContext(
3148 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3150
3151 // false
3153 VK_PRValue);
3154 ExprResult Cond = &CondExpr;
3155
3156 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3157 if (ConstRefQual) {
3158 D1.addConst();
3159 D2.addConst();
3160 }
3161
3162 // declval<D1>()
3163 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3164 ExprResult LHS = &LHSExpr;
3165
3166 // declval<D2>()
3167 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3168 ExprResult RHS = &RHSExpr;
3169
3172
3173 // decltype(false ? declval<D1>() : declval<D2>())
3175 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3176
3177 if (Result.isNull() || SFINAE.hasErrorOccurred())
3178 return QualType();
3179
3180 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3181 return S.BuiltinDecay(Result, TemplateLoc);
3182 };
3183
3184 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3185 return Res;
3186
3187 // Let:
3188 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3189 // COND-RES(X, Y) be
3190 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3191
3192 // C++20 only
3193 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3194 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3195 if (!S.Context.getLangOpts().CPlusPlus20)
3196 return QualType();
3197 return CheckConditionalOperands(true);
3198 }
3199 }
3200
3201 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3202 // denote the first, second, and (pack of) remaining types constituting T. Let
3203 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3204 // a type C, the member typedef-name type shall denote the same type, if any,
3205 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3206 default: {
3207 QualType Result = Ts.front().getAsType();
3208 for (auto T : llvm::drop_begin(Ts)) {
3209 Result = lookUpCommonType(Result, T.getAsType());
3210 if (Result.isNull())
3211 return QualType();
3212 }
3213 return Result;
3214 }
3215 }
3216}
3217
3218static QualType
3221 SourceLocation TemplateLoc,
3222 TemplateArgumentListInfo &TemplateArgs) {
3223 ASTContext &Context = SemaRef.getASTContext();
3224
3225 switch (BTD->getBuiltinTemplateKind()) {
3226 case BTK__make_integer_seq: {
3227 // Specializations of __make_integer_seq<S, T, N> are treated like
3228 // S<T, 0, ..., N-1>.
3229
3230 QualType OrigType = Converted[1].getAsType();
3231 // C++14 [inteseq.intseq]p1:
3232 // T shall be an integer type.
3233 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3234 SemaRef.Diag(TemplateArgs[1].getLocation(),
3235 diag::err_integer_sequence_integral_element_type);
3236 return QualType();
3237 }
3238
3239 TemplateArgument NumArgsArg = Converted[2];
3240 if (NumArgsArg.isDependent())
3242 Converted);
3243
3244 TemplateArgumentListInfo SyntheticTemplateArgs;
3245 // The type argument, wrapped in substitution sugar, gets reused as the
3246 // first template argument in the synthetic template argument list.
3247 SyntheticTemplateArgs.addArgument(
3250 OrigType, TemplateArgs[1].getLocation())));
3251
3252 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3253 // Expand N into 0 ... N-1.
3254 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3255 I < NumArgs; ++I) {
3256 TemplateArgument TA(Context, I, OrigType);
3257 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3258 TA, OrigType, TemplateArgs[2].getLocation()));
3259 }
3260 } else {
3261 // C++14 [inteseq.make]p1:
3262 // If N is negative the program is ill-formed.
3263 SemaRef.Diag(TemplateArgs[2].getLocation(),
3264 diag::err_integer_sequence_negative_length);
3265 return QualType();
3266 }
3267
3268 // The first template argument will be reused as the template decl that
3269 // our synthetic template arguments will be applied to.
3270 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3271 TemplateLoc, SyntheticTemplateArgs);
3272 }
3273
3275 // Specializations of
3276 // __type_pack_element<Index, T_1, ..., T_N>
3277 // are treated like T_Index.
3278 assert(Converted.size() == 2 &&
3279 "__type_pack_element should be given an index and a parameter pack");
3280
3281 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3282 if (IndexArg.isDependent() || Ts.isDependent())
3284 Converted);
3285
3286 llvm::APSInt Index = IndexArg.getAsIntegral();
3287 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3288 "type std::size_t, and hence be non-negative");
3289 // If the Index is out of bounds, the program is ill-formed.
3290 if (Index >= Ts.pack_size()) {
3291 SemaRef.Diag(TemplateArgs[0].getLocation(),
3292 diag::err_type_pack_element_out_of_bounds);
3293 return QualType();
3294 }
3295
3296 // We simply return the type at index `Index`.
3297 int64_t N = Index.getExtValue();
3298 return Ts.getPackAsArray()[N].getAsType();
3299 }
3300
3302 assert(Converted.size() == 4);
3303 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3305 Converted);
3306
3307 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3308 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3309 QualType HasNoTypeMember = Converted[2].getAsType();
3310 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3311 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3312 !CT.isNull()) {
3316 CT, TemplateArgs[1].getLocation())));
3317
3318 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3319 }
3320 return HasNoTypeMember;
3321 }
3322 }
3323 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3324}
3325
3326/// Determine whether this alias template is "enable_if_t".
3327/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3329 return AliasTemplate->getName() == "enable_if_t" ||
3330 AliasTemplate->getName() == "__enable_if_t";
3331}
3332
3333/// Collect all of the separable terms in the given condition, which
3334/// might be a conjunction.
3335///
3336/// FIXME: The right answer is to convert the logical expression into
3337/// disjunctive normal form, so we can find the first failed term
3338/// within each possible clause.
3339static void collectConjunctionTerms(Expr *Clause,
3340 SmallVectorImpl<Expr *> &Terms) {
3341 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3342 if (BinOp->getOpcode() == BO_LAnd) {
3343 collectConjunctionTerms(BinOp->getLHS(), Terms);
3344 collectConjunctionTerms(BinOp->getRHS(), Terms);
3345 return;
3346 }
3347 }
3348
3349 Terms.push_back(Clause);
3350}
3351
3352// The ranges-v3 library uses an odd pattern of a top-level "||" with
3353// a left-hand side that is value-dependent but never true. Identify
3354// the idiom and ignore that term.
3356 // Top-level '||'.
3357 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3358 if (!BinOp) return Cond;
3359
3360 if (BinOp->getOpcode() != BO_LOr) return Cond;
3361
3362 // With an inner '==' that has a literal on the right-hand side.
3363 Expr *LHS = BinOp->getLHS();
3364 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3365 if (!InnerBinOp) return Cond;
3366
3367 if (InnerBinOp->getOpcode() != BO_EQ ||
3368 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3369 return Cond;
3370
3371 // If the inner binary operation came from a macro expansion named
3372 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3373 // of the '||', which is the real, user-provided condition.
3374 SourceLocation Loc = InnerBinOp->getExprLoc();
3375 if (!Loc.isMacroID()) return Cond;
3376
3377 StringRef MacroName = PP.getImmediateMacroName(Loc);
3378 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3379 return BinOp->getRHS();
3380
3381 return Cond;
3382}
3383
3384namespace {
3385
3386// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3387// within failing boolean expression, such as substituting template parameters
3388// for actual types.
3389class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3390public:
3391 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3392 : Policy(P) {}
3393
3394 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3395 const auto *DR = dyn_cast<DeclRefExpr>(E);
3396 if (DR && DR->getQualifier()) {
3397 // If this is a qualified name, expand the template arguments in nested
3398 // qualifiers.
3399 DR->getQualifier()->print(OS, Policy, true);
3400 // Then print the decl itself.
3401 const ValueDecl *VD = DR->getDecl();
3402 OS << VD->getName();
3403 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3404 // This is a template variable, print the expanded template arguments.
3406 OS, IV->getTemplateArgs().asArray(), Policy,
3407 IV->getSpecializedTemplate()->getTemplateParameters());
3408 }
3409 return true;
3410 }
3411 return false;
3412 }
3413
3414private:
3415 const PrintingPolicy Policy;
3416};
3417
3418} // end anonymous namespace
3419
3420std::pair<Expr *, std::string>
3422 Cond = lookThroughRangesV3Condition(PP, Cond);
3423
3424 // Separate out all of the terms in a conjunction.
3426 collectConjunctionTerms(Cond, Terms);
3427
3428 // Determine which term failed.
3429 Expr *FailedCond = nullptr;
3430 for (Expr *Term : Terms) {
3431 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3432
3433 // Literals are uninteresting.
3434 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3435 isa<IntegerLiteral>(TermAsWritten))
3436 continue;
3437
3438 // The initialization of the parameter from the argument is
3439 // a constant-evaluated context.
3442
3443 bool Succeeded;
3444 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3445 !Succeeded) {
3446 FailedCond = TermAsWritten;
3447 break;
3448 }
3449 }
3450 if (!FailedCond)
3451 FailedCond = Cond->IgnoreParenImpCasts();
3452
3453 std::string Description;
3454 {
3455 llvm::raw_string_ostream Out(Description);
3457 Policy.PrintCanonicalTypes = true;
3458 FailedBooleanConditionPrinterHelper Helper(Policy);
3459 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3460 }
3461 return { FailedCond, Description };
3462}
3463
3465 SourceLocation TemplateLoc,
3466 TemplateArgumentListInfo &TemplateArgs) {
3468 Name.getUnderlying().getAsDependentTemplateName();
3469 if (DTN && DTN->isIdentifier())
3470 // When building a template-id where the template-name is dependent,
3471 // assume the template is a type template. Either our assumption is
3472 // correct, or the code is ill-formed and will be diagnosed when the
3473 // dependent name is substituted.
3476 TemplateArgs.arguments());
3477
3478 if (Name.getAsAssumedTemplateName() &&
3479 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3480 return QualType();
3481
3482 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3483
3484 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3485 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3486 // We might have a substituted template template parameter pack. If so,
3487 // build a template specialization type for it.
3488 if (Name.getAsSubstTemplateTemplateParmPack())
3490 TemplateArgs.arguments());
3491
3492 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3493 << Name;
3495 return QualType();
3496 }
3497
3498 // Check that the template argument list is well-formed for this
3499 // template.
3500 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3501 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3502 DefaultArgs, false, SugaredConverted,
3503 CanonicalConverted,
3504 /*UpdateArgsWithConversions=*/true))
3505 return QualType();
3506
3507 QualType CanonType;
3508
3510 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3511
3512 // Find the canonical type for this type alias template specialization.
3513 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3514 if (Pattern->isInvalidDecl())
3515 return QualType();
3516
3517 // Only substitute for the innermost template argument list. NOTE: Some
3518 // external resugarers rely on leaving a Subst* node here. Make the
3519 // substitution non-final in that case. Note that these external resugarers
3520 // will still miss some information in this representation, because we don't
3521 // provide enough context in the Subst* nodes in order to tell different
3522 // template type alias specializations apart.
3523 MultiLevelTemplateArgumentList TemplateArgLists;
3524 TemplateArgLists.addOuterTemplateArguments(
3525 Template, SugaredConverted,
3526 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3527 TemplateArgLists.addOuterRetainedLevels(
3528 AliasTemplate->getTemplateParameters()->getDepth());
3529
3532 *this, /*PointOfInstantiation=*/TemplateLoc,
3533 /*Entity=*/AliasTemplate,
3534 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3535
3536 // Diagnose uses of this alias.
3537 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3538
3539 if (Inst.isInvalid())
3540 return QualType();
3541
3542 std::optional<ContextRAII> SavedContext;
3543 if (!AliasTemplate->getDeclContext()->isFileContext())
3544 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3545
3546 CanonType =
3547 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3548 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3549 if (CanonType.isNull()) {
3550 // If this was enable_if and we failed to find the nested type
3551 // within enable_if in a SFINAE context, dig out the specific
3552 // enable_if condition that failed and present that instead.
3554 if (auto DeductionInfo = isSFINAEContext()) {
3555 if (*DeductionInfo &&
3556 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3557 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3558 diag::err_typename_nested_not_found_enable_if &&
3559 TemplateArgs[0].getArgument().getKind()
3561 Expr *FailedCond;
3562 std::string FailedDescription;
3563 std::tie(FailedCond, FailedDescription) =
3564 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3565
3566 // Remove the old SFINAE diagnostic.
3567 PartialDiagnosticAt OldDiag =
3569 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3570
3571 // Add a new SFINAE diagnostic specifying which condition
3572 // failed.
3573 (*DeductionInfo)->addSFINAEDiagnostic(
3574 OldDiag.first,
3575 PDiag(diag::err_typename_nested_not_found_requirement)
3576 << FailedDescription
3577 << FailedCond->getSourceRange());
3578 }
3579 }
3580 }
3581
3582 return QualType();
3583 }
3584 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3585 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3586 TemplateLoc, TemplateArgs);
3587 } else if (Name.isDependent() ||
3589 TemplateArgs, CanonicalConverted)) {
3590 // This class template specialization is a dependent
3591 // type. Therefore, its canonical type is another class template
3592 // specialization type that contains all of the converted
3593 // arguments in canonical form. This ensures that, e.g., A<T> and
3594 // A<T, T> have identical types when A is declared as:
3595 //
3596 // template<typename T, typename U = T> struct A;
3598 Name, CanonicalConverted);
3599
3600 // This might work out to be a current instantiation, in which
3601 // case the canonical type needs to be the InjectedClassNameType.
3602 //
3603 // TODO: in theory this could be a simple hashtable lookup; most
3604 // changes to CurContext don't change the set of current
3605 // instantiations.
3606 if (isa<ClassTemplateDecl>(Template)) {
3607 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3608 // If we get out to a namespace, we're done.
3609 if (Ctx->isFileContext()) break;
3610
3611 // If this isn't a record, keep looking.
3612 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3613 if (!Record) continue;
3614
3615 // Look for one of the two cases with InjectedClassNameTypes
3616 // and check whether it's the same template.
3617 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3618 !Record->getDescribedClassTemplate())
3619 continue;
3620
3621 // Fetch the injected class name type and check whether its
3622 // injected type is equal to the type we just built.
3624 QualType Injected = cast<InjectedClassNameType>(ICNT)
3625 ->getInjectedSpecializationType();
3626
3627 if (CanonType != Injected->getCanonicalTypeInternal())
3628 continue;
3629
3630 // If so, the canonical type of this TST is the injected
3631 // class name type of the record we just found.
3632 assert(ICNT.isCanonical());
3633 CanonType = ICNT;
3634 break;
3635 }
3636 }
3637 } else if (ClassTemplateDecl *ClassTemplate =
3638 dyn_cast<ClassTemplateDecl>(Template)) {
3639 // Find the class template specialization declaration that
3640 // corresponds to these arguments.
3641 void *InsertPos = nullptr;
3643 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3644 if (!Decl) {
3645 // This is the first time we have referenced this class template
3646 // specialization. Create the canonical declaration and add it to
3647 // the set of specializations.
3649 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3650 ClassTemplate->getDeclContext(),
3651 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3652 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3653 nullptr);
3654 ClassTemplate->AddSpecialization(Decl, InsertPos);
3655 if (ClassTemplate->isOutOfLine())
3656 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3657 }
3658
3659 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3660 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3661 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3662 if (!Inst.isInvalid()) {
3663 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3664 CanonicalConverted,
3665 /*Final=*/false);
3666 InstantiateAttrsForDecl(TemplateArgLists,
3667 ClassTemplate->getTemplatedDecl(), Decl);
3668 }
3669 }
3670
3671 // Diagnose uses of this specialization.
3672 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3673
3674 CanonType = Context.getTypeDeclType(Decl);
3675 assert(isa<RecordType>(CanonType) &&
3676 "type of non-dependent specialization is not a RecordType");
3677 } else {
3678 llvm_unreachable("Unhandled template kind");
3679 }
3680
3681 // Build the fully-sugared type for this class template
3682 // specialization, which refers back to the class template
3683 // specialization we created or found.
3684 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3685 CanonType);
3686}
3687
3689 TemplateNameKind &TNK,
3690 SourceLocation NameLoc,
3691 IdentifierInfo *&II) {
3692 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3693
3694 TemplateName Name = ParsedName.get();
3695 auto *ATN = Name.getAsAssumedTemplateName();
3696 assert(ATN && "not an assumed template name");
3697 II = ATN->getDeclName().getAsIdentifierInfo();
3698
3699 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3700 // Resolved to a type template name.
3701 ParsedName = TemplateTy::make(Name);
3702 TNK = TNK_Type_template;
3703 }
3704}
3705
3707 SourceLocation NameLoc,
3708 bool Diagnose) {
3709 // We assumed this undeclared identifier to be an (ADL-only) function
3710 // template name, but it was used in a context where a type was required.
3711 // Try to typo-correct it now.
3712 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3713 assert(ATN && "not an assumed template name");
3714
3715 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3716 struct CandidateCallback : CorrectionCandidateCallback {
3717 bool ValidateCandidate(const TypoCorrection &TC) override {
3718 return TC.getCorrectionDecl() &&
3720 }
3721 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3722 return std::make_unique<CandidateCallback>(*this);
3723 }
3724 } FilterCCC;
3725
3726 TypoCorrection Corrected =
3727 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3728 FilterCCC, CTK_ErrorRecovery);
3729 if (Corrected && Corrected.getFoundDecl()) {
3730 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3731 << ATN->getDeclName());
3733 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3735 return false;
3736 }
3737
3738 if (Diagnose)
3739 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3740 return true;
3741}
3742
3744 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3745 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3746 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3747 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3748 bool IsCtorOrDtorName, bool IsClassName,
3749 ImplicitTypenameContext AllowImplicitTypename) {
3750 if (SS.isInvalid())
3751 return true;
3752
3753 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3754 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3755
3756 // C++ [temp.res]p3:
3757 // A qualified-id that refers to a type and in which the
3758 // nested-name-specifier depends on a template-parameter (14.6.2)
3759 // shall be prefixed by the keyword typename to indicate that the
3760 // qualified-id denotes a type, forming an
3761 // elaborated-type-specifier (7.1.5.3).
3762 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3763 // C++2a relaxes some of those restrictions in [temp.res]p5.
3764 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3766 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3767 else
3768 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3769 << SS.getScopeRep() << TemplateII->getName()
3770 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3771 } else
3772 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3773 << SS.getScopeRep() << TemplateII->getName();
3774
3775 // FIXME: This is not quite correct recovery as we don't transform SS
3776 // into the corresponding dependent form (and we don't diagnose missing
3777 // 'template' keywords within SS as a result).
3778 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3779 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3780 TemplateArgsIn, RAngleLoc);
3781 }
3782
3783 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3784 // it's not actually allowed to be used as a type in most cases. Because
3785 // we annotate it before we know whether it's valid, we have to check for
3786 // this case here.
3787 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3788 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3789 Diag(TemplateIILoc,
3790 TemplateKWLoc.isInvalid()
3791 ? diag::err_out_of_line_qualified_id_type_names_constructor
3792 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3793 << TemplateII << 0 /*injected-class-name used as template name*/
3794 << 1 /*if any keyword was present, it was 'template'*/;
3795 }
3796 }
3797
3798 TemplateName Template = TemplateD.get();
3799 if (Template.getAsAssumedTemplateName() &&
3800 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3801 return true;
3802
3803 // Translate the parser's template argument list in our AST format.
3804 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3805 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3806
3807 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3808 assert(SS.getScopeRep() == DTN->getQualifier());
3810 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3811 TemplateArgs.arguments());
3812 // Build type-source information.
3813 TypeLocBuilder TLB;
3818 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3819 SpecTL.setTemplateNameLoc(TemplateIILoc);
3820 SpecTL.setLAngleLoc(LAngleLoc);
3821 SpecTL.setRAngleLoc(RAngleLoc);
3822 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3823 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3825 }
3826
3827 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3828 if (SpecTy.isNull())
3829 return true;
3830
3831 // Build type-source information.
3832 TypeLocBuilder TLB;
3835 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3836 SpecTL.setTemplateNameLoc(TemplateIILoc);
3837 SpecTL.setLAngleLoc(LAngleLoc);
3838 SpecTL.setRAngleLoc(RAngleLoc);
3839 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3840 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3841
3842 // Create an elaborated-type-specifier containing the nested-name-specifier.
3843 QualType ElTy =
3845 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3846 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3848 if (!ElabTL.isEmpty())
3850 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3851}
3852
3854 TypeSpecifierType TagSpec,
3855 SourceLocation TagLoc,
3856 CXXScopeSpec &SS,
3857 SourceLocation TemplateKWLoc,
3858 TemplateTy TemplateD,
3859 SourceLocation TemplateLoc,
3860 SourceLocation LAngleLoc,
3861 ASTTemplateArgsPtr TemplateArgsIn,
3862 SourceLocation RAngleLoc) {
3863 if (SS.isInvalid())
3864 return TypeResult(true);
3865
3866 TemplateName Template = TemplateD.get();
3867
3868 // Translate the parser's template argument list in our AST format.
3869 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3870 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3871
3872 // Determine the tag kind
3874 ElaboratedTypeKeyword Keyword
3876
3877 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3878 assert(SS.getScopeRep() == DTN->getQualifier());
3880 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3881 TemplateArgs.arguments());
3882
3883 // Build type-source information.
3884 TypeLocBuilder TLB;
3887 SpecTL.setElaboratedKeywordLoc(TagLoc);
3889 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3890 SpecTL.setTemplateNameLoc(TemplateLoc);
3891 SpecTL.setLAngleLoc(LAngleLoc);
3892 SpecTL.setRAngleLoc(RAngleLoc);
3893 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3894 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3896 }
3897
3898 if (TypeAliasTemplateDecl *TAT =
3899 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3900 // C++0x [dcl.type.elab]p2:
3901 // If the identifier resolves to a typedef-name or the simple-template-id
3902 // resolves to an alias template specialization, the
3903 // elaborated-type-specifier is ill-formed.
3904 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3905 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3906 Diag(TAT->getLocation(), diag::note_declared_at);
3907 }
3908
3909 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3910 if (Result.isNull())
3911 return TypeResult(true);
3912
3913 // Check the tag kind
3914 if (const RecordType *RT = Result->getAs<RecordType>()) {
3915 RecordDecl *D = RT->getDecl();
3916
3917 IdentifierInfo *Id = D->getIdentifier();
3918 assert(Id && "templated class must have an identifier");
3919
3921 TagLoc, Id)) {
3922 Diag(TagLoc, diag::err_use_with_wrong_tag)
3923 << Result
3924 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3925 Diag(D->getLocation(), diag::note_previous_use);
3926 }
3927 }
3928
3929 // Provide source-location information for the template specialization.
3930 TypeLocBuilder TLB;
3933 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3934 SpecTL.setTemplateNameLoc(TemplateLoc);
3935 SpecTL.setLAngleLoc(LAngleLoc);
3936 SpecTL.setRAngleLoc(RAngleLoc);
3937 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3938 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3939
3940 // Construct an elaborated type containing the nested-name-specifier (if any)
3941 // and tag keyword.
3944 ElabTL.setElaboratedKeywordLoc(TagLoc);
3947}
3948
3949static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3950 NamedDecl *PrevDecl,
3953
3955
3957 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3958 switch (Arg.getKind()) {
3966 return false;
3967
3969 QualType Type = Arg.getAsType();
3970 const TemplateTypeParmType *TPT =
3972 return TPT && !Type.hasQualifiers() &&
3973 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3974 }
3975
3977 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3978 if (!DRE || !DRE->getDecl())
3979 return false;
3980 const NonTypeTemplateParmDecl *NTTP =
3981 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3982 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3983 }
3984
3986 const TemplateTemplateParmDecl *TTP =
3987 dyn_cast_or_null<TemplateTemplateParmDecl>(
3989 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3990 }
3991 llvm_unreachable("unexpected kind of template argument");
3992}
3993
3996 if (Params->size() != Args.size())
3997 return false;
3998
3999 unsigned Depth = Params->getDepth();
4000
4001 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4002 TemplateArgument Arg = Args[I];
4003
4004 // If the parameter is a pack expansion, the argument must be a pack
4005 // whose only element is a pack expansion.
4006 if (Params->getParam(I)->isParameterPack()) {
4007 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4008 !Arg.pack_begin()->isPackExpansion())
4009 return false;
4010 Arg = Arg.pack_begin()->getPackExpansionPattern();
4011 }
4012
4013 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4014 return false;
4015 }
4016
4017 return true;
4018}
4019
4020template<typename PartialSpecDecl>
4021static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4022 if (Partial->getDeclContext()->isDependentContext())
4023 return;
4024
4025 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4026 // for non-substitution-failure issues?
4027 TemplateDeductionInfo Info(Partial->getLocation());
4028 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4029 return;
4030
4031 auto *Template = Partial->getSpecializedTemplate();
4032 S.Diag(Partial->getLocation(),
4033 diag::ext_partial_spec_not_more_specialized_than_primary)
4034 << isa<VarTemplateDecl>(Template);
4035
4036 if (Info.hasSFINAEDiagnostic()) {
4040 SmallString<128> SFINAEArgString;
4041 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4042 S.Diag(Diag.first,
4043 diag::note_partial_spec_not_more_specialized_than_primary)
4044 << SFINAEArgString;
4045 }
4046
4047 S.NoteTemplateLocation(*Template);
4048 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4049 Template->getAssociatedConstraints(TemplateAC);
4050 Partial->getAssociatedConstraints(PartialAC);
4051 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4052 TemplateAC);
4053}
4054
4055static void
4057 const llvm::SmallBitVector &DeducibleParams) {
4058 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4059 if (!DeducibleParams[I]) {
4060 NamedDecl *Param = TemplateParams->getParam(I);
4061 if (Param->getDeclName())
4062 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4063 << Param->getDeclName();
4064 else
4065 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4066 << "(anonymous)";
4067 }
4068 }
4069}
4070
4071
4072template<typename PartialSpecDecl>
4074 PartialSpecDecl *Partial) {
4075 // C++1z [temp.class.spec]p8: (DR1495)
4076 // - The specialization shall be more specialized than the primary
4077 // template (14.5.5.2).
4079
4080 // C++ [temp.class.spec]p8: (DR1315)
4081 // - Each template-parameter shall appear at least once in the
4082 // template-id outside a non-deduced context.
4083 // C++1z [temp.class.spec.match]p3 (P0127R2)
4084 // If the template arguments of a partial specialization cannot be
4085 // deduced because of the structure of its template-parameter-list
4086 // and the template-id, the program is ill-formed.
4087 auto *TemplateParams = Partial->getTemplateParameters();
4088 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4089 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4090 TemplateParams->getDepth(), DeducibleParams);
4091
4092 if (!DeducibleParams.all()) {
4093 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4094 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4095 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4096 << (NumNonDeducible > 1)
4097 << SourceRange(Partial->getLocation(),
4098 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4099 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4100 }
4101}
4102
4105 checkTemplatePartialSpecialization(*this, Partial);
4106}
4107
4110 checkTemplatePartialSpecialization(*this, Partial);
4111}
4112
4114 // C++1z [temp.param]p11:
4115 // A template parameter of a deduction guide template that does not have a
4116 // default-argument shall be deducible from the parameter-type-list of the
4117 // deduction guide template.
4118 auto *TemplateParams = TD->getTemplateParameters();
4119 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4120 MarkDeducedTemplateParameters(TD, DeducibleParams);
4121 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4122 // A parameter pack is deducible (to an empty pack).
4123 auto *Param = TemplateParams->getParam(I);
4124 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4125 DeducibleParams[I] = true;
4126 }
4127
4128 if (!DeducibleParams.all()) {
4129 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4130 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4131 << (NumNonDeducible > 1);
4132 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4133 }
4134}
4135
4138 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4140 // D must be variable template id.
4141 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4142 "Variable template specialization is declared with a template id.");
4143
4144 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4145 TemplateArgumentListInfo TemplateArgs =
4146 makeTemplateArgumentListInfo(*this, *TemplateId);
4147 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4148 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4149 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4150
4151 TemplateName Name = TemplateId->Template.get();
4152
4153 // The template-id must name a variable template.
4155 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4156 if (!VarTemplate) {
4157 NamedDecl *FnTemplate;
4158 if (auto *OTS = Name.getAsOverloadedTemplate())
4159 FnTemplate = *OTS->begin();
4160 else
4161 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4162 if (FnTemplate)
4163 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4164 << FnTemplate->getDeclName();
4165 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4167 }
4168
4169 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4170 auto Message = DSA->getMessage();
4171 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4172 << VarTemplate << !Message.empty() << Message;
4173 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4174 }
4175
4176 // Check for unexpanded parameter packs in any of the template arguments.
4177 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4178 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4182 return true;
4183
4184 // Check that the template argument list is well-formed for this
4185 // template.
4186 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4187 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4188 /*DefaultArgs=*/{}, false, SugaredConverted,
4189 CanonicalConverted,
4190 /*UpdateArgsWithConversions=*/true))
4191 return true;
4192
4193 // Find the variable template (partial) specialization declaration that
4194 // corresponds to these arguments.
4197 TemplateArgs.size(),
4198 CanonicalConverted))
4199 return true;
4200
4201 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4202 // also do them during instantiation.
4203 if (!Name.isDependent() &&
4205 TemplateArgs, CanonicalConverted)) {
4206 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4207 << VarTemplate->getDeclName();
4209 }
4210
4211 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4212 CanonicalConverted) &&
4213 (!Context.getLangOpts().CPlusPlus20 ||
4214 !TemplateParams->hasAssociatedConstraints())) {
4215 // C++ [temp.class.spec]p9b3:
4216 //
4217 // -- The argument list of the specialization shall not be identical
4218 // to the implicit argument list of the primary template.
4219 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4220 << /*variable template*/ 1
4221 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4222 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4223 // FIXME: Recover from this by treating the declaration as a redeclaration
4224 // of the primary template.
4225 return true;
4226 }
4227 }
4228
4229 void *InsertPos = nullptr;
4230 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4231
4233 PrevDecl = VarTemplate->findPartialSpecialization(
4234 CanonicalConverted, TemplateParams, InsertPos);
4235 else
4236 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4237
4239
4240 // Check whether we can declare a variable template specialization in
4241 // the current scope.
4242 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4243 TemplateNameLoc,
4245 return true;
4246
4247 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4248 // Since the only prior variable template specialization with these
4249 // arguments was referenced but not declared, reuse that
4250 // declaration node as our own, updating its source location and
4251 // the list of outer template parameters to reflect our new declaration.
4252 Specialization = PrevDecl;
4253 Specialization->setLocation(TemplateNameLoc);
4254 PrevDecl = nullptr;
4255 } else if (IsPartialSpecialization) {
4256 // Create a new class template partial specialization declaration node.
4258 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4261 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4262 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4263 CanonicalConverted);
4264 Partial->setTemplateArgsAsWritten(TemplateArgs);
4265
4266 if (!PrevPartial)
4267 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4268 Specialization = Partial;
4269
4270 // If we are providing an explicit specialization of a member variable
4271 // template specialization, make a note of that.
4272 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4273 PrevPartial->setMemberSpecialization();
4274
4276 } else {
4277 // Create a new class template specialization declaration node for
4278 // this explicit specialization or friend declaration.
4280 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4281 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4282 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4283
4284 if (!PrevDecl)
4285 VarTemplate->AddSpecialization(Specialization, InsertPos);
4286 }
4287
4288 // C++ [temp.expl.spec]p6:
4289 // If a template, a member template or the member of a class template is
4290 // explicitly specialized then that specialization shall be declared
4291 // before the first use of that specialization that would cause an implicit
4292 // instantiation to take place, in every translation unit in which such a
4293 // use occurs; no diagnostic is required.
4294 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4295 bool Okay = false;
4296 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4297 // Is there any previous explicit specialization declaration?
4299 Okay = true;
4300 break;
4301 }
4302 }
4303
4304 if (!Okay) {
4305 SourceRange Range(TemplateNameLoc, RAngleLoc);
4306 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4307 << Name << Range;
4308
4309 Diag(PrevDecl->getPointOfInstantiation(),
4310 diag::note_instantiation_required_here)
4311 << (PrevDecl->getTemplateSpecializationKind() !=
4313 return true;
4314 }
4315 }
4316
4317 Specialization->setLexicalDeclContext(CurContext);
4318
4319 // Add the specialization into its lexical context, so that it can
4320 // be seen when iterating through the list of declarations in that
4321 // context. However, specializations are not found by name lookup.
4323
4324 // Note that this is an explicit specialization.
4325 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4326
4327 Previous.clear();
4328 if (PrevDecl)
4329 Previous.addDecl(PrevDecl);
4330 else if (Specialization->isStaticDataMember() &&
4331 Specialization->isOutOfLine())
4332 Specialization->setAccess(VarTemplate->getAccess());
4333
4334 return Specialization;
4335}
4336
4337namespace {
4338/// A partial specialization whose template arguments have matched
4339/// a given template-id.
4340struct PartialSpecMatchResult {
4343};
4344} // end anonymous namespace
4345
4348 SourceLocation TemplateNameLoc,
4349 const TemplateArgumentListInfo &TemplateArgs) {
4350 assert(Template && "A variable template id without template?");
4351
4352 // Check that the template argument list is well-formed for this template.
4353 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4355 Template, TemplateNameLoc,
4356 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4357 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4358 /*UpdateArgsWithConversions=*/true))
4359 return true;
4360
4361 // Produce a placeholder value if the specialization is dependent.
4362 if (Template->getDeclContext()->isDependentContext() ||
4364 TemplateArgs, CanonicalConverted))
4365 return DeclResult();
4366
4367 // Find the variable template specialization declaration that
4368 // corresponds to these arguments.
4369 void *InsertPos = nullptr;
4371 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4372 checkSpecializationReachability(TemplateNameLoc, Spec);
4373 // If we already have a variable template specialization, return it.
4374 return Spec;
4375 }
4376
4377 // This is the first time we have referenced this variable template
4378 // specialization. Create the canonical declaration and add it to
4379 // the set of specializations, based on the closest partial specialization
4380 // that it represents. That is,
4381 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4382 const TemplateArgumentList *PartialSpecArgs = nullptr;
4383 bool AmbiguousPartialSpec = false;
4384 typedef PartialSpecMatchResult MatchResult;
4386 SourceLocation PointOfInstantiation = TemplateNameLoc;
4387 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4388 /*ForTakingAddress=*/false);
4389
4390 // 1. Attempt to find the closest partial specialization that this
4391 // specializes, if any.
4392 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4393 // Perhaps better after unification of DeduceTemplateArguments() and
4394 // getMoreSpecializedPartialSpecialization().
4396 Template->getPartialSpecializations(PartialSpecs);
4397
4398 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4399 // C++ [temp.spec.partial.member]p2:
4400 // If the primary member template is explicitly specialized for a given
4401 // (implicit) specialization of the enclosing class template, the partial
4402 // specializations of the member template are ignored for this
4403 // specialization of the enclosing class template. If a partial
4404 // specialization of the member template is explicitly specialized for a
4405 // given (implicit) specialization of the enclosing class template, the
4406 // primary member template and its other partial specializations are still
4407 // considered for this specialization of the enclosing class template.
4408 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4409 !Partial->getMostRecentDecl()->isMemberSpecialization())
4410 continue;
4411
4412 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4413
4415 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4417 // Store the failed-deduction information for use in diagnostics, later.
4418 // TODO: Actually use the failed-deduction info?
4419 FailedCandidates.addCandidate().set(
4420 DeclAccessPair::make(Template, AS_public), Partial,
4422 (void)Result;
4423 } else {
4424 Matched.push_back(PartialSpecMatchResult());
4425 Matched.back().Partial = Partial;
4426 Matched.back().Args = Info.takeSugared();
4427 }
4428 }
4429
4430 if (Matched.size() >= 1) {
4431 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4432 if (Matched.size() == 1) {
4433 // -- If exactly one matching specialization is found, the
4434 // instantiation is generated from that specialization.
4435 // We don't need to do anything for this.
4436 } else {
4437 // -- If more than one matching specialization is found, the
4438 // partial order rules (14.5.4.2) are used to determine
4439 // whether one of the specializations is more specialized
4440 // than the others. If none of the specializations is more
4441 // specialized than all of the other matching
4442 // specializations, then the use of the variable template is
4443 // ambiguous and the program is ill-formed.
4445 PEnd = Matched.end();
4446 P != PEnd; ++P) {
4447 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4448 PointOfInstantiation) ==
4449 P->Partial)
4450 Best = P;
4451 }
4452
4453 // Determine if the best partial specialization is more specialized than
4454 // the others.
4455 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4456 PEnd = Matched.end();
4457 P != PEnd; ++P) {
4459 P->Partial, Best->Partial,
4460 PointOfInstantiation) != Best->Partial) {
4461 AmbiguousPartialSpec = true;
4462 break;
4463 }
4464 }
4465 }
4466
4467 // Instantiate using the best variable template partial specialization.
4468 InstantiationPattern = Best->Partial;
4469 PartialSpecArgs = Best->Args;
4470 } else {
4471 // -- If no match is found, the instantiation is generated
4472 // from the primary template.
4473 // InstantiationPattern = Template->getTemplatedDecl();
4474 }
4475
4476 // 2. Create the canonical declaration.
4477 // Note that we do not instantiate a definition until we see an odr-use
4478 // in DoMarkVarDeclReferenced().
4479 // FIXME: LateAttrs et al.?
4481 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4482 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4483 if (!Decl)
4484 return true;
4485
4486 if (AmbiguousPartialSpec) {
4487 // Partial ordering did not produce a clear winner. Complain.
4489 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4490 << Decl;
4491
4492 // Print the matching partial specializations.
4493 for (MatchResult P : Matched)
4494 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4495 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4496 *P.Args);
4497 return true;
4498 }
4499
4501 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4502 Decl->setInstantiationOf(D, PartialSpecArgs);
4503
4504 checkSpecializationReachability(TemplateNameLoc, Decl);
4505
4506 assert(Decl && "No variable template specialization?");
4507 return Decl;
4508}
4509
4511 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4512 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4513 const TemplateArgumentListInfo *TemplateArgs) {
4514
4515 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4516 *TemplateArgs);
4517 if (Decl.isInvalid())
4518 return ExprError();
4519
4520 if (!Decl.get())
4521 return ExprResult();
4522
4523 VarDecl *Var = cast<VarDecl>(Decl.get());
4526 NameInfo.getLoc());
4527
4528 // Build an ordinary singleton decl ref.
4529 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4530}
4531
4534 Diag(Loc, diag::err_template_missing_args)
4535 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4536 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4537 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4538 }
4539}
4540
4542 bool TemplateKeyword,
4543 TemplateDecl *TD,
4546 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4548}
4549
4552 SourceLocation TemplateKWLoc,
4553 const DeclarationNameInfo &ConceptNameInfo,
4554 NamedDecl *FoundDecl,
4555 ConceptDecl *NamedConcept,
4556 const TemplateArgumentListInfo *TemplateArgs) {
4557 assert(NamedConcept && "A concept template id without a template?");
4558
4559 if (NamedConcept->isInvalidDecl())
4560 return ExprError();
4561
4562 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4564 NamedConcept, ConceptNameInfo.getLoc(),
4565 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4566 /*DefaultArgs=*/{},
4567 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4568 /*UpdateArgsWithConversions=*/false))
4569 return ExprError();
4570
4571 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4572
4574 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4575 CanonicalConverted);
4576 ConstraintSatisfaction Satisfaction;
4577 bool AreArgsDependent =
4579 *TemplateArgs, CanonicalConverted);
4580 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4581 /*Final=*/false);
4583
4586
4587 if (!AreArgsDependent &&
4589 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4590 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4591 TemplateArgs->getRAngleLoc()),
4592 Satisfaction))
4593 return ExprError();
4594 auto *CL = ConceptReference::Create(
4595 Context,
4597 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4600 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4601}
4602
4604 SourceLocation TemplateKWLoc,
4605 LookupResult &R,
4606 bool RequiresADL,
4607 const TemplateArgumentListInfo *TemplateArgs) {
4608 // FIXME: Can we do any checking at this point? I guess we could check the
4609 // template arguments that we have against the template name, if the template
4610 // name refers to a single template. That's not a terribly common case,
4611 // though.
4612 // foo<int> could identify a single function unambiguously
4613 // This approach does NOT work, since f<int>(1);
4614 // gets resolved prior to resorting to overload resolution
4615 // i.e., template<class T> void f(double);
4616 // vs template<class T, class U> void f(U);
4617
4618 // These should be filtered out by our callers.
4619 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4620
4621 // Non-function templates require a template argument list.
4622 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4623 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4625 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4626 return ExprError();
4627 }
4628 }
4629 bool KnownDependent = false;
4630 // In C++1y, check variable template ids.
4631 if (R.getAsSingle<VarTemplateDecl>()) {
4634 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4635 if (Res.isInvalid() || Res.isUsable())
4636 return Res;
4637 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4638 KnownDependent = true;
4639 }
4640
4641 if (R.getAsSingle<ConceptDecl>()) {
4642 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4644 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4645 }
4646
4647 // We don't want lookup warnings at this point.
4649
4652 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4653 R.begin(), R.end(), KnownDependent,
4654 /*KnownInstantiationDependent=*/false);
4655
4656 // Model the templates with UnresolvedTemplateTy. The expression should then
4657 // either be transformed in an instantiation or be diagnosed in
4658 // CheckPlaceholderExpr.
4659 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4662
4663 return ULE;
4664}
4665
4667 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4668 const DeclarationNameInfo &NameInfo,
4669 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4670 assert(TemplateArgs || TemplateKWLoc.isValid());
4671
4672 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4673 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4674 /*EnteringContext=*/false, TemplateKWLoc))
4675 return ExprError();
4676
4677 if (R.isAmbiguous())
4678 return ExprError();
4679
4681 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4682
4683 if (R.empty()) {
4685 Diag(NameInfo.getLoc(), diag::err_no_member)
4686 << NameInfo.getName() << DC << SS.getRange();
4687 return ExprError();
4688 }
4689
4690 // If necessary, build an implicit class member access.
4691 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4692 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4693 /*S=*/nullptr);
4694
4695 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4696}
4697
4699 CXXScopeSpec &SS,
4700 SourceLocation TemplateKWLoc,
4701 const UnqualifiedId &Name,
4702 ParsedType ObjectType,
4703 bool EnteringContext,
4705 bool AllowInjectedClassName) {
4706 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4707 Diag(TemplateKWLoc,
4709 diag::warn_cxx98_compat_template_outside_of_template :
4710 diag::ext_template_outside_of_template)
4711 << FixItHint::CreateRemoval(TemplateKWLoc);
4712
4713 if (SS.isInvalid())
4714 return TNK_Non_template;
4715
4716 // Figure out where isTemplateName is going to look.
4717 DeclContext *LookupCtx = nullptr;
4718 if (SS.isNotEmpty())
4719 LookupCtx = computeDeclContext(SS, EnteringContext);
4720 else if (ObjectType)
4721 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4722
4723 // C++0x [temp.names]p5:
4724 // If a name prefixed by the keyword template is not the name of
4725 // a template, the program is ill-formed. [Note: the keyword
4726 // template may not be applied to non-template members of class
4727 // templates. -end note ] [ Note: as is the case with the
4728 // typename prefix, the template prefix is allowed in cases
4729 // where it is not strictly necessary; i.e., when the
4730 // nested-name-specifier or the expression on the left of the ->
4731 // or . is not dependent on a template-parameter, or the use
4732 // does not appear in the scope of a template. -end note]
4733 //
4734 // Note: C++03 was more strict here, because it banned the use of
4735 // the "template" keyword prior to a template-name that was not a
4736 // dependent name. C++ DR468 relaxed this requirement (the
4737 // "template" keyword is now permitted). We follow the C++0x
4738 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4739 bool MemberOfUnknownSpecialization;
4740 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4741 ObjectType, EnteringContext, Result,
4742 MemberOfUnknownSpecialization);
4743 if (TNK != TNK_Non_template) {
4744 // We resolved this to a (non-dependent) template name. Return it.
4745 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4746 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4747 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4748 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4749 // C++14 [class.qual]p2:
4750 // In a lookup in which function names are not ignored and the
4751 // nested-name-specifier nominates a class C, if the name specified
4752 // [...] is the injected-class-name of C, [...] the name is instead
4753 // considered to name the constructor
4754 //
4755 // We don't get here if naming the constructor would be valid, so we
4756 // just reject immediately and recover by treating the
4757 // injected-class-name as naming the template.
4758 Diag(Name.getBeginLoc(),
4759 diag::ext_out_of_line_qualified_id_type_names_constructor)
4760 << Name.Identifier
4761 << 0 /*injected-class-name used as template name*/
4762 << TemplateKWLoc.isValid();
4763 }
4764 return TNK;
4765 }
4766
4767 if (!MemberOfUnknownSpecialization) {
4768 // Didn't find a template name, and the lookup wasn't dependent.
4769 // Do the lookup again to determine if this is a "nothing found" case or
4770 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4771 // need to do this.
4773 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4775 // Tell LookupTemplateName that we require a template so that it diagnoses
4776 // cases where it finds a non-template.
4777 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4778 ? RequiredTemplateKind(TemplateKWLoc)
4780 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4781 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4782 !R.isAmbiguous()) {
4783 if (LookupCtx)
4784 Diag(Name.getBeginLoc(), diag::err_no_member)
4785 << DNI.getName() << LookupCtx << SS.getRange();
4786 else
4787 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4788 << DNI.getName() << SS.getRange();
4789 }
4790 return TNK_Non_template;
4791 }
4792
4793 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4794
4795 switch (Name.getKind()) {
4798 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4800
4803 Qualifier, Name.OperatorFunctionId.Operator));
4804 return TNK_Function_template;
4805
4807 // This is a kind of template name, but can never occur in a dependent
4808 // scope (literal operators can only be declared at namespace scope).
4809 break;
4810
4811 default:
4812 break;
4813 }
4814
4815 // This name cannot possibly name a dependent template. Diagnose this now
4816 // rather than building a dependent template name that can never be valid.
4817 Diag(Name.getBeginLoc(),
4818 diag::err_template_kw_refers_to_dependent_non_template)
4819 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4820 << TemplateKWLoc.isValid() << TemplateKWLoc;
4821 return TNK_Non_template;
4822}
4823
4826 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4827 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4828 const TemplateArgument &Arg = AL.getArgument();
4829 QualType ArgType;
4830 TypeSourceInfo *TSI = nullptr;
4831
4832 // Check template type parameter.
4833 switch(Arg.getKind()) {
4835 // C++ [temp.arg.type]p1:
4836 // A template-argument for a template-parameter which is a
4837 // type shall be a type-id.
4838 ArgType = Arg.getAsType();
4839 TSI = AL.getTypeSourceInfo();
4840 break;
4843 // We have a template type parameter but the template argument
4844 // is a template without any arguments.
4845 SourceRange SR = AL.getSourceRange();
4848 return true;
4849 }
4851 // We have a template type parameter but the template argument is an
4852 // expression; see if maybe it is missing the "typename" keyword.
4853 CXXScopeSpec SS;
4854 DeclarationNameInfo NameInfo;
4855
4856 if (DependentScopeDeclRefExpr *ArgExpr =
4857 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4858 SS.Adopt(ArgExpr->getQualifierLoc());
4859 NameInfo = ArgExpr->getNameInfo();
4860 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4861 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4862 if (ArgExpr->isImplicitAccess()) {
4863 SS.Adopt(ArgExpr->getQualifierLoc());
4864 NameInfo = ArgExpr->getMemberNameInfo();
4865 }
4866 }
4867
4868 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4869 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4870 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4871
4872 if (Result.getAsSingle<TypeDecl>() ||
4873 Result.wasNotFoundInCurrentInstantiation()) {
4874 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4875 // Suggest that the user add 'typename' before the NNS.
4877 Diag(Loc, getLangOpts().MSVCCompat
4878 ? diag::ext_ms_template_type_arg_missing_typename
4879 : diag::err_template_arg_must_be_type_suggest)
4880 << FixItHint::CreateInsertion(Loc, "typename ");
4882
4883 // Recover by synthesizing a type using the location information that we
4884 // already have.
4886 SS.getScopeRep(), II);
4887 TypeLocBuilder TLB;
4889 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4891 TL.setNameLoc(NameInfo.getLoc());
4892 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4893
4894 // Overwrite our input TemplateArgumentLoc so that we can recover
4895 // properly.
4898
4899 break;
4900 }
4901 }
4902 // fallthrough
4903 [[fallthrough]];
4904 }
4905 default: {
4906 // We allow instantiateing a template with template argument packs when
4907 // building deduction guides.
4908 if (Arg.getKind() == TemplateArgument::Pack &&
4909 CodeSynthesisContexts.back().Kind ==
4911 SugaredConverted.push_back(Arg);
4912 CanonicalConverted.push_back(Arg);
4913 return false;
4914 }
4915 // We have a template type parameter but the template argument
4916 // is not a type.
4917 SourceRange SR = AL.getSourceRange();
4918 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4920
4921 return true;
4922 }
4923 }
4924
4925 if (CheckTemplateArgument(TSI))
4926 return true;
4927
4928 // Objective-C ARC:
4929 // If an explicitly-specified template argument type is a lifetime type
4930 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4931 if (getLangOpts().ObjCAutoRefCount &&
4932 ArgType->isObjCLifetimeType() &&
4933 !ArgType.getObjCLifetime()) {
4934 Qualifiers Qs;
4936 ArgType = Context.getQualifiedType(ArgType, Qs);
4937 }
4938
4939 SugaredConverted.push_back(TemplateArgument(ArgType));
4940 CanonicalConverted.push_back(
4942 return false;
4943}
4944
4945/// Substitute template arguments into the default template argument for
4946/// the given template type parameter.
4947///
4948/// \param SemaRef the semantic analysis object for which we are performing
4949/// the substitution.
4950///
4951/// \param Template the template that we are synthesizing template arguments
4952/// for.
4953///
4954/// \param TemplateLoc the location of the template name that started the
4955/// template-id we are checking.
4956///
4957/// \param RAngleLoc the location of the right angle bracket ('>') that
4958/// terminates the template-id.
4959///
4960/// \param Param the template template parameter whose default we are
4961/// substituting into.
4962///
4963/// \param Converted the list of template arguments provided for template
4964/// parameters that precede \p Param in the template parameter list.
4965///
4966/// \param Output the resulting substituted template argument.
4967///
4968/// \returns true if an error occurred.
4970 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4971 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4972 ArrayRef<TemplateArgument> SugaredConverted,
4973 ArrayRef<TemplateArgument> CanonicalConverted,
4974 TemplateArgumentLoc &Output) {
4975 Output = Param->getDefaultArgument();
4976
4977 // If the argument type is dependent, instantiate it now based
4978 // on the previously-computed template arguments.
4979 if (Output.getArgument().isInstantiationDependent()) {
4980 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4981 SugaredConverted,
4982 SourceRange(TemplateLoc, RAngleLoc));
4983 if (Inst.isInvalid())
4984 return true;
4985
4986 // Only substitute for the innermost template argument list.
4987 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4988 /*Final=*/true);
4989 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4990 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4991
4992 bool ForLambdaCallOperator = false;
4993 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4994 ForLambdaCallOperator = Rec->isLambda();
4995 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4996 !ForLambdaCallOperator);
4997
4998 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4999 Param->getDefaultArgumentLoc(),
5000 Param->getDeclName()))
5001 return true;
5002 }
5003
5004 return false;
5005}
5006
5007/// Substitute template arguments into the default template argument for
5008/// the given non-type template parameter.
5009///
5010/// \param SemaRef the semantic analysis object for which we are performing
5011/// the substitution.
5012///
5013/// \param Template the template that we are synthesizing template arguments
5014/// for.
5015///
5016/// \param TemplateLoc the location of the template name that started the
5017/// template-id we are checking.
5018///
5019/// \param RAngleLoc the location of the right angle bracket ('>') that
5020/// terminates the template-id.
5021///
5022/// \param Param the non-type template parameter whose default we are
5023/// substituting into.
5024///
5025/// \param Converted the list of template arguments provided for template
5026/// parameters that precede \p Param in the template parameter list.
5027///
5028/// \returns the substituted template argument, or NULL if an error occurred.
5030 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5031 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5032 ArrayRef<TemplateArgument> SugaredConverted,
5033 ArrayRef<TemplateArgument> CanonicalConverted,
5034 TemplateArgumentLoc &Output) {
5035 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5036 SugaredConverted,
5037 SourceRange(TemplateLoc, RAngleLoc));
5038 if (Inst.isInvalid())
5039 return true;
5040
5041 // Only substitute for the innermost template argument list.
5042 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5043 /*Final=*/true);
5044 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5045 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5046
5047 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5048 EnterExpressionEvaluationContext ConstantEvaluated(
5050 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5051 TemplateArgLists, Output);
5052}
5053
5054/// Substitute template arguments into the default template argument for
5055/// the given template template parameter.
5056///
5057/// \param SemaRef the semantic analysis object for which we are performing
5058/// the substitution.
5059///
5060/// \param Template the template that we are synthesizing template arguments
5061/// for.
5062///
5063/// \param TemplateLoc the location of the template name that started the
5064/// template-id we are checking.
5065///
5066/// \param RAngleLoc the location of the right angle bracket ('>') that
5067/// terminates the template-id.
5068///
5069/// \param Param the template template parameter whose default we are
5070/// substituting into.
5071///
5072/// \param Converted the list of template arguments provided for template
5073/// parameters that precede \p Param in the template parameter list.
5074///
5075/// \param QualifierLoc Will be set to the nested-name-specifier (with
5076/// source-location information) that precedes the template name.
5077///
5078/// \returns the substituted template argument, or NULL if an error occurred.
5080 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5081 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5082 ArrayRef<TemplateArgument> SugaredConverted,
5083 ArrayRef<TemplateArgument> CanonicalConverted,
5084 NestedNameSpecifierLoc &QualifierLoc) {
5086 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5087 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5088 if (Inst.isInvalid())
5089 return TemplateName();
5090
5091 // Only substitute for the innermost template argument list.
5092 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5093 /*Final=*/true);
5094 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5095 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5096
5097 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5098 // Substitute into the nested-name-specifier first,
5099 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5100 if (QualifierLoc) {
5101 QualifierLoc =
5102 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5103 if (!QualifierLoc)
5104 return TemplateName();
5105 }
5106
5107 return SemaRef.SubstTemplateName(
5108 QualifierLoc,
5111 TemplateArgLists);
5112}
5113
5115 TemplateDecl *Template, SourceLocation TemplateLoc,
5116 SourceLocation RAngleLoc, Decl *Param,
5117 ArrayRef<TemplateArgument> SugaredConverted,
5118 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5119 HasDefaultArg = false;
5120
5121 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5122 if (!hasReachableDefaultArgument(TypeParm))
5123 return TemplateArgumentLoc();
5124
5125 HasDefaultArg = true;
5126 TemplateArgumentLoc Output;
5127 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5128 TypeParm, SugaredConverted,
5129 CanonicalConverted, Output))
5130 return TemplateArgumentLoc();
5131 return Output;
5132 }
5133
5134 if (NonTypeTemplateParmDecl *NonTypeParm
5135 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5136 if (!hasReachableDefaultArgument(NonTypeParm))
5137 return TemplateArgumentLoc();
5138
5139 HasDefaultArg = true;
5140 TemplateArgumentLoc Output;
5141 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5142 NonTypeParm, SugaredConverted,
5143 CanonicalConverted, Output))
5144 return TemplateArgumentLoc();
5145 return Output;
5146 }
5147
5148 TemplateTemplateParmDecl *TempTempParm
5149 = cast<TemplateTemplateParmDecl>(Param);
5150 if (!hasReachableDefaultArgument(TempTempParm))
5151 return TemplateArgumentLoc();
5152
5153 HasDefaultArg = true;
5154 NestedNameSpecifierLoc QualifierLoc;
5156 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5157 CanonicalConverted, QualifierLoc);
5158 if (TName.isNull())
5159 return TemplateArgumentLoc();
5160
5161 return TemplateArgumentLoc(
5162 Context, TemplateArgument(TName),
5164 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5165}
5166
5167/// Convert a template-argument that we parsed as a type into a template, if
5168/// possible. C++ permits injected-class-names to perform dual service as
5169/// template template arguments and as template type arguments.
5172 // Extract and step over any surrounding nested-name-specifier.
5173 NestedNameSpecifierLoc QualLoc;
5174 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5175 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5176 return TemplateArgumentLoc();
5177
5178 QualLoc = ETLoc.getQualifierLoc();
5179 TLoc = ETLoc.getNamedTypeLoc();
5180 }
5181 // If this type was written as an injected-class-name, it can be used as a
5182 // template template argument.
5183 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5184 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5185 QualLoc, InjLoc.getNameLoc());
5186
5187 // If this type was written as an injected-class-name, it may have been
5188 // converted to a RecordType during instantiation. If the RecordType is
5189 // *not* wrapped in a TemplateSpecializationType and denotes a class
5190 // template specialization, it must have come from an injected-class-name.
5191 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5192 if (auto *CTSD =
5193 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5194 return TemplateArgumentLoc(Context,
5195 TemplateName(CTSD->getSpecializedTemplate()),
5196 QualLoc, RecLoc.getNameLoc());
5197
5198 return TemplateArgumentLoc();
5199}
5200
5202 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5203 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5204 unsigned ArgumentPackIndex,
5205 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5206 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5208 // Check template type parameters.
5209 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5210 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5211 CanonicalConverted);
5212
5213 // Check non-type template parameters.
5214 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5215 // Do substitution on the type of the non-type template parameter
5216 // with the template arguments we've seen thus far. But if the
5217 // template has a dependent context then we cannot substitute yet.
5218 QualType NTTPType = NTTP->getType();
5219 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5220 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5221
5222 if (NTTPType->isInstantiationDependentType() &&
5223 !isa<TemplateTemplateParmDecl>(Template) &&
5224 !Template->getDeclContext()->isDependentContext()) {
5225 // Do substitution on the type of the non-type template parameter.
5226 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5227 SugaredConverted,
5228 SourceRange(TemplateLoc, RAngleLoc));
5229 if (Inst.isInvalid())
5230 return true;
5231
5232 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5233 /*Final=*/true);
5234 // If the parameter is a pack expansion, expand this slice of the pack.
5235 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5237 ArgumentPackIndex);
5238 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5239 NTTP->getDeclName());
5240 } else {
5241 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5242 NTTP->getDeclName());
5243 }
5244
5245 // If that worked, check the non-type template parameter type
5246 // for validity.
5247 if (!NTTPType.isNull())
5248 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5249 NTTP->getLocation());
5250 if (NTTPType.isNull())
5251 return true;
5252 }
5253
5254 switch (Arg.getArgument().getKind()) {
5256 llvm_unreachable("Should never see a NULL template argument here");
5257
5259 Expr *E = Arg.getArgument().getAsExpr();
5260 TemplateArgument SugaredResult, CanonicalResult;
5261 unsigned CurSFINAEErrors = NumSFINAEErrors;
5262 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5263 CanonicalResult, CTAK);
5264 if (Res.isInvalid())
5265 return true;
5266 // If the current template argument causes an error, give up now.
5267 if (CurSFINAEErrors < NumSFINAEErrors)
5268 return true;
5269
5270 // If the resulting expression is new, then use it in place of the
5271 // old expression in the template argument.
5272 if (Res.get() != E) {
5273 TemplateArgument TA(Res.get());
5274 Arg = TemplateArgumentLoc(TA, Res.get());
5275 }
5276
5277 SugaredConverted.push_back(SugaredResult);
5278 CanonicalConverted.push_back(CanonicalResult);
5279 break;
5280 }
5281
5286 // We've already checked this template argument, so just copy
5287 // it to the list of converted arguments.
5288 SugaredConverted.push_back(Arg.getArgument());
5289 CanonicalConverted.push_back(
5291 break;
5292
5295 // We were given a template template argument. It may not be ill-formed;
5296 // see below.
5297 if (DependentTemplateName *DTN
5300 // We have a template argument such as \c T::template X, which we
5301 // parsed as a template template argument. However, since we now
5302 // know that we need a non-type template argument, convert this
5303 // template name into an expression.
5304
5305 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5306 Arg.getTemplateNameLoc());
5307
5308 CXXScopeSpec SS;
5310 // FIXME: the template-template arg was a DependentTemplateName,
5311 // so it was provided with a template keyword. However, its source
5312 // location is not stored in the template argument structure.
5313 SourceLocation TemplateKWLoc;
5315 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5316 nullptr);
5317
5318 // If we parsed the template argument as a pack expansion, create a
5319 // pack expansion expression.
5322 if (E.isInvalid())
5323 return true;
5324 }
5325
5326 TemplateArgument SugaredResult, CanonicalResult;
5327 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5328 CanonicalResult, CTAK_Specified);
5329 if (E.isInvalid())
5330 return true;
5331
5332 SugaredConverted.push_back(SugaredResult);
5333 CanonicalConverted.push_back(CanonicalResult);
5334 break;
5335 }
5336
5337 // We have a template argument that actually does refer to a class
5338 // template, alias template, or template template parameter, and
5339 // therefore cannot be a non-type template argument.
5340 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5341 << Arg.getSourceRange();
5343
5344 return true;
5345
5347 // We have a non-type template parameter but the template
5348 // argument is a type.
5349
5350 // C++ [temp.arg]p2:
5351 // In a template-argument, an ambiguity between a type-id and
5352 // an expression is resolved to a type-id, regardless of the
5353 // form of the corresponding template-parameter.
5354 //
5355 // We warn specifically about this case, since it can be rather
5356 // confusing for users.
5357 QualType T = Arg.getArgument().getAsType();
5358 SourceRange SR = Arg.getSourceRange();
5359 if (T->isFunctionType())
5360 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5361 else
5362 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5364 return true;
5365 }
5366
5368 llvm_unreachable("Caller must expand template argument packs");
5369 }
5370
5371 return false;
5372 }
5373
5374
5375 // Check template template parameters.
5376 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5377
5378 TemplateParameterList *Params = TempParm->getTemplateParameters();
5379 if (TempParm->isExpandedParameterPack())
5380 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5381
5382 // Substitute into the template parameter list of the template
5383 // template parameter, since previously-supplied template arguments
5384 // may appear within the template template parameter.
5385 //
5386 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5387 {
5388 // Set up a template instantiation context.
5390 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5391 SugaredConverted,
5392 SourceRange(TemplateLoc, RAngleLoc));
5393 if (Inst.isInvalid())
5394 return true;
5395
5396 Params =
5399 Template, SugaredConverted, /*Final=*/true),
5400 /*EvaluateConstraints=*/false);
5401 if (!Params)
5402 return true;
5403 }
5404
5405 // C++1z [temp.local]p1: (DR1004)
5406 // When [the injected-class-name] is used [...] as a template-argument for
5407 // a template template-parameter [...] it refers to the class template
5408 // itself.
5412 if (!ConvertedArg.getArgument().isNull())
5413 Arg = ConvertedArg;
5414 }
5415
5416 switch (Arg.getArgument().getKind()) {
5418 llvm_unreachable("Should never see a NULL template argument here");
5419
5422 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5423 /*IsDeduced=*/CTAK != CTAK_Specified))
5424 return true;
5425
5426 SugaredConverted.push_back(Arg.getArgument());
5427 CanonicalConverted.push_back(
5429 break;
5430
5433 // We have a template template parameter but the template
5434 // argument does not refer to a template.
5435 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5436 << getLangOpts().CPlusPlus11;
5437 return true;
5438
5443 llvm_unreachable("non-type argument with template template parameter");
5444
5446 llvm_unreachable("Caller must expand template argument packs");
5447 }
5448
5449 return false;
5450}
5451
5452/// Diagnose a missing template argument.
5453template<typename TemplateParmDecl>
5455 TemplateDecl *TD,
5456 const TemplateParmDecl *D,
5458 // Dig out the most recent declaration of the template parameter; there may be
5459 // declarations of the template that are more recent than TD.
5460 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5461 ->getTemplateParameters()
5462 ->getParam(D->getIndex()));
5463
5464 // If there's a default argument that's not reachable, diagnose that we're
5465 // missing a module import.
5467 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5468 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5469 D->getDefaultArgumentLoc(), Modules,
5471 /*Recover*/true);
5472 return true;
5473 }
5474
5475 // FIXME: If there's a more recent default argument that *is* visible,
5476 // diagnose that it was declared too late.
5477
5479
5480 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5481 << /*not enough args*/0
5483 << TD;
5484 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5485 return true;
5486}
5487
5488/// Check that the given template argument list is well-formed
5489/// for specializing the given template.
5491 TemplateDecl *Template, SourceLocation TemplateLoc,
5492 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5493 bool PartialTemplateArgs,
5494 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5495 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5496 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5497 bool PartialOrderingTTP) {
5498
5500 *ConstraintsNotSatisfied = false;
5501
5502 // Make a copy of the template arguments for processing. Only make the
5503 // changes at the end when successful in matching the arguments to the
5504 // template.
5505 TemplateArgumentListInfo NewArgs = TemplateArgs;
5506
5508
5509 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5510
5511 // C++ [temp.arg]p1:
5512 // [...] The type and form of each template-argument specified in
5513 // a template-id shall match the type and form specified for the
5514 // corresponding parameter declared by the template in its
5515 // template-parameter-list.
5516 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5517 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5518 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5519 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5520 LocalInstantiationScope InstScope(*this, true);
5521 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5522 ParamEnd = Params->end(),
5523 Param = ParamBegin;
5524 Param != ParamEnd;
5525 /* increment in loop */) {
5526 if (size_t ParamIdx = Param - ParamBegin;
5527 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5528 // All written arguments should have been consumed by this point.
5529 assert(ArgIdx == NumArgs && "bad default argument deduction");
5530 // FIXME: Don't ignore parameter packs.
5531 if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5532 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5533 // Default arguments from a DeducedTemplateName are already converted.
5534 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5535 SugaredConverted.push_back(DefArg);
5536 CanonicalConverted.push_back(
5538 ++Param;
5539 }
5540 continue;
5541 }
5542 }
5543
5544 // If we have an expanded parameter pack, make sure we don't have too
5545 // many arguments.
5546 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5547 if (*Expansions == SugaredArgumentPack.size()) {
5548 // We're done with this parameter pack. Pack up its arguments and add
5549 // them to the list.
5550 SugaredConverted.push_back(
5551 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5552 SugaredArgumentPack.clear();
5553
5554 CanonicalConverted.push_back(
5555 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5556 CanonicalArgumentPack.clear();
5557
5558 // This argument is assigned to the next parameter.
5559 ++Param;
5560 continue;
5561 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5562 // Not enough arguments for this parameter pack.
5563 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5564 << /*not enough args*/0
5566 << Template;
5567 NoteTemplateLocation(*Template, Params->getSourceRange());
5568 return true;
5569 }
5570 }
5571
5572 if (ArgIdx < NumArgs) {
5573 // Check the template argument we were given.
5574 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5575 RAngleLoc, SugaredArgumentPack.size(),
5576 SugaredConverted, CanonicalConverted,
5578 return true;
5579
5580 CanonicalConverted.back().setIsDefaulted(
5582 Context, NewArgs[ArgIdx].getArgument(), *Param,
5583 CanonicalConverted, Params->getDepth()));
5584
5585 bool PackExpansionIntoNonPack =
5586 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5587 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5588 // CWG1430: Don't diagnose this pack expansion when partial
5589 // ordering template template parameters. Some uses of the template could
5590 // be valid, and invalid uses will be diagnosed later during
5591 // instantiation.
5592 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5593 (isa<TypeAliasTemplateDecl>(Template) ||
5594 isa<ConceptDecl>(Template))) {
5595 // CWG1430: we have a pack expansion as an argument to an
5596 // alias template, and it's not part of a parameter pack. This
5597 // can't be canonicalized, so reject it now.
5598 // As for concepts - we cannot normalize constraints where this
5599 // situation exists.
5600 Diag(NewArgs[ArgIdx].getLocation(),
5601 diag::err_template_expansion_into_fixed_list)
5602 << (isa<ConceptDecl>(Template) ? 1 : 0)
5603 << NewArgs[ArgIdx].getSourceRange();
5605 return true;
5606 }
5607
5608 // We're now done with this argument.
5609 ++ArgIdx;
5610
5611 if ((*Param)->isTemplateParameterPack()) {
5612 // The template parameter was a template parameter pack, so take the
5613 // deduced argument and place it on the argument pack. Note that we
5614 // stay on the same template parameter so that we can deduce more
5615 // arguments.
5616 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5617 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5618 } else {
5619 // Move to the next template parameter.
5620 ++Param;
5621 }
5622
5623 // If we just saw a pack expansion into a non-pack, then directly convert
5624 // the remaining arguments, because we don't know what parameters they'll
5625 // match up with.
5626 if (PackExpansionIntoNonPack) {
5627 if (!SugaredArgumentPack.empty()) {
5628 // If we were part way through filling in an expanded parameter pack,
5629 // fall back to just producing individual arguments.
5630 SugaredConverted.insert(SugaredConverted.end(),
5631 SugaredArgumentPack.begin(),
5632 SugaredArgumentPack.end());
5633 SugaredArgumentPack.clear();
5634
5635 CanonicalConverted.insert(CanonicalConverted.end(),
5636 CanonicalArgumentPack.begin(),
5637 CanonicalArgumentPack.end());
5638 CanonicalArgumentPack.clear();
5639 }
5640
5641 while (ArgIdx < NumArgs) {
5642 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5643 SugaredConverted.push_back(Arg);
5644 CanonicalConverted.push_back(
5646 ++ArgIdx;
5647 }
5648
5649 return false;
5650 }
5651
5652 continue;
5653 }
5654
5655 // If we're checking a partial template argument list, we're done.
5656 if (PartialTemplateArgs) {
5657 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5658 SugaredConverted.push_back(
5659 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5660 CanonicalConverted.push_back(
5661 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5662 }
5663 return false;
5664 }
5665
5666 // If we have a template parameter pack with no more corresponding
5667 // arguments, just break out now and we'll fill in the argument pack below.
5668 if ((*Param)->isTemplateParameterPack()) {
5669 assert(!getExpandedPackSize(*Param) &&
5670 "Should have dealt with this already");
5671
5672 // A non-expanded parameter pack before the end of the parameter list
5673 // only occurs for an ill-formed template parameter list, unless we've
5674 // got a partial argument list for a function template, so just bail out.
5675 if (Param + 1 != ParamEnd) {
5676 assert(
5677 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5678 "Concept templates must have parameter packs at the end.");
5679 return true;
5680 }
5681
5682 SugaredConverted.push_back(
5683 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5684 SugaredArgumentPack.clear();
5685
5686 CanonicalConverted.push_back(
5687 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5688 CanonicalArgumentPack.clear();
5689
5690 ++Param;
5691 continue;
5692 }
5693
5694 // Check whether we have a default argument.
5695 bool HasDefaultArg;
5696
5697 // Retrieve the default template argument from the template
5698 // parameter. For each kind of template parameter, we substitute the
5699 // template arguments provided thus far and any "outer" template arguments
5700 // (when the template parameter was part of a nested template) into
5701 // the default argument.
5703 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5704 CanonicalConverted, HasDefaultArg);
5705
5706 if (Arg.getArgument().isNull()) {
5707 if (!HasDefaultArg) {
5708 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5709 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5710 NewArgs);
5711 if (NonTypeTemplateParmDecl *NTTP =
5712 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5713 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5714 NewArgs);
5715 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5716 cast<TemplateTemplateParmDecl>(*Param),
5717 NewArgs);
5718 }
5719 return true;
5720 }
5721
5722 // Introduce an instantiation record that describes where we are using
5723 // the default template argument. We're not actually instantiating a
5724 // template here, we just create this object to put a note into the
5725 // context stack.
5726 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5727 SugaredConverted,
5728 SourceRange(TemplateLoc, RAngleLoc));
5729 if (Inst.isInvalid())
5730 return true;
5731
5732 // Check the default template argument.
5733 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5734 SugaredConverted, CanonicalConverted,
5736 return true;
5737
5738 SugaredConverted.back().setIsDefaulted(true);
5739 CanonicalConverted.back().setIsDefaulted(true);
5740
5741 // Core issue 150 (assumed resolution): if this is a template template
5742 // parameter, keep track of the default template arguments from the
5743 // template definition.
5744 if (isTemplateTemplateParameter)
5745 NewArgs.addArgument(Arg);
5746
5747 // Move to the next template parameter and argument.
5748 ++Param;
5749 ++ArgIdx;
5750 }
5751
5752 // If we're performing a partial argument substitution, allow any trailing
5753 // pack expansions; they might be empty. This can happen even if
5754 // PartialTemplateArgs is false (the list of arguments is complete but
5755 // still dependent).
5756 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5758 while (ArgIdx < NumArgs &&
5759 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5760 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5761 SugaredConverted.push_back(Arg);
5762 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5763 }
5764 }
5765
5766 // If we have any leftover arguments, then there were too many arguments.
5767 // Complain and fail.
5768 if (ArgIdx < NumArgs) {
5769 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5770 << /*too many args*/1
5772 << Template
5773 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5774 NoteTemplateLocation(*Template, Params->getSourceRange());
5775 return true;
5776 }
5777
5778 // No problems found with the new argument list, propagate changes back
5779 // to caller.
5780 if (UpdateArgsWithConversions)
5781 TemplateArgs = std::move(NewArgs);
5782
5783 if (!PartialTemplateArgs) {
5784 // Setup the context/ThisScope for the case where we are needing to
5785 // re-instantiate constraints outside of normal instantiation.
5786 DeclContext *NewContext = Template->getDeclContext();
5787
5788 // If this template is in a template, make sure we extract the templated
5789 // decl.
5790 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5791 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5792 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5793
5794 Qualifiers ThisQuals;
5795 if (const auto *Method =
5796 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5797 ThisQuals = Method->getMethodQualifiers();
5798
5799 ContextRAII Context(*this, NewContext);
5800 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5801
5803 Template, NewContext, /*Final=*/false, CanonicalConverted,
5804 /*RelativeToPrimary=*/true,
5805 /*Pattern=*/nullptr,
5806 /*ForConceptInstantiation=*/true);
5808 Template, MLTAL,
5809 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5812 return true;
5813 }
5814 }
5815
5816 return false;
5817}
5818
5819namespace {
5820 class UnnamedLocalNoLinkageFinder
5821 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5822 {
5823 Sema &S;
5824 SourceRange SR;
5825
5827
5828 public:
5829 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5830
5831 bool Visit(QualType T) {
5832 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5833 }
5834
5835#define TYPE(Class, Parent) \
5836 bool Visit##Class##Type(const Class##Type *);
5837#define ABSTRACT_TYPE(Class, Parent) \
5838 bool Visit##Class##Type(const Class##Type *) { return false; }
5839#define NON_CANONICAL_TYPE(Class, Parent) \
5840 bool Visit##Class##Type(const Class##Type *) { return false; }
5841#include "clang/AST/TypeNodes.inc"
5842
5843 bool VisitTagDecl(const TagDecl *Tag);
5844 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5845 };
5846} // end anonymous namespace
5847
5848bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5849 return false;
5850}
5851
5852bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5853 return Visit(T->getElementType());
5854}
5855
5856bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5857 return Visit(T->getPointeeType());
5858}
5859
5860bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5861 const BlockPointerType* T) {
5862 return Visit(T->getPointeeType());
5863}
5864
5865bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5866 const LValueReferenceType* T) {
5867 return Visit(T->getPointeeType());
5868}
5869
5870bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5871 const RValueReferenceType* T) {
5872 return Visit(T->getPointeeType());
5873}
5874
5875bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5876 const MemberPointerType* T) {
5877 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5878}
5879
5880bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5881 const ConstantArrayType* T) {
5882 return Visit(T->getElementType());
5883}
5884
5885bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5886 const IncompleteArrayType* T) {
5887 return Visit(T->getElementType());
5888}
5889
5890bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5891 const VariableArrayType* T) {
5892 return Visit(T->getElementType());
5893}
5894
5895bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5896 const DependentSizedArrayType* T) {
5897 return Visit(T->getElementType());
5898}
5899
5900bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5902 return Visit(T->getElementType());
5903}
5904
5905bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5906 const DependentSizedMatrixType *T) {
5907 return Visit(T->getElementType());
5908}
5909
5910bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5912 return Visit(T->getPointeeType());
5913}
5914
5915bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5916 return Visit(T->getElementType());
5917}
5918
5919bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5920 const DependentVectorType *T) {
5921 return Visit(T->getElementType());
5922}
5923
5924bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5925 return Visit(T->getElementType());
5926}
5927
5928bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5929 const ConstantMatrixType *T) {
5930 return Visit(T->getElementType());
5931}
5932
5933bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5934 const FunctionProtoType* T) {
5935 for (const auto &A : T->param_types()) {
5936 if (Visit(A))
5937 return true;
5938 }
5939
5940 return Visit(T->getReturnType());
5941}
5942
5943bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5944 const FunctionNoProtoType* T) {
5945 return Visit(T->getReturnType());
5946}
5947
5948bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5949 const UnresolvedUsingType*) {
5950 return false;
5951}
5952
5953bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5954 return false;
5955}
5956
5957bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5958 return Visit(T->getUnmodifiedType());
5959}
5960
5961bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5962 return false;
5963}
5964
5965bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5966 const PackIndexingType *) {
5967 return false;
5968}
5969
5970bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5971 const UnaryTransformType*) {
5972 return false;
5973}
5974
5975bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5976 return Visit(T->getDeducedType());
5977}
5978
5979bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5981 return Visit(T->getDeducedType());
5982}
5983
5984bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5985 return VisitTagDecl(T->getDecl());
5986}
5987
5988bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5989 return VisitTagDecl(T->getDecl());
5990}
5991
5992bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5993 const TemplateTypeParmType*) {
5994 return false;
5995}
5996
5997bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5999 return false;
6000}
6001
6002bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6004 return false;
6005}
6006
6007bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6008 const InjectedClassNameType* T) {
6009 return VisitTagDecl(T->getDecl());
6010}
6011
6012bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6013 const DependentNameType* T) {
6014 return VisitNestedNameSpecifier(T->getQualifier());
6015}
6016
6017bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6019 if (auto *Q = T->getQualifier())
6020 return VisitNestedNameSpecifier(Q);
6021 return false;
6022}
6023
6024bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6025 const PackExpansionType* T) {
6026 return Visit(T->getPattern());
6027}
6028
6029bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6030 return false;
6031}
6032
6033bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6034 const ObjCInterfaceType *) {
6035 return false;
6036}
6037
6038bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6039 const ObjCObjectPointerType *) {
6040 return false;
6041}
6042
6043bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6044 return Visit(T->getValueType());
6045}
6046
6047bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6048 return false;
6049}
6050
6051bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6052 return false;
6053}
6054
6055bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6056 const ArrayParameterType *T) {
6057 return VisitConstantArrayType(T);
6058}
6059
6060bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6061 const DependentBitIntType *T) {
6062 return false;
6063}
6064
6065bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6066 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6067 S.Diag(SR.getBegin(),
6068 S.getLangOpts().CPlusPlus11 ?
6069 diag::warn_cxx98_compat_template_arg_local_type :
6070 diag::ext_template_arg_local_type)
6071 << S.Context.getTypeDeclType(Tag) << SR;
6072 return true;
6073 }
6074
6075 if (!Tag->hasNameForLinkage()) {
6076 S.Diag(SR.getBegin(),
6077 S.getLangOpts().CPlusPlus11 ?
6078 diag::warn_cxx98_compat_template_arg_unnamed_type :
6079 diag::ext_template_arg_unnamed_type) << SR;
6080 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6081 return true;
6082 }
6083
6084 return false;
6085}
6086
6087bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6088 NestedNameSpecifier *NNS) {
6089 assert(NNS);
6090 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6091 return true;
6092
6093 switch (NNS->getKind()) {
6099 return false;
6100
6103 return Visit(QualType(NNS->getAsType(), 0));
6104 }
6105 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6106}
6107
6108bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6110 if (T->hasContainedType() && Visit(T->getContainedType()))
6111 return true;
6112 return Visit(T->getWrappedType());
6113}
6114
6116 assert(ArgInfo && "invalid TypeSourceInfo");
6117 QualType Arg = ArgInfo->getType();
6118 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6119 QualType CanonArg = Context.getCanonicalType(Arg);
6120
6121 if (CanonArg->isVariablyModifiedType()) {
6122 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6124 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6125 }
6126
6127 // C++03 [temp.arg.type]p2:
6128 // A local type, a type with no linkage, an unnamed type or a type
6129 // compounded from any of these types shall not be used as a
6130 // template-argument for a template type-parameter.
6131 //
6132 // C++11 allows these, and even in C++03 we allow them as an extension with
6133 // a warning.
6134 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6135 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6136 (void)Finder.Visit(CanonArg);
6137 }
6138
6139 return false;
6140}
6141
6145 NPV_Error
6147
6148/// Determine whether the given template argument is a null pointer
6149/// value of the appropriate type.
6152 QualType ParamType, Expr *Arg,
6153 Decl *Entity = nullptr) {
6154 if (Arg->isValueDependent() || Arg->isTypeDependent())
6155 return NPV_NotNullPointer;
6156
6157 // dllimport'd entities aren't constant but are available inside of template
6158 // arguments.
6159 if (Entity && Entity->hasAttr<DLLImportAttr>())
6160 return NPV_NotNullPointer;
6161
6162 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6163 llvm_unreachable(
6164 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6165
6166 if (!S.getLangOpts().CPlusPlus11)
6167 return NPV_NotNullPointer;
6168
6169 // Determine whether we have a constant expression.
6171 if (ArgRV.isInvalid())
6172 return NPV_Error;
6173 Arg = ArgRV.get();
6174
6175 Expr::EvalResult EvalResult;
6177 EvalResult.Diag = &Notes;
6178 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6179 EvalResult.HasSideEffects) {
6180 SourceLocation DiagLoc = Arg->getExprLoc();
6181
6182 // If our only note is the usual "invalid subexpression" note, just point
6183 // the caret at its location rather than producing an essentially
6184 // redundant note.
6185 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6186 diag::note_invalid_subexpr_in_const_expr) {
6187 DiagLoc = Notes[0].first;
6188 Notes.clear();
6189 }
6190
6191 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6192 << Arg->getType() << Arg->getSourceRange();
6193 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6194 S.Diag(Notes[I].first, Notes[I].second);
6195
6197 return NPV_Error;
6198 }
6199
6200 // C++11 [temp.arg.nontype]p1:
6201 // - an address constant expression of type std::nullptr_t
6202 if (Arg->getType()->isNullPtrType())
6203 return NPV_NullPointer;
6204
6205 // - a constant expression that evaluates to a null pointer value (4.10); or
6206 // - a constant expression that evaluates to a null member pointer value
6207 // (4.11); or
6208 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6209 (EvalResult.Val.isMemberPointer() &&
6210 !EvalResult.Val.getMemberPointerDecl())) {
6211 // If our expression has an appropriate type, we've succeeded.
6212 bool ObjCLifetimeConversion;
6213 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6214 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6215 ObjCLifetimeConversion))
6216 return NPV_NullPointer;
6217
6218 // The types didn't match, but we know we got a null pointer; complain,
6219 // then recover as if the types were correct.
6220 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6221 << Arg->getType() << ParamType << Arg->getSourceRange();
6223 return NPV_NullPointer;
6224 }
6225
6226 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6227 // We found a pointer that isn't null, but doesn't refer to an object.
6228 // We could just return NPV_NotNullPointer, but we can print a better
6229 // message with the information we have here.
6230 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6231 << EvalResult.Val.getAsString(S.Context, ParamType);
6233 return NPV_Error;
6234 }
6235
6236 // If we don't have a null pointer value, but we do have a NULL pointer
6237 // constant, suggest a cast to the appropriate type.
6239 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6240 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6241 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6243 ")");
6245 return NPV_NullPointer;
6246 }
6247
6248 // FIXME: If we ever want to support general, address-constant expressions
6249 // as non-type template arguments, we should return the ExprResult here to
6250 // be interpreted by the caller.
6251 return NPV_NotNullPointer;
6252}
6253
6254/// Checks whether the given template argument is compatible with its
6255/// template parameter.
6257 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6258 Expr *Arg, QualType ArgType) {
6259 bool ObjCLifetimeConversion;
6260 if (ParamType->isPointerType() &&
6261 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6262 S.IsQualificationConversion(ArgType, ParamType, false,
6263 ObjCLifetimeConversion)) {
6264 // For pointer-to-object types, qualification conversions are
6265 // permitted.
6266 } else {
6267 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6268 if (!ParamRef->getPointeeType()->isFunctionType()) {
6269 // C++ [temp.arg.nontype]p5b3:
6270 // For a non-type template-parameter of type reference to
6271 // object, no conversions apply. The type referred to by the
6272 // reference may be more cv-qualified than the (otherwise
6273 // identical) type of the template- argument. The
6274 // template-parameter is bound directly to the
6275 // template-argument, which shall be an lvalue.
6276
6277 // FIXME: Other qualifiers?
6278 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6279 unsigned ArgQuals = ArgType.getCVRQualifiers();
6280
6281 if ((ParamQuals | ArgQuals) != ParamQuals) {
6282 S.Diag(Arg->getBeginLoc(),
6283 diag::err_template_arg_ref_bind_ignores_quals)
6284 << ParamType << Arg->getType() << Arg->getSourceRange();
6286 return true;
6287 }
6288 }
6289 }
6290
6291 // At this point, the template argument refers to an object or
6292 // function with external linkage. We now need to check whether the
6293 // argument and parameter types are compatible.
6294 if (!S.Context.hasSameUnqualifiedType(ArgType,
6295 ParamType.getNonReferenceType())) {
6296 // We can't perform this conversion or binding.
6297 if (ParamType->isReferenceType())
6298 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6299 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6300 else
6301 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6302 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6304 return true;
6305 }
6306 }
6307
6308 return false;
6309}
6310
6311/// Checks whether the given template argument is the address
6312/// of an object or function according to C++ [temp.arg.nontype]p1.
6314 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6315 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6316 bool Invalid = false;
6317 Expr *Arg = ArgIn;
6318 QualType ArgType = Arg->getType();
6319
6320 bool AddressTaken = false;
6321 SourceLocation AddrOpLoc;
6322 if (S.getLangOpts().MicrosoftExt) {
6323 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6324 // dereference and address-of operators.
6325 Arg = Arg->IgnoreParenCasts();
6326
6327 bool ExtWarnMSTemplateArg = false;
6328 UnaryOperatorKind FirstOpKind;
6329 SourceLocation FirstOpLoc;
6330 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6331 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6332 if (UnOpKind == UO_Deref)
6333 ExtWarnMSTemplateArg = true;
6334 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6335 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6336 if (!AddrOpLoc.isValid()) {
6337 FirstOpKind = UnOpKind;
6338 FirstOpLoc = UnOp->getOperatorLoc();
6339 }
6340 } else
6341 break;
6342 }
6343 if (FirstOpLoc.isValid()) {
6344 if (ExtWarnMSTemplateArg)
6345 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6346 << ArgIn->getSourceRange();
6347
6348 if (FirstOpKind == UO_AddrOf)
6349 AddressTaken = true;
6350 else if (Arg->getType()->isPointerType()) {
6351 // We cannot let pointers get dereferenced here, that is obviously not a
6352 // constant expression.
6353 assert(FirstOpKind == UO_Deref);
6354 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6355 << Arg->getSourceRange();
6356 }
6357 }
6358 } else {
6359 // See through any implicit casts we added to fix the type.
6360 Arg = Arg->IgnoreImpCasts();
6361
6362 // C++ [temp.arg.nontype]p1:
6363 //
6364 // A template-argument for a non-type, non-template
6365 // template-parameter shall be one of: [...]
6366 //
6367 // -- the address of an object or function with external
6368 // linkage, including function templates and function
6369 // template-ids but excluding non-static class members,
6370 // expressed as & id-expression where the & is optional if
6371 // the name refers to a function or array, or if the
6372 // corresponding template-parameter is a reference; or
6373
6374 // In C++98/03 mode, give an extension warning on any extra parentheses.
6375 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6376 bool ExtraParens = false;
6377 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6378 if (!Invalid && !ExtraParens) {
6379 S.Diag(Arg->getBeginLoc(),
6380 S.getLangOpts().CPlusPlus11
6381 ? diag::warn_cxx98_compat_template_arg_extra_parens
6382 : diag::ext_template_arg_extra_parens)
6383 << Arg->getSourceRange();
6384 ExtraParens = true;
6385 }
6386
6387 Arg = Parens->getSubExpr();
6388 }
6389
6390 while (SubstNonTypeTemplateParmExpr *subst =
6391 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6392 Arg = subst->getReplacement()->IgnoreImpCasts();
6393
6394 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6395 if (UnOp->getOpcode() == UO_AddrOf) {
6396 Arg = UnOp->getSubExpr();
6397 AddressTaken = true;
6398 AddrOpLoc = UnOp->getOperatorLoc();
6399 }
6400 }
6401
6402 while (SubstNonTypeTemplateParmExpr *subst =
6403 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6404 Arg = subst->getReplacement()->IgnoreImpCasts();
6405 }
6406
6407 ValueDecl *Entity = nullptr;
6408 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6409 Entity = DRE->getDecl();
6410 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6411 Entity = CUE->getGuidDecl();
6412
6413 // If our parameter has pointer type, check for a null template value.
6414 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6415 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6416 Entity)) {
6417 case NPV_NullPointer:
6418 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6419 SugaredConverted = TemplateArgument(ParamType,
6420 /*isNullPtr=*/true);
6421 CanonicalConverted =
6423 /*isNullPtr=*/true);
6424 return false;
6425
6426 case NPV_Error:
6427 return true;
6428
6429 case NPV_NotNullPointer:
6430 break;
6431 }
6432 }
6433
6434 // Stop checking the precise nature of the argument if it is value dependent,
6435 // it should be checked when instantiated.
6436 if (Arg->isValueDependent()) {
6437 SugaredConverted = TemplateArgument(ArgIn);
6438 CanonicalConverted =
6439 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6440 return false;
6441 }
6442
6443 if (!Entity) {
6444 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6445 << Arg->getSourceRange();
6447 return true;
6448 }
6449
6450 // Cannot refer to non-static data members
6451 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6452 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6453 << Entity << Arg->getSourceRange();
6455 return true;
6456 }
6457
6458 // Cannot refer to non-static member functions
6459 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6460 if (!Method->isStatic()) {
6461 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6462 << Method << Arg->getSourceRange();
6464 return true;
6465 }
6466 }
6467
6468 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6469 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6470 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6471
6472 // A non-type template argument must refer to an object or function.
6473 if (!Func && !Var && !Guid) {
6474 // We found something, but we don't know specifically what it is.
6475 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6476 << Arg->getSourceRange();
6477 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6478 return true;
6479 }
6480
6481 // Address / reference template args must have external linkage in C++98.
6482 if (Entity->getFormalLinkage() == Linkage::Internal) {
6483 S.Diag(Arg->getBeginLoc(),
6484 S.getLangOpts().CPlusPlus11
6485 ? diag::warn_cxx98_compat_template_arg_object_internal
6486 : diag::ext_template_arg_object_internal)
6487 << !Func << Entity << Arg->getSourceRange();
6488 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6489 << !Func;
6490 } else if (!Entity->hasLinkage()) {
6491 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6492 << !Func << Entity << Arg->getSourceRange();
6493 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6494 << !Func;
6495 return true;
6496 }
6497
6498 if (Var) {
6499 // A value of reference type is not an object.
6500 if (Var->getType()->isReferenceType()) {
6501 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6502 << Var->getType() << Arg->getSourceRange();
6504 return true;
6505 }
6506
6507 // A template argument must have static storage duration.
6508 if (Var->getTLSKind()) {
6509 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6510 << Arg->getSourceRange();
6511 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6512 return true;
6513 }
6514 }
6515
6516 if (AddressTaken && ParamType->isReferenceType()) {
6517 // If we originally had an address-of operator, but the
6518 // parameter has reference type, complain and (if things look
6519 // like they will work) drop the address-of operator.
6520 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6521 ParamType.getNonReferenceType())) {
6522 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6523 << ParamType;
6525 return true;
6526 }
6527
6528 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6529 << ParamType
6530 << FixItHint::CreateRemoval(AddrOpLoc);
6532
6533 ArgType = Entity->getType();
6534 }
6535
6536 // If the template parameter has pointer type, either we must have taken the
6537 // address or the argument must decay to a pointer.
6538 if (!AddressTaken && ParamType->isPointerType()) {
6539 if (Func) {
6540 // Function-to-pointer decay.
6541 ArgType = S.Context.getPointerType(Func->getType());
6542 } else if (Entity->getType()->isArrayType()) {
6543 // Array-to-pointer decay.
6544 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6545 } else {
6546 // If the template parameter has pointer type but the address of
6547 // this object was not taken, complain and (possibly) recover by
6548 // taking the address of the entity.
6549 ArgType = S.Context.getPointerType(Entity->getType());
6550 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6551 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6552 << ParamType;
6554 return true;
6555 }
6556
6557 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6558 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6559
6561 }
6562 }
6563
6564 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6565 Arg, ArgType))
6566 return true;
6567
6568 // Create the template argument.
6569 SugaredConverted = TemplateArgument(Entity, ParamType);
6570 CanonicalConverted =
6571 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6572 S.Context.getCanonicalType(ParamType));
6573 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6574 return false;
6575}
6576
6577/// Checks whether the given template argument is a pointer to
6578/// member constant according to C++ [temp.arg.nontype]p1.
6579static bool
6581 QualType ParamType, Expr *&ResultArg,
6582 TemplateArgument &SugaredConverted,
6583 TemplateArgument &CanonicalConverted) {
6584 bool Invalid = false;
6585
6586 Expr *Arg = ResultArg;
6587 bool ObjCLifetimeConversion;
6588
6589 // C++ [temp.arg.nontype]p1:
6590 //
6591 // A template-argument for a non-type, non-template
6592 // template-parameter shall be one of: [...]
6593 //
6594 // -- a pointer to member expressed as described in 5.3.1.
6595 DeclRefExpr *DRE = nullptr;
6596
6597 // In C++98/03 mode, give an extension warning on any extra parentheses.
6598 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6599 bool ExtraParens = false;
6600 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6601 if (!Invalid && !ExtraParens) {
6602 S.Diag(Arg->getBeginLoc(),
6603 S.getLangOpts().CPlusPlus11
6604 ? diag::warn_cxx98_compat_template_arg_extra_parens
6605 : diag::ext_template_arg_extra_parens)
6606 << Arg->getSourceRange();
6607 ExtraParens = true;
6608 }
6609
6610 Arg = Parens->getSubExpr();
6611 }
6612
6613 while (SubstNonTypeTemplateParmExpr *subst =
6614 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6615 Arg = subst->getReplacement()->IgnoreImpCasts();
6616
6617 // A pointer-to-member constant written &Class::member.
6618 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6619 if (UnOp->getOpcode() == UO_AddrOf) {
6620 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6621 if (DRE && !DRE->getQualifier())
6622 DRE = nullptr;
6623 }
6624 }
6625 // A constant of pointer-to-member type.
6626 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6627 ValueDecl *VD = DRE->getDecl();
6628 if (VD->getType()->isMemberPointerType()) {
6629 if (isa<NonTypeTemplateParmDecl>(VD)) {
6630 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6631 SugaredConverted = TemplateArgument(Arg);
6632 CanonicalConverted =
6633 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6634 } else {
6635 SugaredConverted = TemplateArgument(VD, ParamType);
6636 CanonicalConverted =
6637 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6638 S.Context.getCanonicalType(ParamType));
6639 }
6640 return Invalid;
6641 }
6642 }
6643
6644 DRE = nullptr;
6645 }
6646
6647 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6648
6649 // Check for a null pointer value.
6650 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6651 Entity)) {
6652 case NPV_Error:
6653 return true;
6654 case NPV_NullPointer:
6655 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6656 SugaredConverted = TemplateArgument(ParamType,
6657 /*isNullPtr*/ true);
6658 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6659 /*isNullPtr*/ true);
6660 return false;
6661 case NPV_NotNullPointer:
6662 break;
6663 }
6664
6665 if (S.IsQualificationConversion(ResultArg->getType(),
6666 ParamType.getNonReferenceType(), false,
6667 ObjCLifetimeConversion)) {
6668 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6669 ResultArg->getValueKind())
6670 .get();
6671 } else if (!S.Context.hasSameUnqualifiedType(
6672 ResultArg->getType(), ParamType.getNonReferenceType())) {
6673 // We can't perform this conversion.
6674 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6675 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6677 return true;
6678 }
6679
6680 if (!DRE)
6681 return S.Diag(Arg->getBeginLoc(),
6682 diag::err_template_arg_not_pointer_to_member_form)
6683 << Arg->getSourceRange();
6684
6685 if (isa<FieldDecl>(DRE->getDecl()) ||
6686 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6687 isa<CXXMethodDecl>(DRE->getDecl())) {
6688 assert((isa<FieldDecl>(DRE->getDecl()) ||
6689 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6690 cast<CXXMethodDecl>(DRE->getDecl())
6691 ->isImplicitObjectMemberFunction()) &&
6692 "Only non-static member pointers can make it here");
6693
6694 // Okay: this is the address of a non-static member, and therefore
6695 // a member pointer constant.
6696 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6697 SugaredConverted = TemplateArgument(Arg);
6698 CanonicalConverted =
6699 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6700 } else {
6701 ValueDecl *D = DRE->getDecl();
6702 SugaredConverted = TemplateArgument(D, ParamType);
6703 CanonicalConverted =
6704 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6705 S.Context.getCanonicalType(ParamType));
6706 }
6707 return Invalid;
6708 }
6709
6710 // We found something else, but we don't know specifically what it is.
6711 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6712 << Arg->getSourceRange();
6713 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6714 return true;
6715}
6716
6718 QualType ParamType, Expr *Arg,
6719 TemplateArgument &SugaredConverted,
6720 TemplateArgument &CanonicalConverted,
6722 SourceLocation StartLoc = Arg->getBeginLoc();
6723
6724 // If the parameter type somehow involves auto, deduce the type now.
6725 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6726 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6727 // During template argument deduction, we allow 'decltype(auto)' to
6728 // match an arbitrary dependent argument.
6729 // FIXME: The language rules don't say what happens in this case.
6730 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6731 // expression is merely instantiation-dependent; is this enough?
6732 if (Arg->isTypeDependent()) {
6733 auto *AT = dyn_cast<AutoType>(DeducedT);
6734 if (AT && AT->isDecltypeAuto()) {
6735 SugaredConverted = TemplateArgument(Arg);
6736 CanonicalConverted = TemplateArgument(
6737 Context.getCanonicalTemplateArgument(SugaredConverted));
6738 return Arg;
6739 }
6740 }
6741
6742 // When checking a deduced template argument, deduce from its type even if
6743 // the type is dependent, in order to check the types of non-type template
6744 // arguments line up properly in partial ordering.
6745 Expr *DeductionArg = Arg;
6746 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6747 DeductionArg = PE->getPattern();
6748 TypeSourceInfo *TSI =
6749 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6750 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6751 InitializedEntity Entity =
6754 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6755 Expr *Inits[1] = {DeductionArg};
6756 ParamType =
6757 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6758 if (ParamType.isNull())
6759 return ExprError();
6760 } else {
6761 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6762 Param->getDepth() + 1);
6763 ParamType = QualType();
6765 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6766 /*DependentDeduction=*/true,
6767 // We do not check constraints right now because the
6768 // immediately-declared constraint of the auto type is
6769 // also an associated constraint, and will be checked
6770 // along with the other associated constraints after
6771 // checking the template argument list.
6772 /*IgnoreConstraints=*/true);
6774 if (ParamType.isNull())
6775 return ExprError();
6777 Diag(Arg->getExprLoc(),
6778 diag::err_non_type_template_parm_type_deduction_failure)
6779 << Param->getDeclName() << Param->getType() << Arg->getType()
6780 << Arg->getSourceRange();
6782 return ExprError();
6783 }
6784 }
6785 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6786 // an error. The error message normally references the parameter
6787 // declaration, but here we'll pass the argument location because that's
6788 // where the parameter type is deduced.
6789 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6790 if (ParamType.isNull()) {
6792 return ExprError();
6793 }
6794 }
6795
6796 // We should have already dropped all cv-qualifiers by now.
6797 assert(!ParamType.hasQualifiers() &&
6798 "non-type template parameter type cannot be qualified");
6799
6800 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6801 if (CTAK == CTAK_Deduced &&
6802 (ParamType->isReferenceType()
6804 Arg->getType())
6805 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6806 // FIXME: If either type is dependent, we skip the check. This isn't
6807 // correct, since during deduction we're supposed to have replaced each
6808 // template parameter with some unique (non-dependent) placeholder.
6809 // FIXME: If the argument type contains 'auto', we carry on and fail the
6810 // type check in order to force specific types to be more specialized than
6811 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6812 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6813 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6814 !Arg->getType()->getContainedDeducedType()) {
6815 SugaredConverted = TemplateArgument(Arg);
6816 CanonicalConverted = TemplateArgument(
6817 Context.getCanonicalTemplateArgument(SugaredConverted));
6818 return Arg;
6819 }
6820 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6821 // we should actually be checking the type of the template argument in P,
6822 // not the type of the template argument deduced from A, against the
6823 // template parameter type.
6824 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6825 << Arg->getType()
6826 << ParamType.getUnqualifiedType();
6828 return ExprError();
6829 }
6830
6831 // If either the parameter has a dependent type or the argument is
6832 // type-dependent, there's nothing we can check now.
6833 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6834 // Force the argument to the type of the parameter to maintain invariants.
6835 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6836 if (PE)
6837 Arg = PE->getPattern();
6839 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6840 ParamType->isLValueReferenceType() ? VK_LValue
6841 : ParamType->isRValueReferenceType() ? VK_XValue
6842 : VK_PRValue);
6843 if (E.isInvalid())
6844 return ExprError();
6845 if (PE) {
6846 // Recreate a pack expansion if we unwrapped one.
6847 E = new (Context)
6848 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6849 PE->getNumExpansions());
6850 }
6851 SugaredConverted = TemplateArgument(E.get());
6852 CanonicalConverted = TemplateArgument(
6853 Context.getCanonicalTemplateArgument(SugaredConverted));
6854 return E;
6855 }
6856
6857 QualType CanonParamType = Context.getCanonicalType(ParamType);
6858 // Avoid making a copy when initializing a template parameter of class type
6859 // from a template parameter object of the same type. This is going beyond
6860 // the standard, but is required for soundness: in
6861 // template<A a> struct X { X *p; X<a> *q; };
6862 // ... we need p and q to have the same type.
6863 //
6864 // Similarly, don't inject a call to a copy constructor when initializing
6865 // from a template parameter of the same type.
6866 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6867 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6868 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6869 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6870 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6871
6872 SugaredConverted = TemplateArgument(TPO, ParamType);
6873 CanonicalConverted =
6874 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6875 return Arg;
6876 }
6877 if (isa<NonTypeTemplateParmDecl>(ND)) {
6878 SugaredConverted = TemplateArgument(Arg);
6879 CanonicalConverted =
6880 Context.getCanonicalTemplateArgument(SugaredConverted);
6881 return Arg;
6882 }
6883 }
6884
6885 // The initialization of the parameter from the argument is
6886 // a constant-evaluated context.
6889
6890 bool IsConvertedConstantExpression = true;
6891 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6893 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6894 Expr *Inits[1] = {Arg};
6895 InitializedEntity Entity =
6897 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6898 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6899 if (Result.isInvalid() || !Result.get())
6900 return ExprError();
6902 if (Result.isInvalid() || !Result.get())
6903 return ExprError();
6904 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6905 /*DiscardedValue=*/false,
6906 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6907 .get();
6908 IsConvertedConstantExpression = false;
6909 }
6910
6911 if (getLangOpts().CPlusPlus17) {
6912 // C++17 [temp.arg.nontype]p1:
6913 // A template-argument for a non-type template parameter shall be
6914 // a converted constant expression of the type of the template-parameter.
6915 APValue Value;
6916 ExprResult ArgResult;
6917 if (IsConvertedConstantExpression) {
6918 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6919 CCEK_TemplateArg, Param);
6920 if (ArgResult.isInvalid())
6921 return ExprError();
6922 } else {
6923 ArgResult = Arg;
6924 }
6925
6926 // For a value-dependent argument, CheckConvertedConstantExpression is
6927 // permitted (and expected) to be unable to determine a value.
6928 if (ArgResult.get()->isValueDependent()) {
6929 SugaredConverted = TemplateArgument(ArgResult.get());
6930 CanonicalConverted =
6931 Context.getCanonicalTemplateArgument(SugaredConverted);
6932 return ArgResult;
6933 }
6934
6935 APValue PreNarrowingValue;
6937 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6938 false, PreNarrowingValue);
6939 if (ArgResult.isInvalid())
6940 return ExprError();
6941
6942 if (Value.isLValue()) {
6943 APValue::LValueBase Base = Value.getLValueBase();
6944 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6945 // For a non-type template-parameter of pointer or reference type,
6946 // the value of the constant expression shall not refer to
6947 assert(ParamType->isPointerOrReferenceType() ||
6948 ParamType->isNullPtrType());
6949 // -- a temporary object
6950 // -- a string literal
6951 // -- the result of a typeid expression, or
6952 // -- a predefined __func__ variable
6953 if (Base &&
6954 (!VD ||
6955 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6956 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6957 << Arg->getSourceRange();
6958 return ExprError();
6959 }
6960
6961 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6962 VD->getType()->isArrayType() &&
6963 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6964 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6965 SugaredConverted = TemplateArgument(VD, ParamType);
6966 CanonicalConverted = TemplateArgument(
6967 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6968 return ArgResult.get();
6969 }
6970
6971 // -- a subobject [until C++20]
6972 if (!getLangOpts().CPlusPlus20) {
6973 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6974 Value.isLValueOnePastTheEnd()) {
6975 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6976 << Value.getAsString(Context, ParamType);
6977 return ExprError();
6978 }
6979 assert((VD || !ParamType->isReferenceType()) &&
6980 "null reference should not be a constant expression");
6981 assert((!VD || !ParamType->isNullPtrType()) &&
6982 "non-null value of type nullptr_t?");
6983 }
6984 }
6985
6986 if (Value.isAddrLabelDiff())
6987 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6988
6989 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6990 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6991 return ArgResult.get();
6992 }
6993
6994 // C++ [temp.arg.nontype]p5:
6995 // The following conversions are performed on each expression used
6996 // as a non-type template-argument. If a non-type
6997 // template-argument cannot be converted to the type of the
6998 // corresponding template-parameter then the program is
6999 // ill-formed.
7000 if (ParamType->isIntegralOrEnumerationType()) {
7001 // C++11:
7002 // -- for a non-type template-parameter of integral or
7003 // enumeration type, conversions permitted in a converted
7004 // constant expression are applied.
7005 //
7006 // C++98:
7007 // -- for a non-type template-parameter of integral or
7008 // enumeration type, integral promotions (4.5) and integral
7009 // conversions (4.7) are applied.
7010
7011 if (getLangOpts().CPlusPlus11) {
7012 // C++ [temp.arg.nontype]p1:
7013 // A template-argument for a non-type, non-template template-parameter
7014 // shall be one of:
7015 //
7016 // -- for a non-type template-parameter of integral or enumeration
7017 // type, a converted constant expression of the type of the
7018 // template-parameter; or
7019 llvm::APSInt Value;
7020 ExprResult ArgResult =
7023 if (ArgResult.isInvalid())
7024 return ExprError();
7025
7026 // We can't check arbitrary value-dependent arguments.
7027 if (ArgResult.get()->isValueDependent()) {
7028 SugaredConverted = TemplateArgument(ArgResult.get());
7029 CanonicalConverted =
7030 Context.getCanonicalTemplateArgument(SugaredConverted);
7031 return ArgResult;
7032 }
7033
7034 // Widen the argument value to sizeof(parameter type). This is almost
7035 // always a no-op, except when the parameter type is bool. In
7036 // that case, this may extend the argument from 1 bit to 8 bits.
7037 QualType IntegerType = ParamType;
7038 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7039 IntegerType = Enum->getDecl()->getIntegerType();
7040 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7041 ? Context.getIntWidth(IntegerType)
7042 : Context.getTypeSize(IntegerType));
7043
7044 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7045 CanonicalConverted =
7047 return ArgResult;
7048 }
7049
7050 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7051 if (ArgResult.isInvalid())
7052 return ExprError();
7053 Arg = ArgResult.get();
7054
7055 QualType ArgType = Arg->getType();
7056
7057 // C++ [temp.arg.nontype]p1:
7058 // A template-argument for a non-type, non-template
7059 // template-parameter shall be one of:
7060 //
7061 // -- an integral constant-expression of integral or enumeration
7062 // type; or
7063 // -- the name of a non-type template-parameter; or
7064 llvm::APSInt Value;
7065 if (!ArgType->isIntegralOrEnumerationType()) {
7066 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7067 << ArgType << Arg->getSourceRange();
7069 return ExprError();
7070 } else if (!Arg->isValueDependent()) {
7071 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7072 QualType T;
7073
7074 public:
7075 TmplArgICEDiagnoser(QualType T) : T(T) { }
7076
7077 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7078 SourceLocation Loc) override {
7079 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7080 }
7081 } Diagnoser(ArgType);
7082
7083 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7084 if (!Arg)
7085 return ExprError();
7086 }
7087
7088 // From here on out, all we care about is the unqualified form
7089 // of the argument type.
7090 ArgType = ArgType.getUnqualifiedType();
7091
7092 // Try to convert the argument to the parameter's type.
7093 if (Context.hasSameType(ParamType, ArgType)) {
7094 // Okay: no conversion necessary
7095 } else if (ParamType->isBooleanType()) {
7096 // This is an integral-to-boolean conversion.
7097 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7098 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7099 !ParamType->isEnumeralType()) {
7100 // This is an integral promotion or conversion.
7101 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7102 } else {
7103 // We can't perform this conversion.
7104 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7105 << Arg->getType() << ParamType << Arg->getSourceRange();
7107 return ExprError();
7108 }
7109
7110 // Add the value of this argument to the list of converted
7111 // arguments. We use the bitwidth and signedness of the template
7112 // parameter.
7113 if (Arg->isValueDependent()) {
7114 // The argument is value-dependent. Create a new
7115 // TemplateArgument with the converted expression.
7116 SugaredConverted = TemplateArgument(Arg);
7117 CanonicalConverted =
7118 Context.getCanonicalTemplateArgument(SugaredConverted);
7119 return Arg;
7120 }
7121
7122 QualType IntegerType = ParamType;
7123 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7124 IntegerType = Enum->getDecl()->getIntegerType();
7125 }
7126
7127 if (ParamType->isBooleanType()) {
7128 // Value must be zero or one.
7129 Value = Value != 0;
7130 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7131 if (Value.getBitWidth() != AllowedBits)
7132 Value = Value.extOrTrunc(AllowedBits);
7133 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7134 } else {
7135 llvm::APSInt OldValue = Value;
7136
7137 // Coerce the template argument's value to the value it will have
7138 // based on the template parameter's type.
7139 unsigned AllowedBits = IntegerType->isBitIntType()
7140 ? Context.getIntWidth(IntegerType)
7141 : Context.getTypeSize(IntegerType);
7142 if (Value.getBitWidth() != AllowedBits)
7143 Value = Value.extOrTrunc(AllowedBits);
7144 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7145
7146 // Complain if an unsigned parameter received a negative value.
7147 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7148 (OldValue.isSigned() && OldValue.isNegative())) {
7149 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7150 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7151 << Arg->getSourceRange();
7153 }
7154
7155 // Complain if we overflowed the template parameter's type.
7156 unsigned RequiredBits;
7157 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7158 RequiredBits = OldValue.getActiveBits();
7159 else if (OldValue.isUnsigned())
7160 RequiredBits = OldValue.getActiveBits() + 1;
7161 else
7162 RequiredBits = OldValue.getSignificantBits();
7163 if (RequiredBits > AllowedBits) {
7164 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7165 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7166 << Arg->getSourceRange();
7168 }
7169 }
7170
7171 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7172 SugaredConverted = TemplateArgument(Context, Value, T);
7173 CanonicalConverted =
7175 return Arg;
7176 }
7177
7178 QualType ArgType = Arg->getType();
7179 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7180
7181 // Handle pointer-to-function, reference-to-function, and
7182 // pointer-to-member-function all in (roughly) the same way.
7183 if (// -- For a non-type template-parameter of type pointer to
7184 // function, only the function-to-pointer conversion (4.3) is
7185 // applied. If the template-argument represents a set of
7186 // overloaded functions (or a pointer to such), the matching
7187 // function is selected from the set (13.4).
7188 (ParamType->isPointerType() &&
7189 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7190 // -- For a non-type template-parameter of type reference to
7191 // function, no conversions apply. If the template-argument
7192 // represents a set of overloaded functions, the matching
7193 // function is selected from the set (13.4).
7194 (ParamType->isReferenceType() &&
7195 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7196 // -- For a non-type template-parameter of type pointer to
7197 // member function, no conversions apply. If the
7198 // template-argument represents a set of overloaded member
7199 // functions, the matching member function is selected from
7200 // the set (13.4).
7201 (ParamType->isMemberPointerType() &&
7202 ParamType->castAs<MemberPointerType>()->getPointeeType()
7203 ->isFunctionType())) {
7204
7205 if (Arg->getType() == Context.OverloadTy) {
7206 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7207 true,
7208 FoundResult)) {
7209 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7210 return ExprError();
7211
7212 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7213 if (Res.isInvalid())
7214 return ExprError();
7215 Arg = Res.get();
7216 ArgType = Arg->getType();
7217 } else
7218 return ExprError();
7219 }
7220
7221 if (!ParamType->isMemberPointerType()) {
7223 *this, Param, ParamType, Arg, SugaredConverted,
7224 CanonicalConverted))
7225 return ExprError();
7226 return Arg;
7227 }
7228
7230 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7231 return ExprError();
7232 return Arg;
7233 }
7234
7235 if (ParamType->isPointerType()) {
7236 // -- for a non-type template-parameter of type pointer to
7237 // object, qualification conversions (4.4) and the
7238 // array-to-pointer conversion (4.2) are applied.
7239 // C++0x also allows a value of std::nullptr_t.
7240 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7241 "Only object pointers allowed here");
7242
7244 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7245 return ExprError();
7246 return Arg;
7247 }
7248
7249 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7250 // -- For a non-type template-parameter of type reference to
7251 // object, no conversions apply. The type referred to by the
7252 // reference may be more cv-qualified than the (otherwise
7253 // identical) type of the template-argument. The
7254 // template-parameter is bound directly to the
7255 // template-argument, which must be an lvalue.
7256 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7257 "Only object references allowed here");
7258
7259 if (Arg->getType() == Context.OverloadTy) {
7261 ParamRefType->getPointeeType(),
7262 true,
7263 FoundResult)) {
7264 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7265 return ExprError();
7266 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7267 if (Res.isInvalid())
7268 return ExprError();
7269 Arg = Res.get();
7270 ArgType = Arg->getType();
7271 } else
7272 return ExprError();
7273 }
7274
7276 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7277 return ExprError();
7278 return Arg;
7279 }
7280
7281 // Deal with parameters of type std::nullptr_t.
7282 if (ParamType->isNullPtrType()) {
7283 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7284 SugaredConverted = TemplateArgument(Arg);
7285 CanonicalConverted =
7286 Context.getCanonicalTemplateArgument(SugaredConverted);
7287 return Arg;
7288 }
7289
7290 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7291 case NPV_NotNullPointer:
7292 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7293 << Arg->getType() << ParamType;
7295 return ExprError();
7296
7297 case NPV_Error:
7298 return ExprError();
7299
7300 case NPV_NullPointer:
7301 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7302 SugaredConverted = TemplateArgument(ParamType,
7303 /*isNullPtr=*/true);
7304 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7305 /*isNullPtr=*/true);
7306 return Arg;
7307 }
7308 }
7309
7310 // -- For a non-type template-parameter of type pointer to data
7311 // member, qualification conversions (4.4) are applied.
7312 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7313
7315 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7316 return ExprError();
7317 return Arg;
7318}
7319
7323
7325 TemplateParameterList *Params,
7327 bool IsDeduced) {
7329 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7330 if (!Template) {
7331 // Any dependent template name is fine.
7332 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7333 return false;
7334 }
7335
7336 if (Template->isInvalidDecl())
7337 return true;
7338
7339 // C++0x [temp.arg.template]p1:
7340 // A template-argument for a template template-parameter shall be
7341 // the name of a class template or an alias template, expressed as an
7342 // id-expression. When the template-argument names a class template, only
7343 // primary class templates are considered when matching the
7344 // template template argument with the corresponding parameter;
7345 // partial specializations are not considered even if their
7346 // parameter lists match that of the template template parameter.
7347 //
7348 // Note that we also allow template template parameters here, which
7349 // will happen when we are dealing with, e.g., class template
7350 // partial specializations.
7351 if (!isa<ClassTemplateDecl>(Template) &&
7352 !isa<TemplateTemplateParmDecl>(Template) &&
7353 !isa<TypeAliasTemplateDecl>(Template) &&
7354 !isa<BuiltinTemplateDecl>(Template)) {
7355 assert(isa<FunctionTemplateDecl>(Template) &&
7356 "Only function templates are possible here");
7357 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7358 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7359 << Template;
7360 }
7361
7362 // C++1z [temp.arg.template]p3: (DR 150)
7363 // A template-argument matches a template template-parameter P when P
7364 // is at least as specialized as the template-argument A.
7365 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7366 // Quick check for the common case:
7367 // If P contains a parameter pack, then A [...] matches P if each of A's
7368 // template parameters matches the corresponding template parameter in
7369 // the template-parameter-list of P.
7371 Template->getTemplateParameters(), Params, false,
7373 // If the argument has no associated constraints, then the parameter is
7374 // definitely at least as specialized as the argument.
7375 // Otherwise - we need a more thorough check.
7376 !Template->hasAssociatedConstraints())
7377 return false;
7378
7380 Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7381 // P2113
7382 // C++20[temp.func.order]p2
7383 // [...] If both deductions succeed, the partial ordering selects the
7384 // more constrained template (if one exists) as determined below.
7385 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7386 Params->getAssociatedConstraints(ParamsAC);
7387 // C++2a[temp.arg.template]p3
7388 // [...] In this comparison, if P is unconstrained, the constraints on A
7389 // are not considered.
7390 if (ParamsAC.empty())
7391 return false;
7392
7393 Template->getAssociatedConstraints(TemplateAC);
7394
7395 bool IsParamAtLeastAsConstrained;
7396 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7397 IsParamAtLeastAsConstrained))
7398 return true;
7399 if (!IsParamAtLeastAsConstrained) {
7400 Diag(Arg.getLocation(),
7401 diag::err_template_template_parameter_not_at_least_as_constrained)
7402 << Template << Param << Arg.getSourceRange();
7403 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7404 Diag(Template->getLocation(), diag::note_entity_declared_at)
7405 << Template;
7406 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7407 TemplateAC);
7408 return true;
7409 }
7410 return false;
7411 }
7412 // FIXME: Produce better diagnostics for deduction failures.
7413 }
7414
7415 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7416 Params,
7417 true,
7419 Arg.getLocation());
7420}
7421
7423 unsigned HereDiagID,
7424 unsigned ExternalDiagID) {
7425 if (Decl.getLocation().isValid())
7426 return S.Diag(Decl.getLocation(), HereDiagID);
7427
7428 SmallString<128> Str;
7429 llvm::raw_svector_ostream Out(Str);
7431 PP.TerseOutput = 1;
7432 Decl.print(Out, PP);
7433 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7434}
7435
7437 std::optional<SourceRange> ParamRange) {
7439 noteLocation(*this, Decl, diag::note_template_decl_here,
7440 diag::note_template_decl_external);
7441 if (ParamRange && ParamRange->isValid()) {
7442 assert(Decl.getLocation().isValid() &&
7443 "Parameter range has location when Decl does not");
7444 DB << *ParamRange;
7445 }
7446}
7447
7449 noteLocation(*this, Decl, diag::note_template_param_here,
7450 diag::note_template_param_external);
7451}
7452
7454 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7456 // C++ [temp.param]p8:
7457 //
7458 // A non-type template-parameter of type "array of T" or
7459 // "function returning T" is adjusted to be of type "pointer to
7460 // T" or "pointer to function returning T", respectively.
7461 if (ParamType->isArrayType())
7462 ParamType = Context.getArrayDecayedType(ParamType);
7463 else if (ParamType->isFunctionType())
7464 ParamType = Context.getPointerType(ParamType);
7465
7466 // For a NULL non-type template argument, return nullptr casted to the
7467 // parameter's type.
7468 if (Arg.getKind() == TemplateArgument::NullPtr) {
7469 return ImpCastExprToType(
7471 ParamType,
7472 ParamType->getAs<MemberPointerType>()
7473 ? CK_NullToMemberPointer
7474 : CK_NullToPointer);
7475 }
7476 assert(Arg.getKind() == TemplateArgument::Declaration &&
7477 "Only declaration template arguments permitted here");
7478
7479 ValueDecl *VD = Arg.getAsDecl();
7480
7481 CXXScopeSpec SS;
7482 if (ParamType->isMemberPointerType()) {
7483 // If this is a pointer to member, we need to use a qualified name to
7484 // form a suitable pointer-to-member constant.
7485 assert(VD->getDeclContext()->isRecord() &&
7486 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7487 isa<IndirectFieldDecl>(VD)));
7488 QualType ClassType
7489 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7490 NestedNameSpecifier *Qualifier
7491 = NestedNameSpecifier::Create(Context, nullptr, false,
7492 ClassType.getTypePtr());
7493 SS.MakeTrivial(Context, Qualifier, Loc);
7494 }
7495
7497 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7498 if (RefExpr.isInvalid())
7499 return ExprError();
7500
7501 // For a pointer, the argument declaration is the pointee. Take its address.
7502 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7503 if (ParamType->isPointerType() && !ElemT.isNull() &&
7504 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7505 // Decay an array argument if we want a pointer to its first element.
7506 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7507 if (RefExpr.isInvalid())
7508 return ExprError();
7509 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7510 // For any other pointer, take the address (or form a pointer-to-member).
7511 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7512 if (RefExpr.isInvalid())
7513 return ExprError();
7514 } else if (ParamType->isRecordType()) {
7515 assert(isa<TemplateParamObjectDecl>(VD) &&
7516 "arg for class template param not a template parameter object");
7517 // No conversions apply in this case.
7518 return RefExpr;
7519 } else {
7520 assert(ParamType->isReferenceType() &&
7521 "unexpected type for decl template argument");
7522 if (NonTypeTemplateParmDecl *NTTP =
7523 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7524 QualType TemplateParamType = NTTP->getType();
7525 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7526 if (AT && AT->isDecltypeAuto()) {
7528 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7529 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7530 /*PackIndex=*/std::nullopt,
7531 /*RefParam=*/true);
7532 }
7533 }
7534 }
7535
7536 // At this point we should have the right value category.
7537 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7538 "value kind mismatch for non-type template argument");
7539
7540 // The type of the template parameter can differ from the type of the
7541 // argument in various ways; convert it now if necessary.
7542 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7543 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7544 CastKind CK;
7545 QualType Ignored;
7546 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7547 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7548 CK = CK_NoOp;
7549 } else if (ParamType->isVoidPointerType() &&
7550 RefExpr.get()->getType()->isPointerType()) {
7551 CK = CK_BitCast;
7552 } else {
7553 // FIXME: Pointers to members can need conversion derived-to-base or
7554 // base-to-derived conversions. We currently don't retain enough
7555 // information to convert properly (we need to track a cast path or
7556 // subobject number in the template argument).
7557 llvm_unreachable(
7558 "unexpected conversion required for non-type template argument");
7559 }
7560 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7561 RefExpr.get()->getValueKind());
7562 }
7563
7564 return RefExpr;
7565}
7566
7567/// Construct a new expression that refers to the given
7568/// integral template argument with the given source-location
7569/// information.
7570///
7571/// This routine takes care of the mapping from an integral template
7572/// argument (which may have any integral type) to the appropriate
7573/// literal value.
7575 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7576 assert(OrigT->isIntegralOrEnumerationType());
7577
7578 // If this is an enum type that we're instantiating, we need to use an integer
7579 // type the same size as the enumerator. We don't want to build an
7580 // IntegerLiteral with enum type. The integer type of an enum type can be of
7581 // any integral type with C++11 enum classes, make sure we create the right
7582 // type of literal for it.
7583 QualType T = OrigT;
7584 if (const EnumType *ET = OrigT->getAs<EnumType>())
7585 T = ET->getDecl()->getIntegerType();
7586
7587 Expr *E;
7588 if (T->isAnyCharacterType()) {
7590 if (T->isWideCharType())
7592 else if (T->isChar8Type() && S.getLangOpts().Char8)
7594 else if (T->isChar16Type())
7596 else if (T->isChar32Type())
7598 else
7600
7601 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7602 } else if (T->isBooleanType()) {
7603 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7604 } else {
7605 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7606 }
7607
7608 if (OrigT->isEnumeralType()) {
7609 // FIXME: This is a hack. We need a better way to handle substituted
7610 // non-type template parameters.
7611 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7612 nullptr, S.CurFPFeatureOverrides(),
7614 Loc, Loc);
7615 }
7616
7617 return E;
7618}
7619
7621 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7622 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7623 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7624 ILE->setType(T);
7625 return ILE;
7626 };
7627
7628 switch (Val.getKind()) {
7630 // This cannot occur in a template argument at all.
7631 case APValue::Array:
7632 case APValue::Struct:
7633 case APValue::Union:
7634 // These can only occur within a template parameter object, which is
7635 // represented as a TemplateArgument::Declaration.
7636 llvm_unreachable("unexpected template argument value");
7637
7638 case APValue::Int:
7640 Loc);
7641
7642 case APValue::Float:
7643 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7644 T, Loc);
7645
7648 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7649 Val.getFixedPoint().getScale());
7650
7651 case APValue::ComplexInt: {
7652 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7654 S, ElemT, Val.getComplexIntReal(), Loc),
7656 S, ElemT, Val.getComplexIntImag(), Loc)});
7657 }
7658
7659 case APValue::ComplexFloat: {
7660 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7661 return MakeInitList(
7663 ElemT, Loc),
7665 ElemT, Loc)});
7666 }
7667
7668 case APValue::Vector: {
7669 QualType ElemT = T->castAs<VectorType>()->getElementType();
7671 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7673 S, ElemT, Val.getVectorElt(I), Loc));
7674 return MakeInitList(Elts);
7675 }
7676
7677 case APValue::None:
7679 llvm_unreachable("Unexpected APValue kind.");
7680 case APValue::LValue:
7682 // There isn't necessarily a valid equivalent source-level syntax for
7683 // these; in particular, a naive lowering might violate access control.
7684 // So for now we lower to a ConstantExpr holding the value, wrapped around
7685 // an OpaqueValueExpr.
7686 // FIXME: We should have a better representation for this.
7688 if (T->isReferenceType()) {
7689 T = T->getPointeeType();
7690 VK = VK_LValue;
7691 }
7692 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7693 return ConstantExpr::Create(S.Context, OVE, Val);
7694 }
7695 llvm_unreachable("Unhandled APValue::ValueKind enum");
7696}
7697
7701 switch (Arg.getKind()) {
7707 llvm_unreachable("not a non-type template argument");
7708
7710 return Arg.getAsExpr();
7711
7716
7719 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7720
7723 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7724 }
7725 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7726}
7727
7728/// Match two template parameters within template parameter lists.
7730 Sema &S, NamedDecl *New,
7731 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7732 const NamedDecl *OldInstFrom, bool Complain,
7734 // Check the actual kind (type, non-type, template).
7735 if (Old->getKind() != New->getKind()) {
7736 if (Complain) {
7737 unsigned NextDiag = diag::err_template_param_different_kind;
7738 if (TemplateArgLoc.isValid()) {
7739 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7740 NextDiag = diag::note_template_param_different_kind;
7741 }
7742 S.Diag(New->getLocation(), NextDiag)
7743 << (Kind != Sema::TPL_TemplateMatch);
7744 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7745 << (Kind != Sema::TPL_TemplateMatch);
7746 }
7747
7748 return false;
7749 }
7750
7751 // Check that both are parameter packs or neither are parameter packs.
7752 // However, if we are matching a template template argument to a
7753 // template template parameter, the template template parameter can have
7754 // a parameter pack where the template template argument does not.
7755 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7757 Old->isTemplateParameterPack())) {
7758 if (Complain) {
7759 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7760 if (TemplateArgLoc.isValid()) {
7761 S.Diag(TemplateArgLoc,
7762 diag::err_template_arg_template_params_mismatch);
7763 NextDiag = diag::note_template_parameter_pack_non_pack;
7764 }
7765
7766 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7767 : isa<NonTypeTemplateParmDecl>(New)? 1
7768 : 2;
7769 S.Diag(New->getLocation(), NextDiag)
7770 << ParamKind << New->isParameterPack();
7771 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7772 << ParamKind << Old->isParameterPack();
7773 }
7774
7775 return false;
7776 }
7777
7778 // For non-type template parameters, check the type of the parameter.
7779 if (NonTypeTemplateParmDecl *OldNTTP
7780 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7781 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7782
7783 // If we are matching a template template argument to a template
7784 // template parameter and one of the non-type template parameter types
7785 // is dependent, then we must wait until template instantiation time
7786 // to actually compare the arguments.
7788 (!OldNTTP->getType()->isDependentType() &&
7789 !NewNTTP->getType()->isDependentType())) {
7790 // C++20 [temp.over.link]p6:
7791 // Two [non-type] template-parameters are equivalent [if] they have
7792 // equivalent types ignoring the use of type-constraints for
7793 // placeholder types
7794 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7795 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7796 if (!S.Context.hasSameType(OldType, NewType)) {
7797 if (Complain) {
7798 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7799 if (TemplateArgLoc.isValid()) {
7800 S.Diag(TemplateArgLoc,
7801 diag::err_template_arg_template_params_mismatch);
7802 NextDiag = diag::note_template_nontype_parm_different_type;
7803 }
7804 S.Diag(NewNTTP->getLocation(), NextDiag)
7805 << NewNTTP->getType()
7806 << (Kind != Sema::TPL_TemplateMatch);
7807 S.Diag(OldNTTP->getLocation(),
7808 diag::note_template_nontype_parm_prev_declaration)
7809 << OldNTTP->getType();
7810 }
7811
7812 return false;
7813 }
7814 }
7815 }
7816 // For template template parameters, check the template parameter types.
7817 // The template parameter lists of template template
7818 // parameters must agree.
7819 else if (TemplateTemplateParmDecl *OldTTP =
7820 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7821 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7823 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7824 OldTTP->getTemplateParameters(), Complain,
7827 : Kind),
7828 TemplateArgLoc))
7829 return false;
7830 }
7831
7834 !isa<TemplateTemplateParmDecl>(Old)) {
7835 const Expr *NewC = nullptr, *OldC = nullptr;
7836
7837 if (isa<TemplateTypeParmDecl>(New)) {
7838 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7839 NewC = TC->getImmediatelyDeclaredConstraint();
7840 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7841 OldC = TC->getImmediatelyDeclaredConstraint();
7842 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7843 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7844 ->getPlaceholderTypeConstraint())
7845 NewC = E;
7846 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7847 ->getPlaceholderTypeConstraint())
7848 OldC = E;
7849 } else
7850 llvm_unreachable("unexpected template parameter type");
7851
7852 auto Diagnose = [&] {
7853 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7854 diag::err_template_different_type_constraint);
7855 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7856 diag::note_template_prev_declaration) << /*declaration*/0;
7857 };
7858
7859 if (!NewC != !OldC) {
7860 if (Complain)
7861 Diagnose();
7862 return false;
7863 }
7864
7865 if (NewC) {
7866 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7867 NewC)) {
7868 if (Complain)
7869 Diagnose();
7870 return false;
7871 }
7872 }
7873 }
7874
7875 return true;
7876}
7877
7878/// Diagnose a known arity mismatch when comparing template argument
7879/// lists.
7880static
7885 SourceLocation TemplateArgLoc) {
7886 unsigned NextDiag = diag::err_template_param_list_different_arity;
7887 if (TemplateArgLoc.isValid()) {
7888 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7889 NextDiag = diag::note_template_param_list_different_arity;
7890 }
7891 S.Diag(New->getTemplateLoc(), NextDiag)
7892 << (New->size() > Old->size())
7893 << (Kind != Sema::TPL_TemplateMatch)
7894 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7895 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7896 << (Kind != Sema::TPL_TemplateMatch)
7897 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7898}
7899
7901 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7902 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7903 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7904 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7905 if (Complain)
7906 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7907 TemplateArgLoc);
7908
7909 return false;
7910 }
7911
7912 // C++0x [temp.arg.template]p3:
7913 // A template-argument matches a template template-parameter (call it P)
7914 // when each of the template parameters in the template-parameter-list of
7915 // the template-argument's corresponding class template or alias template
7916 // (call it A) matches the corresponding template parameter in the
7917 // template-parameter-list of P. [...]
7918 TemplateParameterList::iterator NewParm = New->begin();
7919 TemplateParameterList::iterator NewParmEnd = New->end();
7920 for (TemplateParameterList::iterator OldParm = Old->begin(),
7921 OldParmEnd = Old->end();
7922 OldParm != OldParmEnd; ++OldParm) {
7924 !(*OldParm)->isTemplateParameterPack()) {
7925 if (NewParm == NewParmEnd) {
7926 if (Complain)
7927 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7928 TemplateArgLoc);
7929
7930 return false;
7931 }
7932
7933 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7934 OldInstFrom, Complain, Kind,
7935 TemplateArgLoc))
7936 return false;
7937
7938 ++NewParm;
7939 continue;
7940 }
7941
7942 // C++0x [temp.arg.template]p3:
7943 // [...] When P's template- parameter-list contains a template parameter
7944 // pack (14.5.3), the template parameter pack will match zero or more
7945 // template parameters or template parameter packs in the
7946 // template-parameter-list of A with the same type and form as the
7947 // template parameter pack in P (ignoring whether those template
7948 // parameters are template parameter packs).
7949 for (; NewParm != NewParmEnd; ++NewParm) {
7950 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7951 OldInstFrom, Complain, Kind,
7952 TemplateArgLoc))
7953 return false;
7954 }
7955 }
7956
7957 // Make sure we exhausted all of the arguments.
7958 if (NewParm != NewParmEnd) {
7959 if (Complain)
7960 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7961 TemplateArgLoc);
7962
7963 return false;
7964 }
7965
7968 const Expr *NewRC = New->getRequiresClause();
7969 const Expr *OldRC = Old->getRequiresClause();
7970
7971 auto Diagnose = [&] {
7972 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7973 diag::err_template_different_requires_clause);
7974 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7975 diag::note_template_prev_declaration) << /*declaration*/0;
7976 };
7977
7978 if (!NewRC != !OldRC) {
7979 if (Complain)
7980 Diagnose();
7981 return false;
7982 }
7983
7984 if (NewRC) {
7985 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7986 NewRC)) {
7987 if (Complain)
7988 Diagnose();
7989 return false;
7990 }
7991 }
7992 }
7993
7994 return true;
7995}
7996
7997bool
7999 if (!S)
8000 return false;
8001
8002 // Find the nearest enclosing declaration scope.
8003 S = S->getDeclParent();
8004
8005 // C++ [temp.pre]p6: [P2096]
8006 // A template, explicit specialization, or partial specialization shall not
8007 // have C linkage.
8008 DeclContext *Ctx = S->getEntity();
8009 if (Ctx && Ctx->isExternCContext()) {
8010 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8011 << TemplateParams->getSourceRange();
8012 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8013 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8014 return true;
8015 }
8016 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8017
8018 // C++ [temp]p2:
8019 // A template-declaration can appear only as a namespace scope or
8020 // class scope declaration.
8021 // C++ [temp.expl.spec]p3:
8022 // An explicit specialization may be declared in any scope in which the
8023 // corresponding primary template may be defined.
8024 // C++ [temp.class.spec]p6: [P2096]
8025 // A partial specialization may be declared in any scope in which the
8026 // corresponding primary template may be defined.
8027 if (Ctx) {
8028 if (Ctx->isFileContext())
8029 return false;
8030 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8031 // C++ [temp.mem]p2:
8032 // A local class shall not have member templates.
8033 if (RD->isLocalClass())
8034 return Diag(TemplateParams->getTemplateLoc(),
8035 diag::err_template_inside_local_class)
8036 << TemplateParams->getSourceRange();
8037 else
8038 return false;
8039 }
8040 }
8041
8042 return Diag(TemplateParams->getTemplateLoc(),
8043 diag::err_template_outside_namespace_or_class_scope)
8044 << TemplateParams->getSourceRange();
8045}
8046
8047/// Determine what kind of template specialization the given declaration
8048/// is.
8050 if (!D)
8051 return TSK_Undeclared;
8052
8053 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8054 return Record->getTemplateSpecializationKind();
8055 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8056 return Function->getTemplateSpecializationKind();
8057 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8058 return Var->getTemplateSpecializationKind();
8059
8060 return TSK_Undeclared;
8061}
8062
8063/// Check whether a specialization is well-formed in the current
8064/// context.
8065///
8066/// This routine determines whether a template specialization can be declared
8067/// in the current context (C++ [temp.expl.spec]p2).
8068///
8069/// \param S the semantic analysis object for which this check is being
8070/// performed.
8071///
8072/// \param Specialized the entity being specialized or instantiated, which
8073/// may be a kind of template (class template, function template, etc.) or
8074/// a member of a class template (member function, static data member,
8075/// member class).
8076///
8077/// \param PrevDecl the previous declaration of this entity, if any.
8078///
8079/// \param Loc the location of the explicit specialization or instantiation of
8080/// this entity.
8081///
8082/// \param IsPartialSpecialization whether this is a partial specialization of
8083/// a class template.
8084///
8085/// \returns true if there was an error that we cannot recover from, false
8086/// otherwise.
8088 NamedDecl *Specialized,
8089 NamedDecl *PrevDecl,
8092 // Keep these "kind" numbers in sync with the %select statements in the
8093 // various diagnostics emitted by this routine.
8094 int EntityKind = 0;
8095 if (isa<ClassTemplateDecl>(Specialized))
8096 EntityKind = IsPartialSpecialization? 1 : 0;
8097 else if (isa<VarTemplateDecl>(Specialized))
8098 EntityKind = IsPartialSpecialization ? 3 : 2;
8099 else if (isa<FunctionTemplateDecl>(Specialized))
8100 EntityKind = 4;
8101 else if (isa<CXXMethodDecl>(Specialized))
8102 EntityKind = 5;
8103 else if (isa<VarDecl>(Specialized))
8104 EntityKind = 6;
8105 else if (isa<RecordDecl>(Specialized))
8106 EntityKind = 7;
8107 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8108 EntityKind = 8;
8109 else {
8110 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8111 << S.getLangOpts().CPlusPlus11;
8112 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8113 return true;
8114 }
8115
8116 // C++ [temp.expl.spec]p2:
8117 // An explicit specialization may be declared in any scope in which
8118 // the corresponding primary template may be defined.
8120 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8121 << Specialized;
8122 return true;
8123 }
8124
8125 // C++ [temp.class.spec]p6:
8126 // A class template partial specialization may be declared in any
8127 // scope in which the primary template may be defined.
8128 DeclContext *SpecializedContext =
8129 Specialized->getDeclContext()->getRedeclContext();
8131
8132 // Make sure that this redeclaration (or definition) occurs in the same
8133 // scope or an enclosing namespace.
8134 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8135 : DC->Equals(SpecializedContext))) {
8136 if (isa<TranslationUnitDecl>(SpecializedContext))
8137 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8138 << EntityKind << Specialized;
8139 else {
8140 auto *ND = cast<NamedDecl>(SpecializedContext);
8141 int Diag = diag::err_template_spec_redecl_out_of_scope;
8142 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8143 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8144 S.Diag(Loc, Diag) << EntityKind << Specialized
8145 << ND << isa<CXXRecordDecl>(ND);
8146 }
8147
8148 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8149
8150 // Don't allow specializing in the wrong class during error recovery.
8151 // Otherwise, things can go horribly wrong.
8152 if (DC->isRecord())
8153 return true;
8154 }
8155
8156 return false;
8157}
8158
8160 if (!E->isTypeDependent())
8161 return SourceLocation();
8162 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8163 Checker.TraverseStmt(E);
8164 if (Checker.MatchLoc.isInvalid())
8165 return E->getSourceRange();
8166 return Checker.MatchLoc;
8167}
8168
8169static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8170 if (!TL.getType()->isDependentType())
8171 return SourceLocation();
8172 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8173 Checker.TraverseTypeLoc(TL);
8174 if (Checker.MatchLoc.isInvalid())
8175 return TL.getSourceRange();
8176 return Checker.MatchLoc;
8177}
8178
8179/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8180/// that checks non-type template partial specialization arguments.
8182 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8183 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8184 for (unsigned I = 0; I != NumArgs; ++I) {
8185 if (Args[I].getKind() == TemplateArgument::Pack) {
8187 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8188 Args[I].pack_size(), IsDefaultArgument))
8189 return true;
8190
8191 continue;
8192 }
8193
8194 if (Args[I].getKind() != TemplateArgument::Expression)
8195 continue;
8196
8197 Expr *ArgExpr = Args[I].getAsExpr();
8198
8199 // We can have a pack expansion of any of the bullets below.
8200 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8201 ArgExpr = Expansion->getPattern();
8202
8203 // Strip off any implicit casts we added as part of type checking.
8204 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8205 ArgExpr = ICE->getSubExpr();
8206
8207 // C++ [temp.class.spec]p8:
8208 // A non-type argument is non-specialized if it is the name of a
8209 // non-type parameter. All other non-type arguments are
8210 // specialized.
8211 //
8212 // Below, we check the two conditions that only apply to
8213 // specialized non-type arguments, so skip any non-specialized
8214 // arguments.
8215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8216 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8217 continue;
8218
8219 // C++ [temp.class.spec]p9:
8220 // Within the argument list of a class template partial
8221 // specialization, the following restrictions apply:
8222 // -- A partially specialized non-type argument expression
8223 // shall not involve a template parameter of the partial
8224 // specialization except when the argument expression is a
8225 // simple identifier.
8226 // -- The type of a template parameter corresponding to a
8227 // specialized non-type argument shall not be dependent on a
8228 // parameter of the specialization.
8229 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8230 // We implement a compromise between the original rules and DR1315:
8231 // -- A specialized non-type template argument shall not be
8232 // type-dependent and the corresponding template parameter
8233 // shall have a non-dependent type.
8234 SourceRange ParamUseRange =
8235 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8236 if (ParamUseRange.isValid()) {
8237 if (IsDefaultArgument) {
8238 S.Diag(TemplateNameLoc,
8239 diag::err_dependent_non_type_arg_in_partial_spec);
8240 S.Diag(ParamUseRange.getBegin(),
8241 diag::note_dependent_non_type_default_arg_in_partial_spec)
8242 << ParamUseRange;
8243 } else {
8244 S.Diag(ParamUseRange.getBegin(),
8245 diag::err_dependent_non_type_arg_in_partial_spec)
8246 << ParamUseRange;
8247 }
8248 return true;
8249 }
8250
8251 ParamUseRange = findTemplateParameter(
8252 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8253 if (ParamUseRange.isValid()) {
8254 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8255 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8256 << Param->getType();
8258 return true;
8259 }
8260 }
8261
8262 return false;
8263}
8264
8266 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8267 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8268 // We have to be conservative when checking a template in a dependent
8269 // context.
8270 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8271 return false;
8272
8273 TemplateParameterList *TemplateParams =
8274 PrimaryTemplate->getTemplateParameters();
8275 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8277 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8278 if (!Param)
8279 continue;
8280
8281 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8282 Param, &TemplateArgs[I],
8283 1, I >= NumExplicit))
8284 return true;
8285 }
8286
8287 return false;
8288}
8289
8291 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8292 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8294 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8295 assert(TUK != TagUseKind::Reference && "References are not specializations");
8296
8297 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8298 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8299 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8300
8301 // Find the class template we're specializing
8302 TemplateName Name = TemplateId.Template.get();
8304 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8305
8306 if (!ClassTemplate) {
8307 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8308 << (Name.getAsTemplateDecl() &&
8309 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8310 return true;
8311 }
8312
8313 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8314 auto Message = DSA->getMessage();
8315 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8316 << ClassTemplate << !Message.empty() << Message;
8317 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8318 }
8319
8320 if (S->isTemplateParamScope())
8321 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8322
8323 DeclContext *DC = ClassTemplate->getDeclContext();
8324
8325 bool isMemberSpecialization = false;
8326 bool isPartialSpecialization = false;
8327
8328 if (SS.isSet()) {
8329 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8330 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8331 TemplateNameLoc, &TemplateId,
8332 /*IsMemberSpecialization=*/false))
8333 return true;
8334 }
8335
8336 // Check the validity of the template headers that introduce this
8337 // template.
8338 // FIXME: We probably shouldn't complain about these headers for
8339 // friend declarations.
8340 bool Invalid = false;
8341 TemplateParameterList *TemplateParams =
8343 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8344 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8345 if (Invalid)
8346 return true;
8347
8348 // Check that we can declare a template specialization here.
8349 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8350 return true;
8351
8352 if (TemplateParams && DC->isDependentContext()) {
8353 ContextRAII SavedContext(*this, DC);
8355 return true;
8356 }
8357
8358 if (TemplateParams && TemplateParams->size() > 0) {
8359 isPartialSpecialization = true;
8360
8361 if (TUK == TagUseKind::Friend) {
8362 Diag(KWLoc, diag::err_partial_specialization_friend)
8363 << SourceRange(LAngleLoc, RAngleLoc);
8364 return true;
8365 }
8366
8367 // C++ [temp.class.spec]p10:
8368 // The template parameter list of a specialization shall not
8369 // contain default template argument values.
8370 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8371 Decl *Param = TemplateParams->getParam(I);
8372 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8373 if (TTP->hasDefaultArgument()) {
8374 Diag(TTP->getDefaultArgumentLoc(),
8375 diag::err_default_arg_in_partial_spec);
8376 TTP->removeDefaultArgument();
8377 }
8378 } else if (NonTypeTemplateParmDecl *NTTP
8379 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8380 if (NTTP->hasDefaultArgument()) {
8381 Diag(NTTP->getDefaultArgumentLoc(),
8382 diag::err_default_arg_in_partial_spec)
8383 << NTTP->getDefaultArgument().getSourceRange();
8384 NTTP->removeDefaultArgument();
8385 }
8386 } else {
8387 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8388 if (TTP->hasDefaultArgument()) {
8390 diag::err_default_arg_in_partial_spec)
8392 TTP->removeDefaultArgument();
8393 }
8394 }
8395 }
8396 } else if (TemplateParams) {
8397 if (TUK == TagUseKind::Friend)
8398 Diag(KWLoc, diag::err_template_spec_friend)
8400 SourceRange(TemplateParams->getTemplateLoc(),
8401 TemplateParams->getRAngleLoc()))
8402 << SourceRange(LAngleLoc, RAngleLoc);
8403 } else {
8404 assert(TUK == TagUseKind::Friend &&
8405 "should have a 'template<>' for this decl");
8406 }
8407
8408 // Check that the specialization uses the same tag kind as the
8409 // original template.
8411 assert(Kind != TagTypeKind::Enum &&
8412 "Invalid enum tag in class template spec!");
8413 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8414 TUK == TagUseKind::Definition, KWLoc,
8415 ClassTemplate->getIdentifier())) {
8416 Diag(KWLoc, diag::err_use_with_wrong_tag)
8417 << ClassTemplate
8419 ClassTemplate->getTemplatedDecl()->getKindName());
8420 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8421 diag::note_previous_use);
8422 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8423 }
8424
8425 // Translate the parser's template argument list in our AST format.
8426 TemplateArgumentListInfo TemplateArgs =
8427 makeTemplateArgumentListInfo(*this, TemplateId);
8428
8429 // Check for unexpanded parameter packs in any of the template arguments.
8430 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8431 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8432 isPartialSpecialization
8435 return true;
8436
8437 // Check that the template argument list is well-formed for this
8438 // template.
8439 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8440 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8441 /*DefaultArgs=*/{},
8442 /*PartialTemplateArgs=*/false, SugaredConverted,
8443 CanonicalConverted,
8444 /*UpdateArgsWithConversions=*/true))
8445 return true;
8446
8447 // Find the class template (partial) specialization declaration that
8448 // corresponds to these arguments.
8449 if (isPartialSpecialization) {
8451 TemplateArgs.size(),
8452 CanonicalConverted))
8453 return true;
8454
8455 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8456 // also do it during instantiation.
8457 if (!Name.isDependent() &&
8459 TemplateArgs, CanonicalConverted)) {
8460 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8461 << ClassTemplate->getDeclName();
8462 isPartialSpecialization = false;
8463 Invalid = true;
8464 }
8465 }
8466
8467 void *InsertPos = nullptr;
8468 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8469
8470 if (isPartialSpecialization)
8471 PrevDecl = ClassTemplate->findPartialSpecialization(
8472 CanonicalConverted, TemplateParams, InsertPos);
8473 else
8474 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8475
8477
8478 // Check whether we can declare a class template specialization in
8479 // the current scope.
8480 if (TUK != TagUseKind::Friend &&
8482 TemplateNameLoc,
8483 isPartialSpecialization))
8484 return true;
8485
8486 // The canonical type
8487 QualType CanonType;
8488 if (isPartialSpecialization) {
8489 // Build the canonical type that describes the converted template
8490 // arguments of the class template partial specialization.
8491 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8492 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8493 CanonicalConverted);
8494
8495 if (Context.hasSameType(CanonType,
8496 ClassTemplate->getInjectedClassNameSpecialization()) &&
8497 (!Context.getLangOpts().CPlusPlus20 ||
8498 !TemplateParams->hasAssociatedConstraints())) {
8499 // C++ [temp.class.spec]p9b3:
8500 //
8501 // -- The argument list of the specialization shall not be identical
8502 // to the implicit argument list of the primary template.
8503 //
8504 // This rule has since been removed, because it's redundant given DR1495,
8505 // but we keep it because it produces better diagnostics and recovery.
8506 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8507 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8508 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8509 return CheckClassTemplate(
8510 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8511 TemplateNameLoc, Attr, TemplateParams, AS_none,
8512 /*ModulePrivateLoc=*/SourceLocation(),
8513 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8514 TemplateParameterLists.data());
8515 }
8516
8517 // Create a new class template partial specialization declaration node.
8519 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8522 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8523 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8524 Partial->setTemplateArgsAsWritten(TemplateArgs);
8525 SetNestedNameSpecifier(*this, Partial, SS);
8526 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8528 Context, TemplateParameterLists.drop_back(1));
8529 }
8530
8531 if (!PrevPartial)
8532 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8533 Specialization = Partial;
8534
8535 // If we are providing an explicit specialization of a member class
8536 // template specialization, make a note of that.
8537 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8538 PrevPartial->setMemberSpecialization();
8539
8541 } else {
8542 // Create a new class template specialization declaration node for
8543 // this explicit specialization or friend declaration.
8545 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8546 CanonicalConverted, PrevDecl);
8547 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8549 if (TemplateParameterLists.size() > 0) {
8550 Specialization->setTemplateParameterListsInfo(Context,
8551 TemplateParameterLists);
8552 }
8553
8554 if (!PrevDecl)
8555 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8556
8558 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8559 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8560 CanonicalConverted);
8561 } else {
8563 }
8564 }
8565
8566 // C++ [temp.expl.spec]p6:
8567 // If a template, a member template or the member of a class template is
8568 // explicitly specialized then that specialization shall be declared
8569 // before the first use of that specialization that would cause an implicit
8570 // instantiation to take place, in every translation unit in which such a
8571 // use occurs; no diagnostic is required.
8572 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8573 bool Okay = false;
8574 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8575 // Is there any previous explicit specialization declaration?
8577 Okay = true;
8578 break;
8579 }
8580 }
8581
8582 if (!Okay) {
8583 SourceRange Range(TemplateNameLoc, RAngleLoc);
8584 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8586
8587 Diag(PrevDecl->getPointOfInstantiation(),
8588 diag::note_instantiation_required_here)
8589 << (PrevDecl->getTemplateSpecializationKind()
8591 return true;
8592 }
8593 }
8594
8595 // If this is not a friend, note that this is an explicit specialization.
8596 if (TUK != TagUseKind::Friend)
8597 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8598
8599 // Check that this isn't a redefinition of this specialization.
8600 if (TUK == TagUseKind::Definition) {
8601 RecordDecl *Def = Specialization->getDefinition();
8602 NamedDecl *Hidden = nullptr;
8603 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8604 SkipBody->ShouldSkip = true;
8605 SkipBody->Previous = Def;
8607 } else if (Def) {
8608 SourceRange Range(TemplateNameLoc, RAngleLoc);
8609 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8610 Diag(Def->getLocation(), diag::note_previous_definition);
8611 Specialization->setInvalidDecl();
8612 return true;
8613 }
8614 }
8615
8618
8619 // Add alignment attributes if necessary; these attributes are checked when
8620 // the ASTContext lays out the structure.
8621 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8624 }
8625
8626 if (ModulePrivateLoc.isValid())
8627 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8628 << (isPartialSpecialization? 1 : 0)
8629 << FixItHint::CreateRemoval(ModulePrivateLoc);
8630
8631 // C++ [temp.expl.spec]p9:
8632 // A template explicit specialization is in the scope of the
8633 // namespace in which the template was defined.
8634 //
8635 // We actually implement this paragraph where we set the semantic
8636 // context (in the creation of the ClassTemplateSpecializationDecl),
8637 // but we also maintain the lexical context where the actual
8638 // definition occurs.
8639 Specialization->setLexicalDeclContext(CurContext);
8640
8641 // We may be starting the definition of this specialization.
8642 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8643 Specialization->startDefinition();
8644
8645 if (TUK == TagUseKind::Friend) {
8646 // Build the fully-sugared type for this class template
8647 // specialization as the user wrote in the specialization
8648 // itself. This means that we'll pretty-print the type retrieved
8649 // from the specialization's declaration the way that the user
8650 // actually wrote the specialization, rather than formatting the
8651 // name based on the "canonical" representation used to store the
8652 // template arguments in the specialization.
8654 Name, TemplateNameLoc, TemplateArgs, CanonType);
8656 TemplateNameLoc,
8657 WrittenTy,
8658 /*FIXME:*/KWLoc);
8659 Friend->setAccess(AS_public);
8661 } else {
8662 // Add the specialization into its lexical context, so that it can
8663 // be seen when iterating through the list of declarations in that
8664 // context. However, specializations are not found by name lookup.
8666 }
8667
8668 if (SkipBody && SkipBody->ShouldSkip)
8669 return SkipBody->Previous;
8670
8671 Specialization->setInvalidDecl(Invalid);
8673 return Specialization;
8674}
8675
8677 MultiTemplateParamsArg TemplateParameterLists,
8678 Declarator &D) {
8679 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8680 ActOnDocumentableDecl(NewDecl);
8681 return NewDecl;
8682}
8683
8685 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8686 const IdentifierInfo *Name, SourceLocation NameLoc) {
8687 DeclContext *DC = CurContext;
8688
8689 if (!DC->getRedeclContext()->isFileContext()) {
8690 Diag(NameLoc,
8691 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8692 return nullptr;
8693 }
8694
8695 if (TemplateParameterLists.size() > 1) {
8696 Diag(NameLoc, diag::err_concept_extra_headers);
8697 return nullptr;
8698 }
8699
8700 TemplateParameterList *Params = TemplateParameterLists.front();
8701
8702 if (Params->size() == 0) {
8703 Diag(NameLoc, diag::err_concept_no_parameters);
8704 return nullptr;
8705 }
8706
8707 // Ensure that the parameter pack, if present, is the last parameter in the
8708 // template.
8709 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8710 ParamEnd = Params->end();
8711 ParamIt != ParamEnd; ++ParamIt) {
8712 Decl const *Param = *ParamIt;
8713 if (Param->isParameterPack()) {
8714 if (++ParamIt == ParamEnd)
8715 break;
8716 Diag(Param->getLocation(),
8717 diag::err_template_param_pack_must_be_last_template_parameter);
8718 return nullptr;
8719 }
8720 }
8721
8722 ConceptDecl *NewDecl =
8723 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8724
8725 if (NewDecl->hasAssociatedConstraints()) {
8726 // C++2a [temp.concept]p4:
8727 // A concept shall not have associated constraints.
8728 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8729 NewDecl->setInvalidDecl();
8730 }
8731
8732 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8733 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8735 LookupName(Previous, S);
8736 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8737 /*AllowInlineNamespace*/ false);
8738
8739 // We cannot properly handle redeclarations until we parse the constraint
8740 // expression, so only inject the name if we are sure we are not redeclaring a
8741 // symbol
8742 if (Previous.empty())
8743 PushOnScopeChains(NewDecl, S, true);
8744
8745 return NewDecl;
8746}
8747
8749 bool Found = false;
8751 while (F.hasNext()) {
8752 NamedDecl *D = F.next();
8753 if (D == C) {
8754 F.erase();
8755 Found = true;
8756 break;
8757 }
8758 }
8759 F.done();
8760 return Found;
8761}
8762
8765 Expr *ConstraintExpr,
8766 const ParsedAttributesView &Attrs) {
8767 assert(!C->hasDefinition() && "Concept already defined");
8768 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8769 return nullptr;
8770 C->setDefinition(ConstraintExpr);
8771 ProcessDeclAttributeList(S, C, Attrs);
8772
8773 // Check for conflicting previous declaration.
8774 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8775 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8777 LookupName(Previous, S);
8778 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8779 /*AllowInlineNamespace*/ false);
8780 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8781 bool AddToScope = true;
8782 CheckConceptRedefinition(C, Previous, AddToScope);
8783
8785 if (!WasAlreadyAdded && AddToScope)
8786 PushOnScopeChains(C, S);
8787
8788 return C;
8789}
8790
8792 LookupResult &Previous, bool &AddToScope) {
8793 AddToScope = true;
8794
8795 if (Previous.empty())
8796 return;
8797
8798 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8799 if (!OldConcept) {
8800 auto *Old = Previous.getRepresentativeDecl();
8801 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8802 << NewDecl->getDeclName();
8803 notePreviousDefinition(Old, NewDecl->getLocation());
8804 AddToScope = false;
8805 return;
8806 }
8807 // Check if we can merge with a concept declaration.
8808 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8809 if (!IsSame) {
8810 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8811 << NewDecl->getDeclName();
8812 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8813 AddToScope = false;
8814 return;
8815 }
8816 if (hasReachableDefinition(OldConcept) &&
8817 IsRedefinitionInModule(NewDecl, OldConcept)) {
8818 Diag(NewDecl->getLocation(), diag::err_redefinition)
8819 << NewDecl->getDeclName();
8820 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8821 AddToScope = false;
8822 return;
8823 }
8824 if (!Previous.isSingleResult()) {
8825 // FIXME: we should produce an error in case of ambig and failed lookups.
8826 // Other decls (e.g. namespaces) also have this shortcoming.
8827 return;
8828 }
8829 // We unwrap canonical decl late to check for module visibility.
8830 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8831}
8832
8835 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8836 Diag(Loc, diag::err_recursive_concept) << Concept;
8837 Diag(Concept->getLocation(), diag::note_declared_at);
8838 return true;
8839 }
8840 return false;
8841}
8842
8843/// \brief Strips various properties off an implicit instantiation
8844/// that has just been explicitly specialized.
8845static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8846 if (MinGW || (isa<FunctionDecl>(D) &&
8847 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8848 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8849
8850 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8851 FD->setInlineSpecified(false);
8852}
8853
8854/// Compute the diagnostic location for an explicit instantiation
8855// declaration or definition.
8857 NamedDecl* D, SourceLocation PointOfInstantiation) {
8858 // Explicit instantiations following a specialization have no effect and
8859 // hence no PointOfInstantiation. In that case, walk decl backwards
8860 // until a valid name loc is found.
8861 SourceLocation PrevDiagLoc = PointOfInstantiation;
8862 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8863 Prev = Prev->getPreviousDecl()) {
8864 PrevDiagLoc = Prev->getLocation();
8865 }
8866 assert(PrevDiagLoc.isValid() &&
8867 "Explicit instantiation without point of instantiation?");
8868 return PrevDiagLoc;
8869}
8870
8871bool
8874 NamedDecl *PrevDecl,
8876 SourceLocation PrevPointOfInstantiation,
8877 bool &HasNoEffect) {
8878 HasNoEffect = false;
8879
8880 switch (NewTSK) {
8881 case TSK_Undeclared:
8883 assert(
8884 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8885 "previous declaration must be implicit!");
8886 return false;
8887
8889 switch (PrevTSK) {
8890 case TSK_Undeclared:
8892 // Okay, we're just specializing something that is either already
8893 // explicitly specialized or has merely been mentioned without any
8894 // instantiation.
8895 return false;
8896
8898 if (PrevPointOfInstantiation.isInvalid()) {
8899 // The declaration itself has not actually been instantiated, so it is
8900 // still okay to specialize it.
8902 PrevDecl,
8903 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8904 return false;
8905 }
8906 // Fall through
8907 [[fallthrough]];
8908
8911 assert((PrevTSK == TSK_ImplicitInstantiation ||
8912 PrevPointOfInstantiation.isValid()) &&
8913 "Explicit instantiation without point of instantiation?");
8914
8915 // C++ [temp.expl.spec]p6:
8916 // If a template, a member template or the member of a class template
8917 // is explicitly specialized then that specialization shall be declared
8918 // before the first use of that specialization that would cause an
8919 // implicit instantiation to take place, in every translation unit in
8920 // which such a use occurs; no diagnostic is required.
8921 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8922 // Is there any previous explicit specialization declaration?
8924 return false;
8925 }
8926
8927 Diag(NewLoc, diag::err_specialization_after_instantiation)
8928 << PrevDecl;
8929 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8930 << (PrevTSK != TSK_ImplicitInstantiation);
8931
8932 return true;
8933 }
8934 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8935
8937 switch (PrevTSK) {
8939 // This explicit instantiation declaration is redundant (that's okay).
8940 HasNoEffect = true;
8941 return false;
8942
8943 case TSK_Undeclared:
8945 // We're explicitly instantiating something that may have already been
8946 // implicitly instantiated; that's fine.
8947 return false;
8948
8950 // C++0x [temp.explicit]p4:
8951 // For a given set of template parameters, if an explicit instantiation
8952 // of a template appears after a declaration of an explicit
8953 // specialization for that template, the explicit instantiation has no
8954 // effect.
8955 HasNoEffect = true;
8956 return false;
8957
8959 // C++0x [temp.explicit]p10:
8960 // If an entity is the subject of both an explicit instantiation
8961 // declaration and an explicit instantiation definition in the same
8962 // translation unit, the definition shall follow the declaration.
8963 Diag(NewLoc,
8964 diag::err_explicit_instantiation_declaration_after_definition);
8965
8966 // Explicit instantiations following a specialization have no effect and
8967 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8968 // until a valid name loc is found.
8969 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8970 diag::note_explicit_instantiation_definition_here);
8971 HasNoEffect = true;
8972 return false;
8973 }
8974 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8975
8977 switch (PrevTSK) {
8978 case TSK_Undeclared:
8980 // We're explicitly instantiating something that may have already been
8981 // implicitly instantiated; that's fine.
8982 return false;
8983
8985 // C++ DR 259, C++0x [temp.explicit]p4:
8986 // For a given set of template parameters, if an explicit
8987 // instantiation of a template appears after a declaration of
8988 // an explicit specialization for that template, the explicit
8989 // instantiation has no effect.
8990 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8991 << PrevDecl;
8992 Diag(PrevDecl->getLocation(),
8993 diag::note_previous_template_specialization);
8994 HasNoEffect = true;
8995 return false;
8996
8998 // We're explicitly instantiating a definition for something for which we
8999 // were previously asked to suppress instantiations. That's fine.
9000
9001 // C++0x [temp.explicit]p4:
9002 // For a given set of template parameters, if an explicit instantiation
9003 // of a template appears after a declaration of an explicit
9004 // specialization for that template, the explicit instantiation has no
9005 // effect.
9006 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9007 // Is there any previous explicit specialization declaration?
9009 HasNoEffect = true;
9010 break;
9011 }
9012 }
9013
9014 return false;
9015
9017 // C++0x [temp.spec]p5:
9018 // For a given template and a given set of template-arguments,
9019 // - an explicit instantiation definition shall appear at most once
9020 // in a program,
9021
9022 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9023 Diag(NewLoc, (getLangOpts().MSVCCompat)
9024 ? diag::ext_explicit_instantiation_duplicate
9025 : diag::err_explicit_instantiation_duplicate)
9026 << PrevDecl;
9027 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9028 diag::note_previous_explicit_instantiation);
9029 HasNoEffect = true;
9030 return false;
9031 }
9032 }
9033
9034 llvm_unreachable("Missing specialization/instantiation case?");
9035}
9036
9038 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9040 // Remove anything from Previous that isn't a function template in
9041 // the correct context.
9042 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9043 LookupResult::Filter F = Previous.makeFilter();
9044 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9045 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9046 while (F.hasNext()) {
9048 if (!isa<FunctionTemplateDecl>(D)) {
9049 F.erase();
9050 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9051 continue;
9052 }
9053
9054 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9056 F.erase();
9057 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9058 continue;
9059 }
9060 }
9061 F.done();
9062
9063 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9064 if (Previous.empty()) {
9065 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9066 << IsFriend;
9067 for (auto &P : DiscardedCandidates)
9068 Diag(P.second->getLocation(),
9069 diag::note_dependent_function_template_spec_discard_reason)
9070 << P.first << IsFriend;
9071 return true;
9072 }
9073
9075 ExplicitTemplateArgs);
9076 return false;
9077}
9078
9080 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9081 LookupResult &Previous, bool QualifiedFriend) {
9082 // The set of function template specializations that could match this
9083 // explicit function template specialization.
9084 UnresolvedSet<8> Candidates;
9085 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9086 /*ForTakingAddress=*/false);
9087
9088 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9089 ConvertedTemplateArgs;
9090
9091 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9092 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9093 I != E; ++I) {
9094 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9095 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9096 // Only consider templates found within the same semantic lookup scope as
9097 // FD.
9098 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9100 continue;
9101
9102 QualType FT = FD->getType();
9103 // C++11 [dcl.constexpr]p8:
9104 // A constexpr specifier for a non-static member function that is not
9105 // a constructor declares that member function to be const.
9106 //
9107 // When matching a constexpr member function template specialization
9108 // against the primary template, we don't yet know whether the
9109 // specialization has an implicit 'const' (because we don't know whether
9110 // it will be a static member function until we know which template it
9111 // specializes). This rule was removed in C++14.
9112 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9113 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9114 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9115 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9116 if (OldMD && OldMD->isConst()) {
9117 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9119 EPI.TypeQuals.addConst();
9121 FPT->getParamTypes(), EPI);
9122 }
9123 }
9124
9126 if (ExplicitTemplateArgs)
9127 Args = *ExplicitTemplateArgs;
9128
9129 // C++ [temp.expl.spec]p11:
9130 // A trailing template-argument can be left unspecified in the
9131 // template-id naming an explicit function template specialization
9132 // provided it can be deduced from the function argument type.
9133 // Perform template argument deduction to determine whether we may be
9134 // specializing this template.
9135 // FIXME: It is somewhat wasteful to build
9136 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9137 FunctionDecl *Specialization = nullptr;
9139 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9140 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9142 // Template argument deduction failed; record why it failed, so
9143 // that we can provide nifty diagnostics.
9144 FailedCandidates.addCandidate().set(
9145 I.getPair(), FunTmpl->getTemplatedDecl(),
9146 MakeDeductionFailureInfo(Context, TDK, Info));
9147 (void)TDK;
9148 continue;
9149 }
9150
9151 // Target attributes are part of the cuda function signature, so
9152 // the deduced template's cuda target must match that of the
9153 // specialization. Given that C++ template deduction does not
9154 // take target attributes into account, we reject candidates
9155 // here that have a different target.
9156 if (LangOpts.CUDA &&
9158 /* IgnoreImplicitHDAttr = */ true) !=
9159 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9160 FailedCandidates.addCandidate().set(
9161 I.getPair(), FunTmpl->getTemplatedDecl(),
9164 continue;
9165 }
9166
9167 // Record this candidate.
9168 if (ExplicitTemplateArgs)
9169 ConvertedTemplateArgs[Specialization] = std::move(Args);
9170 Candidates.addDecl(Specialization, I.getAccess());
9171 }
9172 }
9173
9174 // For a qualified friend declaration (with no explicit marker to indicate
9175 // that a template specialization was intended), note all (template and
9176 // non-template) candidates.
9177 if (QualifiedFriend && Candidates.empty()) {
9178 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9179 << FD->getDeclName() << FDLookupContext;
9180 // FIXME: We should form a single candidate list and diagnose all
9181 // candidates at once, to get proper sorting and limiting.
9182 for (auto *OldND : Previous) {
9183 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9184 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9185 }
9186 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9187 return true;
9188 }
9189
9190 // Find the most specialized function template.
9192 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9193 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9194 PDiag(diag::err_function_template_spec_ambiguous)
9195 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9196 PDiag(diag::note_function_template_spec_matched));
9197
9198 if (Result == Candidates.end())
9199 return true;
9200
9201 // Ignore access information; it doesn't figure into redeclaration checking.
9202 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9203
9204 if (const auto *PT = Specialization->getPrimaryTemplate();
9205 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9206 auto Message = DSA->getMessage();
9207 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9208 << PT << !Message.empty() << Message;
9209 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9210 }
9211
9212 // C++23 [except.spec]p13:
9213 // An exception specification is considered to be needed when:
9214 // - [...]
9215 // - the exception specification is compared to that of another declaration
9216 // (e.g., an explicit specialization or an overriding virtual function);
9217 // - [...]
9218 //
9219 // The exception specification of a defaulted function is evaluated as
9220 // described above only when needed; similarly, the noexcept-specifier of a
9221 // specialization of a function template or member function of a class
9222 // template is instantiated only when needed.
9223 //
9224 // The standard doesn't specify what the "comparison with another declaration"
9225 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9226 // not state which properties of an explicit specialization must match the
9227 // primary template.
9228 //
9229 // We assume that an explicit specialization must correspond with (per
9230 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9231 // the declaration produced by substitution into the function template.
9232 //
9233 // Since the determination whether two function declarations correspond does
9234 // not consider exception specification, we only need to instantiate it once
9235 // we determine the primary template when comparing types per
9236 // [basic.link]p11.1.
9237 auto *SpecializationFPT =
9238 Specialization->getType()->castAs<FunctionProtoType>();
9239 // If the function has a dependent exception specification, resolve it after
9240 // we have selected the primary template so we can check whether it matches.
9241 if (getLangOpts().CPlusPlus17 &&
9242 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9243 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9244 return true;
9245
9247 = Specialization->getTemplateSpecializationInfo();
9248 assert(SpecInfo && "Function template specialization info missing?");
9249
9250 // Note: do not overwrite location info if previous template
9251 // specialization kind was explicit.
9253 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9254 Specialization->setLocation(FD->getLocation());
9255 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9256 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9257 // function can differ from the template declaration with respect to
9258 // the constexpr specifier.
9259 // FIXME: We need an update record for this AST mutation.
9260 // FIXME: What if there are multiple such prior declarations (for instance,
9261 // from different modules)?
9262 Specialization->setConstexprKind(FD->getConstexprKind());
9263 }
9264
9265 // FIXME: Check if the prior specialization has a point of instantiation.
9266 // If so, we have run afoul of .
9267
9268 // If this is a friend declaration, then we're not really declaring
9269 // an explicit specialization.
9270 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9271
9272 // Check the scope of this explicit specialization.
9273 if (!isFriend &&
9275 Specialization->getPrimaryTemplate(),
9277 false))
9278 return true;
9279
9280 // C++ [temp.expl.spec]p6:
9281 // If a template, a member template or the member of a class template is
9282 // explicitly specialized then that specialization shall be declared
9283 // before the first use of that specialization that would cause an implicit
9284 // instantiation to take place, in every translation unit in which such a
9285 // use occurs; no diagnostic is required.
9286 bool HasNoEffect = false;
9287 if (!isFriend &&
9292 SpecInfo->getPointOfInstantiation(),
9293 HasNoEffect))
9294 return true;
9295
9296 // Mark the prior declaration as an explicit specialization, so that later
9297 // clients know that this is an explicit specialization.
9298 if (!isFriend) {
9299 // Since explicit specializations do not inherit '=delete' from their
9300 // primary function template - check if the 'specialization' that was
9301 // implicitly generated (during template argument deduction for partial
9302 // ordering) from the most specialized of all the function templates that
9303 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9304 // first check that it was implicitly generated during template argument
9305 // deduction by making sure it wasn't referenced, and then reset the deleted
9306 // flag to not-deleted, so that we can inherit that information from 'FD'.
9307 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9308 !Specialization->getCanonicalDecl()->isReferenced()) {
9309 // FIXME: This assert will not hold in the presence of modules.
9310 assert(
9311 Specialization->getCanonicalDecl() == Specialization &&
9312 "This must be the only existing declaration of this specialization");
9313 // FIXME: We need an update record for this AST mutation.
9314 Specialization->setDeletedAsWritten(false);
9315 }
9316 // FIXME: We need an update record for this AST mutation.
9319 }
9320
9321 // Turn the given function declaration into a function template
9322 // specialization, with the template arguments from the previous
9323 // specialization.
9324 // Take copies of (semantic and syntactic) template argument lists.
9326 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9327 FD->setFunctionTemplateSpecialization(
9328 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9330 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9331
9332 // A function template specialization inherits the target attributes
9333 // of its template. (We require the attributes explicitly in the
9334 // code to match, but a template may have implicit attributes by
9335 // virtue e.g. of being constexpr, and it passes these implicit
9336 // attributes on to its specializations.)
9337 if (LangOpts.CUDA)
9338 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9339
9340 // The "previous declaration" for this function template specialization is
9341 // the prior function template specialization.
9342 Previous.clear();
9343 Previous.addDecl(Specialization);
9344 return false;
9345}
9346
9347bool
9349 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9350 "Only for non-template members");
9351
9352 // Try to find the member we are instantiating.
9353 NamedDecl *FoundInstantiation = nullptr;
9354 NamedDecl *Instantiation = nullptr;
9355 NamedDecl *InstantiatedFrom = nullptr;
9356 MemberSpecializationInfo *MSInfo = nullptr;
9357
9358 if (Previous.empty()) {
9359 // Nowhere to look anyway.
9360 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9361 UnresolvedSet<8> Candidates;
9362 for (NamedDecl *Candidate : Previous) {
9363 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9364 // Ignore any candidates that aren't member functions.
9365 if (!Method)
9366 continue;
9367
9368 QualType Adjusted = Function->getType();
9369 if (!hasExplicitCallingConv(Adjusted))
9370 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9371 // Ignore any candidates with the wrong type.
9372 // This doesn't handle deduced return types, but both function
9373 // declarations should be undeduced at this point.
9374 // FIXME: The exception specification should probably be ignored when
9375 // comparing the types.
9376 if (!Context.hasSameType(Adjusted, Method->getType()))
9377 continue;
9378
9379 // Ignore any candidates with unsatisfied constraints.
9380 if (ConstraintSatisfaction Satisfaction;
9381 Method->getTrailingRequiresClause() &&
9382 (CheckFunctionConstraints(Method, Satisfaction,
9383 /*UsageLoc=*/Member->getLocation(),
9384 /*ForOverloadResolution=*/true) ||
9385 !Satisfaction.IsSatisfied))
9386 continue;
9387
9388 Candidates.addDecl(Candidate);
9389 }
9390
9391 // If we have no viable candidates left after filtering, we are done.
9392 if (Candidates.empty())
9393 return false;
9394
9395 // Find the function that is more constrained than every other function it
9396 // has been compared to.
9397 UnresolvedSetIterator Best = Candidates.begin();
9398 CXXMethodDecl *BestMethod = nullptr;
9399 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9400 I != E; ++I) {
9401 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9402 if (I == Best ||
9403 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9404 Best = I;
9405 BestMethod = Method;
9406 }
9407 }
9408
9409 FoundInstantiation = *Best;
9410 Instantiation = BestMethod;
9411 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9412 MSInfo = BestMethod->getMemberSpecializationInfo();
9413
9414 // Make sure the best candidate is more constrained than all of the others.
9415 bool Ambiguous = false;
9416 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9417 I != E; ++I) {
9418 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9419 if (I != Best &&
9420 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9421 Ambiguous = true;
9422 break;
9423 }
9424 }
9425
9426 if (Ambiguous) {
9427 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9428 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9429 for (NamedDecl *Candidate : Candidates) {
9430 Candidate = Candidate->getUnderlyingDecl();
9431 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9432 << Candidate;
9433 }
9434 return true;
9435 }
9436 } else if (isa<VarDecl>(Member)) {
9437 VarDecl *PrevVar;
9438 if (Previous.isSingleResult() &&
9439 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9440 if (PrevVar->isStaticDataMember()) {
9441 FoundInstantiation = Previous.getRepresentativeDecl();
9442 Instantiation = PrevVar;
9443 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9444 MSInfo = PrevVar->getMemberSpecializationInfo();
9445 }
9446 } else if (isa<RecordDecl>(Member)) {
9447 CXXRecordDecl *PrevRecord;
9448 if (Previous.isSingleResult() &&
9449 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9450 FoundInstantiation = Previous.getRepresentativeDecl();
9451 Instantiation = PrevRecord;
9452 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9453 MSInfo = PrevRecord->getMemberSpecializationInfo();
9454 }
9455 } else if (isa<EnumDecl>(Member)) {
9456 EnumDecl *PrevEnum;
9457 if (Previous.isSingleResult() &&
9458 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9459 FoundInstantiation = Previous.getRepresentativeDecl();
9460 Instantiation = PrevEnum;
9461 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9462 MSInfo = PrevEnum->getMemberSpecializationInfo();
9463 }
9464 }
9465
9466 if (!Instantiation) {
9467 // There is no previous declaration that matches. Since member
9468 // specializations are always out-of-line, the caller will complain about
9469 // this mismatch later.
9470 return false;
9471 }
9472
9473 // A member specialization in a friend declaration isn't really declaring
9474 // an explicit specialization, just identifying a specific (possibly implicit)
9475 // specialization. Don't change the template specialization kind.
9476 //
9477 // FIXME: Is this really valid? Other compilers reject.
9478 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9479 // Preserve instantiation information.
9480 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9481 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9482 cast<CXXMethodDecl>(InstantiatedFrom),
9483 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9484 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9485 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9486 cast<CXXRecordDecl>(InstantiatedFrom),
9487 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9488 }
9489
9490 Previous.clear();
9491 Previous.addDecl(FoundInstantiation);
9492 return false;
9493 }
9494
9495 // Make sure that this is a specialization of a member.
9496 if (!InstantiatedFrom) {
9497 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9498 << Member;
9499 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9500 return true;
9501 }
9502
9503 // C++ [temp.expl.spec]p6:
9504 // If a template, a member template or the member of a class template is
9505 // explicitly specialized then that specialization shall be declared
9506 // before the first use of that specialization that would cause an implicit
9507 // instantiation to take place, in every translation unit in which such a
9508 // use occurs; no diagnostic is required.
9509 assert(MSInfo && "Member specialization info missing?");
9510
9511 bool HasNoEffect = false;
9514 Instantiation,
9516 MSInfo->getPointOfInstantiation(),
9517 HasNoEffect))
9518 return true;
9519
9520 // Check the scope of this explicit specialization.
9522 InstantiatedFrom,
9523 Instantiation, Member->getLocation(),
9524 false))
9525 return true;
9526
9527 // Note that this member specialization is an "instantiation of" the
9528 // corresponding member of the original template.
9529 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9530 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9531 if (InstantiationFunction->getTemplateSpecializationKind() ==
9533 // Explicit specializations of member functions of class templates do not
9534 // inherit '=delete' from the member function they are specializing.
9535 if (InstantiationFunction->isDeleted()) {
9536 // FIXME: This assert will not hold in the presence of modules.
9537 assert(InstantiationFunction->getCanonicalDecl() ==
9538 InstantiationFunction);
9539 // FIXME: We need an update record for this AST mutation.
9540 InstantiationFunction->setDeletedAsWritten(false);
9541 }
9542 }
9543
9544 MemberFunction->setInstantiationOfMemberFunction(
9545 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9546 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9547 MemberVar->setInstantiationOfStaticDataMember(
9548 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9549 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9550 MemberClass->setInstantiationOfMemberClass(
9551 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9552 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9553 MemberEnum->setInstantiationOfMemberEnum(
9554 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9555 } else {
9556 llvm_unreachable("unknown member specialization kind");
9557 }
9558
9559 // Save the caller the trouble of having to figure out which declaration
9560 // this specialization matches.
9561 Previous.clear();
9562 Previous.addDecl(FoundInstantiation);
9563 return false;
9564}
9565
9566/// Complete the explicit specialization of a member of a class template by
9567/// updating the instantiated member to be marked as an explicit specialization.
9568///
9569/// \param OrigD The member declaration instantiated from the template.
9570/// \param Loc The location of the explicit specialization of the member.
9571template<typename DeclT>
9572static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9574 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9575 return;
9576
9577 // FIXME: Inform AST mutation listeners of this AST mutation.
9578 // FIXME: If there are multiple in-class declarations of the member (from
9579 // multiple modules, or a declaration and later definition of a member type),
9580 // should we update all of them?
9581 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9582 OrigD->setLocation(Loc);
9583}
9584
9587 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9588 if (Instantiation == Member)
9589 return;
9590
9591 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9592 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9593 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9594 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9595 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9596 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9597 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9598 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9599 else
9600 llvm_unreachable("unknown member specialization kind");
9601}
9602
9603/// Check the scope of an explicit instantiation.
9604///
9605/// \returns true if a serious error occurs, false otherwise.
9607 SourceLocation InstLoc,
9608 bool WasQualifiedName) {
9610 DeclContext *CurContext = S.CurContext->getRedeclContext();
9611
9612 if (CurContext->isRecord()) {
9613 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9614 << D;
9615 return true;
9616 }
9617
9618 // C++11 [temp.explicit]p3:
9619 // An explicit instantiation shall appear in an enclosing namespace of its
9620 // template. If the name declared in the explicit instantiation is an
9621 // unqualified name, the explicit instantiation shall appear in the
9622 // namespace where its template is declared or, if that namespace is inline
9623 // (7.3.1), any namespace from its enclosing namespace set.
9624 //
9625 // This is DR275, which we do not retroactively apply to C++98/03.
9626 if (WasQualifiedName) {
9627 if (CurContext->Encloses(OrigContext))
9628 return false;
9629 } else {
9630 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9631 return false;
9632 }
9633
9634 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9635 if (WasQualifiedName)
9636 S.Diag(InstLoc,
9637 S.getLangOpts().CPlusPlus11?
9638 diag::err_explicit_instantiation_out_of_scope :
9639 diag::warn_explicit_instantiation_out_of_scope_0x)
9640 << D << NS;
9641 else
9642 S.Diag(InstLoc,
9643 S.getLangOpts().CPlusPlus11?
9644 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9645 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9646 << D << NS;
9647 } else
9648 S.Diag(InstLoc,
9649 S.getLangOpts().CPlusPlus11?
9650 diag::err_explicit_instantiation_must_be_global :
9651 diag::warn_explicit_instantiation_must_be_global_0x)
9652 << D;
9653 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9654 return false;
9655}
9656
9657/// Common checks for whether an explicit instantiation of \p D is valid.
9659 SourceLocation InstLoc,
9660 bool WasQualifiedName,
9662 // C++ [temp.explicit]p13:
9663 // An explicit instantiation declaration shall not name a specialization of
9664 // a template with internal linkage.
9666 D->getFormalLinkage() == Linkage::Internal) {
9667 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9668 return true;
9669 }
9670
9671 // C++11 [temp.explicit]p3: [DR 275]
9672 // An explicit instantiation shall appear in an enclosing namespace of its
9673 // template.
9674 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9675 return true;
9676
9677 return false;
9678}
9679
9680/// Determine whether the given scope specifier has a template-id in it.
9682 if (!SS.isSet())
9683 return false;
9684
9685 // C++11 [temp.explicit]p3:
9686 // If the explicit instantiation is for a member function, a member class
9687 // or a static data member of a class template specialization, the name of
9688 // the class template specialization in the qualified-id for the member
9689 // name shall be a simple-template-id.
9690 //
9691 // C++98 has the same restriction, just worded differently.
9692 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9693 NNS = NNS->getPrefix())
9694 if (const Type *T = NNS->getAsType())
9695 if (isa<TemplateSpecializationType>(T))
9696 return true;
9697
9698 return false;
9699}
9700
9701/// Make a dllexport or dllimport attr on a class template specialization take
9702/// effect.
9705 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9706 assert(A && "dllExportImportClassTemplateSpecialization called "
9707 "on Def without dllexport or dllimport");
9708
9709 // We reject explicit instantiations in class scope, so there should
9710 // never be any delayed exported classes to worry about.
9711 assert(S.DelayedDllExportClasses.empty() &&
9712 "delayed exports present at explicit instantiation");
9714
9715 // Propagate attribute to base class templates.
9716 for (auto &B : Def->bases()) {
9717 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9718 B.getType()->getAsCXXRecordDecl()))
9720 }
9721
9723}
9724
9726 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9727 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9728 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9729 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9730 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9731 // Find the class template we're specializing
9732 TemplateName Name = TemplateD.get();
9733 TemplateDecl *TD = Name.getAsTemplateDecl();
9734 // Check that the specialization uses the same tag kind as the
9735 // original template.
9737 assert(Kind != TagTypeKind::Enum &&
9738 "Invalid enum tag in class template explicit instantiation!");
9739
9740 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9741
9742 if (!ClassTemplate) {
9743 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9744 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9745 << TD << NTK << llvm::to_underlying(Kind);
9746 Diag(TD->getLocation(), diag::note_previous_use);
9747 return true;
9748 }
9749
9750 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9751 Kind, /*isDefinition*/false, KWLoc,
9752 ClassTemplate->getIdentifier())) {
9753 Diag(KWLoc, diag::err_use_with_wrong_tag)
9754 << ClassTemplate
9756 ClassTemplate->getTemplatedDecl()->getKindName());
9757 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9758 diag::note_previous_use);
9759 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9760 }
9761
9762 // C++0x [temp.explicit]p2:
9763 // There are two forms of explicit instantiation: an explicit instantiation
9764 // definition and an explicit instantiation declaration. An explicit
9765 // instantiation declaration begins with the extern keyword. [...]
9766 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9769
9771 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9772 // Check for dllexport class template instantiation declarations,
9773 // except for MinGW mode.
9774 for (const ParsedAttr &AL : Attr) {
9775 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9776 Diag(ExternLoc,
9777 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9778 Diag(AL.getLoc(), diag::note_attribute);
9779 break;
9780 }
9781 }
9782
9783 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9784 Diag(ExternLoc,
9785 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9786 Diag(A->getLocation(), diag::note_attribute);
9787 }
9788 }
9789
9790 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9791 // instantiation declarations for most purposes.
9792 bool DLLImportExplicitInstantiationDef = false;
9795 // Check for dllimport class template instantiation definitions.
9796 bool DLLImport =
9797 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9798 for (const ParsedAttr &AL : Attr) {
9799 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9800 DLLImport = true;
9801 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9802 // dllexport trumps dllimport here.
9803 DLLImport = false;
9804 break;
9805 }
9806 }
9807 if (DLLImport) {
9809 DLLImportExplicitInstantiationDef = true;
9810 }
9811 }
9812
9813 // Translate the parser's template argument list in our AST format.
9814 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9815 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9816
9817 // Check that the template argument list is well-formed for this
9818 // template.
9819 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9820 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9821 /*DefaultArgs=*/{}, false, SugaredConverted,
9822 CanonicalConverted,
9823 /*UpdateArgsWithConversions=*/true))
9824 return true;
9825
9826 // Find the class template specialization declaration that
9827 // corresponds to these arguments.
9828 void *InsertPos = nullptr;
9830 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9831
9832 TemplateSpecializationKind PrevDecl_TSK
9833 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9834
9835 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9836 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9837 // Check for dllexport class template instantiation definitions in MinGW
9838 // mode, if a previous declaration of the instantiation was seen.
9839 for (const ParsedAttr &AL : Attr) {
9840 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9841 Diag(AL.getLoc(),
9842 diag::warn_attribute_dllexport_explicit_instantiation_def);
9843 break;
9844 }
9845 }
9846 }
9847
9848 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9849 SS.isSet(), TSK))
9850 return true;
9851
9853
9854 bool HasNoEffect = false;
9855 if (PrevDecl) {
9856 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9857 PrevDecl, PrevDecl_TSK,
9858 PrevDecl->getPointOfInstantiation(),
9859 HasNoEffect))
9860 return PrevDecl;
9861
9862 // Even though HasNoEffect == true means that this explicit instantiation
9863 // has no effect on semantics, we go on to put its syntax in the AST.
9864
9865 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9866 PrevDecl_TSK == TSK_Undeclared) {
9867 // Since the only prior class template specialization with these
9868 // arguments was referenced but not declared, reuse that
9869 // declaration node as our own, updating the source location
9870 // for the template name to reflect our new declaration.
9871 // (Other source locations will be updated later.)
9872 Specialization = PrevDecl;
9873 Specialization->setLocation(TemplateNameLoc);
9874 PrevDecl = nullptr;
9875 }
9876
9877 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9878 DLLImportExplicitInstantiationDef) {
9879 // The new specialization might add a dllimport attribute.
9880 HasNoEffect = false;
9881 }
9882 }
9883
9884 if (!Specialization) {
9885 // Create a new class template specialization declaration node for
9886 // this explicit specialization.
9888 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9889 ClassTemplate, CanonicalConverted, PrevDecl);
9891
9892 // A MSInheritanceAttr attached to the previous declaration must be
9893 // propagated to the new node prior to instantiation.
9894 if (PrevDecl) {
9895 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9896 auto *Clone = A->clone(getASTContext());
9897 Clone->setInherited(true);
9898 Specialization->addAttr(Clone);
9900 }
9901 }
9902
9903 if (!HasNoEffect && !PrevDecl) {
9904 // Insert the new specialization.
9905 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9906 }
9907 }
9908
9909 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9910
9911 // Set source locations for keywords.
9912 Specialization->setExternKeywordLoc(ExternLoc);
9913 Specialization->setTemplateKeywordLoc(TemplateLoc);
9914 Specialization->setBraceRange(SourceRange());
9915
9916 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9919
9920 // Add the explicit instantiation into its lexical context. However,
9921 // since explicit instantiations are never found by name lookup, we
9922 // just put it into the declaration context directly.
9923 Specialization->setLexicalDeclContext(CurContext);
9925
9926 // Syntax is now OK, so return if it has no other effect on semantics.
9927 if (HasNoEffect) {
9928 // Set the template specialization kind.
9929 Specialization->setTemplateSpecializationKind(TSK);
9930 return Specialization;
9931 }
9932
9933 // C++ [temp.explicit]p3:
9934 // A definition of a class template or class member template
9935 // shall be in scope at the point of the explicit instantiation of
9936 // the class template or class member template.
9937 //
9938 // This check comes when we actually try to perform the
9939 // instantiation.
9941 = cast_or_null<ClassTemplateSpecializationDecl>(
9942 Specialization->getDefinition());
9943 if (!Def)
9945 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9946 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9947 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9948 }
9949
9950 // Instantiate the members of this class template specialization.
9951 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9952 Specialization->getDefinition());
9953 if (Def) {
9955 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9956 // TSK_ExplicitInstantiationDefinition
9957 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9959 DLLImportExplicitInstantiationDef)) {
9960 // FIXME: Need to notify the ASTMutationListener that we did this.
9962
9963 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9965 // An explicit instantiation definition can add a dll attribute to a
9966 // template with a previous instantiation declaration. MinGW doesn't
9967 // allow this.
9968 auto *A = cast<InheritableAttr>(
9970 A->setInherited(true);
9971 Def->addAttr(A);
9973 }
9974 }
9975
9976 // Fix a TSK_ImplicitInstantiation followed by a
9977 // TSK_ExplicitInstantiationDefinition
9978 bool NewlyDLLExported =
9979 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9980 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9982 // An explicit instantiation definition can add a dll attribute to a
9983 // template with a previous implicit instantiation. MinGW doesn't allow
9984 // this. We limit clang to only adding dllexport, to avoid potentially
9985 // strange codegen behavior. For example, if we extend this conditional
9986 // to dllimport, and we have a source file calling a method on an
9987 // implicitly instantiated template class instance and then declaring a
9988 // dllimport explicit instantiation definition for the same template
9989 // class, the codegen for the method call will not respect the dllimport,
9990 // while it will with cl. The Def will already have the DLL attribute,
9991 // since the Def and Specialization will be the same in the case of
9992 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9993 // attribute to the Specialization; we just need to make it take effect.
9994 assert(Def == Specialization &&
9995 "Def and Specialization should match for implicit instantiation");
9997 }
9998
9999 // In MinGW mode, export the template instantiation if the declaration
10000 // was marked dllexport.
10001 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10002 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10003 PrevDecl->hasAttr<DLLExportAttr>()) {
10005 }
10006
10007 // Set the template specialization kind. Make sure it is set before
10008 // instantiating the members which will trigger ASTConsumer callbacks.
10009 Specialization->setTemplateSpecializationKind(TSK);
10010 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10011 } else {
10012
10013 // Set the template specialization kind.
10014 Specialization->setTemplateSpecializationKind(TSK);
10015 }
10016
10017 return Specialization;
10018}
10019
10022 SourceLocation TemplateLoc, unsigned TagSpec,
10023 SourceLocation KWLoc, CXXScopeSpec &SS,
10024 IdentifierInfo *Name, SourceLocation NameLoc,
10025 const ParsedAttributesView &Attr) {
10026
10027 bool Owned = false;
10028 bool IsDependent = false;
10029 Decl *TagD =
10030 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10031 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10032 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10033 false, TypeResult(), /*IsTypeSpecifier*/ false,
10034 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10035 .get();
10036 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10037
10038 if (!TagD)
10039 return true;
10040
10041 TagDecl *Tag = cast<TagDecl>(TagD);
10042 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10043
10044 if (Tag->isInvalidDecl())
10045 return true;
10046
10047 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10049 if (!Pattern) {
10050 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10052 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10053 return true;
10054 }
10055
10056 // C++0x [temp.explicit]p2:
10057 // If the explicit instantiation is for a class or member class, the
10058 // elaborated-type-specifier in the declaration shall include a
10059 // simple-template-id.
10060 //
10061 // C++98 has the same restriction, just worded differently.
10063 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10064 << Record << SS.getRange();
10065
10066 // C++0x [temp.explicit]p2:
10067 // There are two forms of explicit instantiation: an explicit instantiation
10068 // definition and an explicit instantiation declaration. An explicit
10069 // instantiation declaration begins with the extern keyword. [...]
10073
10074 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10075
10076 // Verify that it is okay to explicitly instantiate here.
10077 CXXRecordDecl *PrevDecl
10078 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10079 if (!PrevDecl && Record->getDefinition())
10080 PrevDecl = Record;
10081 if (PrevDecl) {
10083 bool HasNoEffect = false;
10084 assert(MSInfo && "No member specialization information?");
10085 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10086 PrevDecl,
10088 MSInfo->getPointOfInstantiation(),
10089 HasNoEffect))
10090 return true;
10091 if (HasNoEffect)
10092 return TagD;
10093 }
10094
10095 CXXRecordDecl *RecordDef
10096 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10097 if (!RecordDef) {
10098 // C++ [temp.explicit]p3:
10099 // A definition of a member class of a class template shall be in scope
10100 // at the point of an explicit instantiation of the member class.
10101 CXXRecordDecl *Def
10102 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10103 if (!Def) {
10104 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10105 << 0 << Record->getDeclName() << Record->getDeclContext();
10106 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10107 << Pattern;
10108 return true;
10109 } else {
10110 if (InstantiateClass(NameLoc, Record, Def,
10112 TSK))
10113 return true;
10114
10115 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10116 if (!RecordDef)
10117 return true;
10118 }
10119 }
10120
10121 // Instantiate all of the members of the class.
10122 InstantiateClassMembers(NameLoc, RecordDef,
10124
10126 MarkVTableUsed(NameLoc, RecordDef, true);
10127
10128 // FIXME: We don't have any representation for explicit instantiations of
10129 // member classes. Such a representation is not needed for compilation, but it
10130 // should be available for clients that want to see all of the declarations in
10131 // the source code.
10132 return TagD;
10133}
10134
10136 SourceLocation ExternLoc,
10137 SourceLocation TemplateLoc,
10138 Declarator &D) {
10139 // Explicit instantiations always require a name.
10140 // TODO: check if/when DNInfo should replace Name.
10142 DeclarationName Name = NameInfo.getName();
10143 if (!Name) {
10144 if (!D.isInvalidType())
10145 Diag(D.getDeclSpec().getBeginLoc(),
10146 diag::err_explicit_instantiation_requires_name)
10147 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10148
10149 return true;
10150 }
10151
10152 // Get the innermost enclosing declaration scope.
10153 S = S->getDeclParent();
10154
10155 // Determine the type of the declaration.
10157 QualType R = T->getType();
10158 if (R.isNull())
10159 return true;
10160
10161 // C++ [dcl.stc]p1:
10162 // A storage-class-specifier shall not be specified in [...] an explicit
10163 // instantiation (14.7.2) directive.
10164 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10165 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10166 << Name;
10167 return true;
10168 } else if (D.getDeclSpec().getStorageClassSpec()
10170 // Complain about then remove the storage class specifier.
10171 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10172 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10173
10174 D.getMutableDeclSpec().ClearStorageClassSpecs();
10175 }
10176
10177 // C++0x [temp.explicit]p1:
10178 // [...] An explicit instantiation of a function template shall not use the
10179 // inline or constexpr specifiers.
10180 // Presumably, this also applies to member functions of class templates as
10181 // well.
10182 if (D.getDeclSpec().isInlineSpecified())
10183 Diag(D.getDeclSpec().getInlineSpecLoc(),
10185 diag::err_explicit_instantiation_inline :
10186 diag::warn_explicit_instantiation_inline_0x)
10187 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10188 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10189 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10190 // not already specified.
10191 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10192 diag::err_explicit_instantiation_constexpr);
10193
10194 // A deduction guide is not on the list of entities that can be explicitly
10195 // instantiated.
10196 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10197 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10198 << /*explicit instantiation*/ 0;
10199 return true;
10200 }
10201
10202 // C++0x [temp.explicit]p2:
10203 // There are two forms of explicit instantiation: an explicit instantiation
10204 // definition and an explicit instantiation declaration. An explicit
10205 // instantiation declaration begins with the extern keyword. [...]
10209
10210 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10211 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10212 /*ObjectType=*/QualType());
10213
10214 if (!R->isFunctionType()) {
10215 // C++ [temp.explicit]p1:
10216 // A [...] static data member of a class template can be explicitly
10217 // instantiated from the member definition associated with its class
10218 // template.
10219 // C++1y [temp.explicit]p1:
10220 // A [...] variable [...] template specialization can be explicitly
10221 // instantiated from its template.
10222 if (Previous.isAmbiguous())
10223 return true;
10224
10225 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10226 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10227
10228 if (!PrevTemplate) {
10229 if (!Prev || !Prev->isStaticDataMember()) {
10230 // We expect to see a static data member here.
10231 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10232 << Name;
10233 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10234 P != PEnd; ++P)
10235 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10236 return true;
10237 }
10238
10240 // FIXME: Check for explicit specialization?
10241 Diag(D.getIdentifierLoc(),
10242 diag::err_explicit_instantiation_data_member_not_instantiated)
10243 << Prev;
10244 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10245 // FIXME: Can we provide a note showing where this was declared?
10246 return true;
10247 }
10248 } else {
10249 // Explicitly instantiate a variable template.
10250
10251 // C++1y [dcl.spec.auto]p6:
10252 // ... A program that uses auto or decltype(auto) in a context not
10253 // explicitly allowed in this section is ill-formed.
10254 //
10255 // This includes auto-typed variable template instantiations.
10256 if (R->isUndeducedType()) {
10257 Diag(T->getTypeLoc().getBeginLoc(),
10258 diag::err_auto_not_allowed_var_inst);
10259 return true;
10260 }
10261
10262 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10263 // C++1y [temp.explicit]p3:
10264 // If the explicit instantiation is for a variable, the unqualified-id
10265 // in the declaration shall be a template-id.
10266 Diag(D.getIdentifierLoc(),
10267 diag::err_explicit_instantiation_without_template_id)
10268 << PrevTemplate;
10269 Diag(PrevTemplate->getLocation(),
10270 diag::note_explicit_instantiation_here);
10271 return true;
10272 }
10273
10274 // Translate the parser's template argument list into our AST format.
10275 TemplateArgumentListInfo TemplateArgs =
10276 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10277
10278 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10279 D.getIdentifierLoc(), TemplateArgs);
10280 if (Res.isInvalid())
10281 return true;
10282
10283 if (!Res.isUsable()) {
10284 // We somehow specified dependent template arguments in an explicit
10285 // instantiation. This should probably only happen during error
10286 // recovery.
10287 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10288 return true;
10289 }
10290
10291 // Ignore access control bits, we don't need them for redeclaration
10292 // checking.
10293 Prev = cast<VarDecl>(Res.get());
10294 }
10295
10296 // C++0x [temp.explicit]p2:
10297 // If the explicit instantiation is for a member function, a member class
10298 // or a static data member of a class template specialization, the name of
10299 // the class template specialization in the qualified-id for the member
10300 // name shall be a simple-template-id.
10301 //
10302 // C++98 has the same restriction, just worded differently.
10303 //
10304 // This does not apply to variable template specializations, where the
10305 // template-id is in the unqualified-id instead.
10306 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10307 Diag(D.getIdentifierLoc(),
10308 diag::ext_explicit_instantiation_without_qualified_id)
10309 << Prev << D.getCXXScopeSpec().getRange();
10310
10311 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10312
10313 // Verify that it is okay to explicitly instantiate here.
10316 bool HasNoEffect = false;
10317 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10318 PrevTSK, POI, HasNoEffect))
10319 return true;
10320
10321 if (!HasNoEffect) {
10322 // Instantiate static data member or variable template.
10323 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10324 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10325 VTSD->setExternKeywordLoc(ExternLoc);
10326 VTSD->setTemplateKeywordLoc(TemplateLoc);
10327 }
10328
10329 // Merge attributes.
10330 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10331 if (PrevTemplate)
10332 ProcessAPINotes(Prev);
10333
10335 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10336 }
10337
10338 // Check the new variable specialization against the parsed input.
10339 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10340 Diag(T->getTypeLoc().getBeginLoc(),
10341 diag::err_invalid_var_template_spec_type)
10342 << 0 << PrevTemplate << R << Prev->getType();
10343 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10344 << 2 << PrevTemplate->getDeclName();
10345 return true;
10346 }
10347
10348 // FIXME: Create an ExplicitInstantiation node?
10349 return (Decl*) nullptr;
10350 }
10351
10352 // If the declarator is a template-id, translate the parser's template
10353 // argument list into our AST format.
10354 bool HasExplicitTemplateArgs = false;
10355 TemplateArgumentListInfo TemplateArgs;
10356 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10357 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10358 HasExplicitTemplateArgs = true;
10359 }
10360
10361 // C++ [temp.explicit]p1:
10362 // A [...] function [...] can be explicitly instantiated from its template.
10363 // A member function [...] of a class template can be explicitly
10364 // instantiated from the member definition associated with its class
10365 // template.
10366 UnresolvedSet<8> TemplateMatches;
10367 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10369 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10370 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10371 P != PEnd; ++P) {
10372 NamedDecl *Prev = *P;
10373 if (!HasExplicitTemplateArgs) {
10374 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10375 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10376 /*AdjustExceptionSpec*/true);
10377 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10378 if (Method->getPrimaryTemplate()) {
10379 TemplateMatches.addDecl(Method, P.getAccess());
10380 } else {
10381 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10382 C.FoundDecl = P.getPair();
10383 C.Function = Method;
10384 C.Viable = true;
10386 if (Method->getTrailingRequiresClause() &&
10387 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10388 /*ForOverloadResolution=*/true) ||
10389 !S.IsSatisfied)) {
10390 C.Viable = false;
10392 }
10393 }
10394 }
10395 }
10396 }
10397
10398 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10399 if (!FunTmpl)
10400 continue;
10401
10402 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10403 FunctionDecl *Specialization = nullptr;
10405 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10406 Specialization, Info);
10408 // Keep track of almost-matches.
10409 FailedTemplateCandidates.addCandidate().set(
10410 P.getPair(), FunTmpl->getTemplatedDecl(),
10411 MakeDeductionFailureInfo(Context, TDK, Info));
10412 (void)TDK;
10413 continue;
10414 }
10415
10416 // Target attributes are part of the cuda function signature, so
10417 // the cuda target of the instantiated function must match that of its
10418 // template. Given that C++ template deduction does not take
10419 // target attributes into account, we reject candidates here that
10420 // have a different target.
10421 if (LangOpts.CUDA &&
10423 /* IgnoreImplicitHDAttr = */ true) !=
10424 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10425 FailedTemplateCandidates.addCandidate().set(
10426 P.getPair(), FunTmpl->getTemplatedDecl(),
10429 continue;
10430 }
10431
10432 TemplateMatches.addDecl(Specialization, P.getAccess());
10433 }
10434
10435 FunctionDecl *Specialization = nullptr;
10436 if (!NonTemplateMatches.empty()) {
10437 unsigned Msg = 0;
10438 OverloadCandidateDisplayKind DisplayKind;
10440 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10441 Best)) {
10442 case OR_Success:
10443 case OR_Deleted:
10444 Specialization = cast<FunctionDecl>(Best->Function);
10445 break;
10446 case OR_Ambiguous:
10447 Msg = diag::err_explicit_instantiation_ambiguous;
10448 DisplayKind = OCD_AmbiguousCandidates;
10449 break;
10451 Msg = diag::err_explicit_instantiation_no_candidate;
10452 DisplayKind = OCD_AllCandidates;
10453 break;
10454 }
10455 if (Msg) {
10456 PartialDiagnostic Diag = PDiag(Msg) << Name;
10457 NonTemplateMatches.NoteCandidates(
10458 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10459 {});
10460 return true;
10461 }
10462 }
10463
10464 if (!Specialization) {
10465 // Find the most specialized function template specialization.
10467 TemplateMatches.begin(), TemplateMatches.end(),
10468 FailedTemplateCandidates, D.getIdentifierLoc(),
10469 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10470 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10471 PDiag(diag::note_explicit_instantiation_candidate));
10472
10473 if (Result == TemplateMatches.end())
10474 return true;
10475
10476 // Ignore access control bits, we don't need them for redeclaration checking.
10477 Specialization = cast<FunctionDecl>(*Result);
10478 }
10479
10480 // C++11 [except.spec]p4
10481 // In an explicit instantiation an exception-specification may be specified,
10482 // but is not required.
10483 // If an exception-specification is specified in an explicit instantiation
10484 // directive, it shall be compatible with the exception-specifications of
10485 // other declarations of that function.
10486 if (auto *FPT = R->getAs<FunctionProtoType>())
10487 if (FPT->hasExceptionSpec()) {
10488 unsigned DiagID =
10489 diag::err_mismatched_exception_spec_explicit_instantiation;
10490 if (getLangOpts().MicrosoftExt)
10491 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10493 PDiag(DiagID) << Specialization->getType(),
10494 PDiag(diag::note_explicit_instantiation_here),
10495 Specialization->getType()->getAs<FunctionProtoType>(),
10496 Specialization->getLocation(), FPT, D.getBeginLoc());
10497 // In Microsoft mode, mismatching exception specifications just cause a
10498 // warning.
10499 if (!getLangOpts().MicrosoftExt && Result)
10500 return true;
10501 }
10502
10503 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10504 Diag(D.getIdentifierLoc(),
10505 diag::err_explicit_instantiation_member_function_not_instantiated)
10507 << (Specialization->getTemplateSpecializationKind() ==
10509 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10510 return true;
10511 }
10512
10513 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10514 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10515 PrevDecl = Specialization;
10516
10517 if (PrevDecl) {
10518 bool HasNoEffect = false;
10519 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10520 PrevDecl,
10522 PrevDecl->getPointOfInstantiation(),
10523 HasNoEffect))
10524 return true;
10525
10526 // FIXME: We may still want to build some representation of this
10527 // explicit specialization.
10528 if (HasNoEffect)
10529 return (Decl*) nullptr;
10530 }
10531
10532 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10533 // functions
10534 // valarray<size_t>::valarray(size_t) and
10535 // valarray<size_t>::~valarray()
10536 // that it declared to have internal linkage with the internal_linkage
10537 // attribute. Ignore the explicit instantiation declaration in this case.
10538 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10540 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10541 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10542 RD->isInStdNamespace())
10543 return (Decl*) nullptr;
10544 }
10545
10546 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10548
10549 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10550 // instantiation declarations.
10552 Specialization->hasAttr<DLLImportAttr>() &&
10555
10556 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10557
10558 if (Specialization->isDefined()) {
10559 // Let the ASTConsumer know that this function has been explicitly
10560 // instantiated now, and its linkage might have changed.
10562 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10563 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10564
10565 // C++0x [temp.explicit]p2:
10566 // If the explicit instantiation is for a member function, a member class
10567 // or a static data member of a class template specialization, the name of
10568 // the class template specialization in the qualified-id for the member
10569 // name shall be a simple-template-id.
10570 //
10571 // C++98 has the same restriction, just worded differently.
10572 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10573 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10574 D.getCXXScopeSpec().isSet() &&
10575 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10576 Diag(D.getIdentifierLoc(),
10577 diag::ext_explicit_instantiation_without_qualified_id)
10578 << Specialization << D.getCXXScopeSpec().getRange();
10579
10581 *this,
10582 FunTmpl ? (NamedDecl *)FunTmpl
10583 : Specialization->getInstantiatedFromMemberFunction(),
10584 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10585
10586 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10587 return (Decl*) nullptr;
10588}
10589
10591 const CXXScopeSpec &SS,
10592 const IdentifierInfo *Name,
10593 SourceLocation TagLoc,
10594 SourceLocation NameLoc) {
10595 // This has to hold, because SS is expected to be defined.
10596 assert(Name && "Expected a name in a dependent tag");
10597
10598 NestedNameSpecifier *NNS = SS.getScopeRep();
10599 if (!NNS)
10600 return true;
10601
10603
10604 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10605 Diag(NameLoc, diag::err_dependent_tag_decl)
10606 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10607 << SS.getRange();
10608 return true;
10609 }
10610
10611 // Create the resulting type.
10613 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10614
10615 // Create type-source location information for this type.
10616 TypeLocBuilder TLB;
10618 TL.setElaboratedKeywordLoc(TagLoc);
10620 TL.setNameLoc(NameLoc);
10622}
10623
10625 const CXXScopeSpec &SS,
10626 const IdentifierInfo &II,
10627 SourceLocation IdLoc,
10628 ImplicitTypenameContext IsImplicitTypename) {
10629 if (SS.isInvalid())
10630 return true;
10631
10632 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10633 Diag(TypenameLoc,
10635 diag::warn_cxx98_compat_typename_outside_of_template :
10636 diag::ext_typename_outside_of_template)
10637 << FixItHint::CreateRemoval(TypenameLoc);
10638
10640 TypeSourceInfo *TSI = nullptr;
10641 QualType T =
10642 CheckTypenameType((TypenameLoc.isValid() ||
10643 IsImplicitTypename == ImplicitTypenameContext::Yes)
10646 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10647 /*DeducedTSTContext=*/true);
10648 if (T.isNull())
10649 return true;
10650 return CreateParsedType(T, TSI);
10651}
10652
10655 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10656 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10657 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10658 ASTTemplateArgsPtr TemplateArgsIn,
10659 SourceLocation RAngleLoc) {
10660 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10661 Diag(TypenameLoc,
10663 diag::warn_cxx98_compat_typename_outside_of_template :
10664 diag::ext_typename_outside_of_template)
10665 << FixItHint::CreateRemoval(TypenameLoc);
10666
10667 // Strangely, non-type results are not ignored by this lookup, so the
10668 // program is ill-formed if it finds an injected-class-name.
10669 if (TypenameLoc.isValid()) {
10670 auto *LookupRD =
10671 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10672 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10673 Diag(TemplateIILoc,
10674 diag::ext_out_of_line_qualified_id_type_names_constructor)
10675 << TemplateII << 0 /*injected-class-name used as template name*/
10676 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10677 }
10678 }
10679
10680 // Translate the parser's template argument list in our AST format.
10681 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10682 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10683
10684 TemplateName Template = TemplateIn.get();
10685 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10686 // Construct a dependent template specialization type.
10687 assert(DTN && "dependent template has non-dependent name?");
10688 assert(DTN->getQualifier() == SS.getScopeRep());
10689
10690 if (!DTN->isIdentifier()) {
10691 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10692 NoteAllFoundTemplates(Template);
10693 return true;
10694 }
10695
10697 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10698 DTN->getIdentifier(), TemplateArgs.arguments());
10699
10700 // Create source-location information for this type.
10701 TypeLocBuilder Builder;
10704 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10706 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10707 SpecTL.setTemplateNameLoc(TemplateIILoc);
10708 SpecTL.setLAngleLoc(LAngleLoc);
10709 SpecTL.setRAngleLoc(RAngleLoc);
10710 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10711 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10712 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10713 }
10714
10715 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10716 if (T.isNull())
10717 return true;
10718
10719 // Provide source-location information for the template specialization type.
10720 TypeLocBuilder Builder;
10722 = Builder.push<TemplateSpecializationTypeLoc>(T);
10723 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10724 SpecTL.setTemplateNameLoc(TemplateIILoc);
10725 SpecTL.setLAngleLoc(LAngleLoc);
10726 SpecTL.setRAngleLoc(RAngleLoc);
10727 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10728 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10729
10731 SS.getScopeRep(), T);
10732 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10733 TL.setElaboratedKeywordLoc(TypenameLoc);
10735
10736 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10737 return CreateParsedType(T, TSI);
10738}
10739
10740/// Determine whether this failed name lookup should be treated as being
10741/// disabled by a usage of std::enable_if.
10743 SourceRange &CondRange, Expr *&Cond) {
10744 // We must be looking for a ::type...
10745 if (!II.isStr("type"))
10746 return false;
10747
10748 // ... within an explicitly-written template specialization...
10749 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10750 return false;
10751 TypeLoc EnableIfTy = NNS.getTypeLoc();
10752 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10754 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10755 return false;
10756 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10757
10758 // ... which names a complete class template declaration...
10759 const TemplateDecl *EnableIfDecl =
10760 EnableIfTST->getTemplateName().getAsTemplateDecl();
10761 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10762 return false;
10763
10764 // ... called "enable_if".
10765 const IdentifierInfo *EnableIfII =
10766 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10767 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10768 return false;
10769
10770 // Assume the first template argument is the condition.
10771 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10772
10773 // Dig out the condition.
10774 Cond = nullptr;
10775 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10777 return true;
10778
10779 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10780
10781 // Ignore Boolean literals; they add no value.
10782 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10783 Cond = nullptr;
10784
10785 return true;
10786}
10787
10790 SourceLocation KeywordLoc,
10791 NestedNameSpecifierLoc QualifierLoc,
10792 const IdentifierInfo &II,
10793 SourceLocation IILoc,
10794 TypeSourceInfo **TSI,
10795 bool DeducedTSTContext) {
10796 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10797 DeducedTSTContext);
10798 if (T.isNull())
10799 return QualType();
10800
10802 if (isa<DependentNameType>(T)) {
10804 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10805 TL.setElaboratedKeywordLoc(KeywordLoc);
10806 TL.setQualifierLoc(QualifierLoc);
10807 TL.setNameLoc(IILoc);
10808 } else {
10809 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10810 TL.setElaboratedKeywordLoc(KeywordLoc);
10811 TL.setQualifierLoc(QualifierLoc);
10812 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10813 }
10814 return T;
10815}
10816
10817/// Build the type that describes a C++ typename specifier,
10818/// e.g., "typename T::type".
10821 SourceLocation KeywordLoc,
10822 NestedNameSpecifierLoc QualifierLoc,
10823 const IdentifierInfo &II,
10824 SourceLocation IILoc, bool DeducedTSTContext) {
10825 CXXScopeSpec SS;
10826 SS.Adopt(QualifierLoc);
10827
10828 DeclContext *Ctx = nullptr;
10829 if (QualifierLoc) {
10830 Ctx = computeDeclContext(SS);
10831 if (!Ctx) {
10832 // If the nested-name-specifier is dependent and couldn't be
10833 // resolved to a type, build a typename type.
10834 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10835 return Context.getDependentNameType(Keyword,
10836 QualifierLoc.getNestedNameSpecifier(),
10837 &II);
10838 }
10839
10840 // If the nested-name-specifier refers to the current instantiation,
10841 // the "typename" keyword itself is superfluous. In C++03, the
10842 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10843 // allows such extraneous "typename" keywords, and we retroactively
10844 // apply this DR to C++03 code with only a warning. In any case we continue.
10845
10846 if (RequireCompleteDeclContext(SS, Ctx))
10847 return QualType();
10848 }
10849
10850 DeclarationName Name(&II);
10851 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10852 if (Ctx)
10853 LookupQualifiedName(Result, Ctx, SS);
10854 else
10855 LookupName(Result, CurScope);
10856 unsigned DiagID = 0;
10857 Decl *Referenced = nullptr;
10858 switch (Result.getResultKind()) {
10860 // If we're looking up 'type' within a template named 'enable_if', produce
10861 // a more specific diagnostic.
10862 SourceRange CondRange;
10863 Expr *Cond = nullptr;
10864 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10865 // If we have a condition, narrow it down to the specific failed
10866 // condition.
10867 if (Cond) {
10868 Expr *FailedCond;
10869 std::string FailedDescription;
10870 std::tie(FailedCond, FailedDescription) =
10872
10873 Diag(FailedCond->getExprLoc(),
10874 diag::err_typename_nested_not_found_requirement)
10875 << FailedDescription
10876 << FailedCond->getSourceRange();
10877 return QualType();
10878 }
10879
10880 Diag(CondRange.getBegin(),
10881 diag::err_typename_nested_not_found_enable_if)
10882 << Ctx << CondRange;
10883 return QualType();
10884 }
10885
10886 DiagID = Ctx ? diag::err_typename_nested_not_found
10887 : diag::err_unknown_typename;
10888 break;
10889 }
10890
10892 // We found a using declaration that is a value. Most likely, the using
10893 // declaration itself is meant to have the 'typename' keyword.
10894 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10895 IILoc);
10896 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10897 << Name << Ctx << FullRange;
10898 if (UnresolvedUsingValueDecl *Using
10899 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10900 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10901 Diag(Loc, diag::note_using_value_decl_missing_typename)
10902 << FixItHint::CreateInsertion(Loc, "typename ");
10903 }
10904 }
10905 // Fall through to create a dependent typename type, from which we can recover
10906 // better.
10907 [[fallthrough]];
10908
10910 // Okay, it's a member of an unknown instantiation.
10911 return Context.getDependentNameType(Keyword,
10912 QualifierLoc.getNestedNameSpecifier(),
10913 &II);
10914
10916 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10917 // C++ [class.qual]p2:
10918 // In a lookup in which function names are not ignored and the
10919 // nested-name-specifier nominates a class C, if the name specified
10920 // after the nested-name-specifier, when looked up in C, is the
10921 // injected-class-name of C [...] then the name is instead considered
10922 // to name the constructor of class C.
10923 //
10924 // Unlike in an elaborated-type-specifier, function names are not ignored
10925 // in typename-specifier lookup. However, they are ignored in all the
10926 // contexts where we form a typename type with no keyword (that is, in
10927 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10928 //
10929 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10930 // ignore functions, but that appears to be an oversight.
10931 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10932 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10933 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10934 FoundRD->isInjectedClassName() &&
10935 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10936 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10937 << &II << 1 << 0 /*'typename' keyword used*/;
10938
10939 // We found a type. Build an ElaboratedType, since the
10940 // typename-specifier was just sugar.
10941 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10942 return Context.getElaboratedType(Keyword,
10943 QualifierLoc.getNestedNameSpecifier(),
10945 }
10946
10947 // C++ [dcl.type.simple]p2:
10948 // A type-specifier of the form
10949 // typename[opt] nested-name-specifier[opt] template-name
10950 // is a placeholder for a deduced class type [...].
10951 if (getLangOpts().CPlusPlus17) {
10952 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10953 if (!DeducedTSTContext) {
10954 QualType T(QualifierLoc
10955 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10956 : nullptr, 0);
10957 if (!T.isNull())
10958 Diag(IILoc, diag::err_dependent_deduced_tst)
10960 else
10961 Diag(IILoc, diag::err_deduced_tst)
10964 return QualType();
10965 }
10967 Keyword, QualifierLoc.getNestedNameSpecifier(),
10969 QualType(), false));
10970 }
10971 }
10972
10973 DiagID = Ctx ? diag::err_typename_nested_not_type
10974 : diag::err_typename_not_type;
10975 Referenced = Result.getFoundDecl();
10976 break;
10977
10979 DiagID = Ctx ? diag::err_typename_nested_not_type
10980 : diag::err_typename_not_type;
10981 Referenced = *Result.begin();
10982 break;
10983
10985 return QualType();
10986 }
10987
10988 // If we get here, it's because name lookup did not find a
10989 // type. Emit an appropriate diagnostic and return an error.
10990 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10991 IILoc);
10992 if (Ctx)
10993 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10994 else
10995 Diag(IILoc, DiagID) << FullRange << Name;
10996 if (Referenced)
10997 Diag(Referenced->getLocation(),
10998 Ctx ? diag::note_typename_member_refers_here
10999 : diag::note_typename_refers_here)
11000 << Name;
11001 return QualType();
11002}
11003
11004namespace {
11005 // See Sema::RebuildTypeInCurrentInstantiation
11006 class CurrentInstantiationRebuilder
11007 : public TreeTransform<CurrentInstantiationRebuilder> {
11009 DeclarationName Entity;
11010
11011 public:
11013
11014 CurrentInstantiationRebuilder(Sema &SemaRef,
11016 DeclarationName Entity)
11017 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11018 Loc(Loc), Entity(Entity) { }
11019
11020 /// Determine whether the given type \p T has already been
11021 /// transformed.
11022 ///
11023 /// For the purposes of type reconstruction, a type has already been
11024 /// transformed if it is NULL or if it is not dependent.
11025 bool AlreadyTransformed(QualType T) {
11026 return T.isNull() || !T->isInstantiationDependentType();
11027 }
11028
11029 /// Returns the location of the entity whose type is being
11030 /// rebuilt.
11031 SourceLocation getBaseLocation() { return Loc; }
11032
11033 /// Returns the name of the entity whose type is being rebuilt.
11034 DeclarationName getBaseEntity() { return Entity; }
11035
11036 /// Sets the "base" location and entity when that
11037 /// information is known based on another transformation.
11038 void setBase(SourceLocation Loc, DeclarationName Entity) {
11039 this->Loc = Loc;
11040 this->Entity = Entity;
11041 }
11042
11043 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11044 // Lambdas never need to be transformed.
11045 return E;
11046 }
11047 };
11048} // end anonymous namespace
11049
11052 DeclarationName Name) {
11053 if (!T || !T->getType()->isInstantiationDependentType())
11054 return T;
11055
11056 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11057 return Rebuilder.TransformType(T);
11058}
11059
11061 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11062 DeclarationName());
11063 return Rebuilder.TransformExpr(E);
11064}
11065
11067 if (SS.isInvalid())
11068 return true;
11069
11071 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11072 DeclarationName());
11074 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11075 if (!Rebuilt)
11076 return true;
11077
11078 SS.Adopt(Rebuilt);
11079 return false;
11080}
11081
11083 TemplateParameterList *Params) {
11084 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11085 Decl *Param = Params->getParam(I);
11086
11087 // There is nothing to rebuild in a type parameter.
11088 if (isa<TemplateTypeParmDecl>(Param))
11089 continue;
11090
11091 // Rebuild the template parameter list of a template template parameter.
11093 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11095 TTP->getTemplateParameters()))
11096 return true;
11097
11098 continue;
11099 }
11100
11101 // Rebuild the type of a non-type template parameter.
11102 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11103 TypeSourceInfo *NewTSI
11105 NTTP->getLocation(),
11106 NTTP->getDeclName());
11107 if (!NewTSI)
11108 return true;
11109
11110 if (NewTSI->getType()->isUndeducedType()) {
11111 // C++17 [temp.dep.expr]p3:
11112 // An id-expression is type-dependent if it contains
11113 // - an identifier associated by name lookup with a non-type
11114 // template-parameter declared with a type that contains a
11115 // placeholder type (7.1.7.4),
11116 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11117 }
11118
11119 if (NewTSI != NTTP->getTypeSourceInfo()) {
11120 NTTP->setTypeSourceInfo(NewTSI);
11121 NTTP->setType(NewTSI->getType());
11122 }
11123 }
11124
11125 return false;
11126}
11127
11128std::string
11130 const TemplateArgumentList &Args) {
11131 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11132}
11133
11134std::string
11136 const TemplateArgument *Args,
11137 unsigned NumArgs) {
11138 SmallString<128> Str;
11139 llvm::raw_svector_ostream Out(Str);
11140
11141 if (!Params || Params->size() == 0 || NumArgs == 0)
11142 return std::string();
11143
11144 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11145 if (I >= NumArgs)
11146 break;
11147
11148 if (I == 0)
11149 Out << "[with ";
11150 else
11151 Out << ", ";
11152
11153 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11154 Out << Id->getName();
11155 } else {
11156 Out << '$' << I;
11157 }
11158
11159 Out << " = ";
11160 Args[I].print(getPrintingPolicy(), Out,
11162 getPrintingPolicy(), Params, I));
11163 }
11164
11165 Out << ']';
11166 return std::string(Out.str());
11167}
11168
11170 CachedTokens &Toks) {
11171 if (!FD)
11172 return;
11173
11174 auto LPT = std::make_unique<LateParsedTemplate>();
11175
11176 // Take tokens to avoid allocations
11177 LPT->Toks.swap(Toks);
11178 LPT->D = FnD;
11179 LPT->FPO = getCurFPFeatures();
11180 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11181
11182 FD->setLateTemplateParsed(true);
11183}
11184
11186 if (!FD)
11187 return;
11188 FD->setLateTemplateParsed(false);
11189}
11190
11192 DeclContext *DC = CurContext;
11193
11194 while (DC) {
11195 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11196 const FunctionDecl *FD = RD->isLocalClass();
11197 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11198 } else if (DC->isTranslationUnit() || DC->isNamespace())
11199 return false;
11200
11201 DC = DC->getParent();
11202 }
11203 return false;
11204}
11205
11206namespace {
11207/// Walk the path from which a declaration was instantiated, and check
11208/// that every explicit specialization along that path is visible. This enforces
11209/// C++ [temp.expl.spec]/6:
11210///
11211/// If a template, a member template or a member of a class template is
11212/// explicitly specialized then that specialization shall be declared before
11213/// the first use of that specialization that would cause an implicit
11214/// instantiation to take place, in every translation unit in which such a
11215/// use occurs; no diagnostic is required.
11216///
11217/// and also C++ [temp.class.spec]/1:
11218///
11219/// A partial specialization shall be declared before the first use of a
11220/// class template specialization that would make use of the partial
11221/// specialization as the result of an implicit or explicit instantiation
11222/// in every translation unit in which such a use occurs; no diagnostic is
11223/// required.
11224class ExplicitSpecializationVisibilityChecker {
11225 Sema &S;
11229
11230public:
11231 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11233 : S(S), Loc(Loc), Kind(Kind) {}
11234
11235 void check(NamedDecl *ND) {
11236 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11237 return checkImpl(FD);
11238 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11239 return checkImpl(RD);
11240 if (auto *VD = dyn_cast<VarDecl>(ND))
11241 return checkImpl(VD);
11242 if (auto *ED = dyn_cast<EnumDecl>(ND))
11243 return checkImpl(ED);
11244 }
11245
11246private:
11247 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11248 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11249 : Sema::MissingImportKind::ExplicitSpecialization;
11250 const bool Recover = true;
11251
11252 // If we got a custom set of modules (because only a subset of the
11253 // declarations are interesting), use them, otherwise let
11254 // diagnoseMissingImport intelligently pick some.
11255 if (Modules.empty())
11256 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11257 else
11258 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11259 }
11260
11261 bool CheckMemberSpecialization(const NamedDecl *D) {
11262 return Kind == Sema::AcceptableKind::Visible
11265 }
11266
11267 bool CheckExplicitSpecialization(const NamedDecl *D) {
11268 return Kind == Sema::AcceptableKind::Visible
11271 }
11272
11273 bool CheckDeclaration(const NamedDecl *D) {
11274 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11276 }
11277
11278 // Check a specific declaration. There are three problematic cases:
11279 //
11280 // 1) The declaration is an explicit specialization of a template
11281 // specialization.
11282 // 2) The declaration is an explicit specialization of a member of an
11283 // templated class.
11284 // 3) The declaration is an instantiation of a template, and that template
11285 // is an explicit specialization of a member of a templated class.
11286 //
11287 // We don't need to go any deeper than that, as the instantiation of the
11288 // surrounding class / etc is not triggered by whatever triggered this
11289 // instantiation, and thus should be checked elsewhere.
11290 template<typename SpecDecl>
11291 void checkImpl(SpecDecl *Spec) {
11292 bool IsHiddenExplicitSpecialization = false;
11293 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11294 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11295 ? !CheckMemberSpecialization(Spec)
11296 : !CheckExplicitSpecialization(Spec);
11297 } else {
11298 checkInstantiated(Spec);
11299 }
11300
11301 if (IsHiddenExplicitSpecialization)
11302 diagnose(Spec->getMostRecentDecl(), false);
11303 }
11304
11305 void checkInstantiated(FunctionDecl *FD) {
11306 if (auto *TD = FD->getPrimaryTemplate())
11307 checkTemplate(TD);
11308 }
11309
11310 void checkInstantiated(CXXRecordDecl *RD) {
11311 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11312 if (!SD)
11313 return;
11314
11315 auto From = SD->getSpecializedTemplateOrPartial();
11316 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11317 checkTemplate(TD);
11318 else if (auto *TD =
11319 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11320 if (!CheckDeclaration(TD))
11321 diagnose(TD, true);
11322 checkTemplate(TD);
11323 }
11324 }
11325
11326 void checkInstantiated(VarDecl *RD) {
11327 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11328 if (!SD)
11329 return;
11330
11331 auto From = SD->getSpecializedTemplateOrPartial();
11332 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11333 checkTemplate(TD);
11334 else if (auto *TD =
11335 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11336 if (!CheckDeclaration(TD))
11337 diagnose(TD, true);
11338 checkTemplate(TD);
11339 }
11340 }
11341
11342 void checkInstantiated(EnumDecl *FD) {}
11343
11344 template<typename TemplDecl>
11345 void checkTemplate(TemplDecl *TD) {
11346 if (TD->isMemberSpecialization()) {
11347 if (!CheckMemberSpecialization(TD))
11348 diagnose(TD->getMostRecentDecl(), false);
11349 }
11350 }
11351};
11352} // end anonymous namespace
11353
11355 if (!getLangOpts().Modules)
11356 return;
11357
11358 ExplicitSpecializationVisibilityChecker(*this, Loc,
11360 .check(Spec);
11361}
11362
11364 NamedDecl *Spec) {
11365 if (!getLangOpts().CPlusPlusModules)
11366 return checkSpecializationVisibility(Loc, Spec);
11367
11368 ExplicitSpecializationVisibilityChecker(*this, Loc,
11370 .check(Spec);
11371}
11372
11375 return N->getLocation();
11376 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11378 return FD->getLocation();
11381 return N->getLocation();
11382 }
11383 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11384 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11385 continue;
11386 return CSC.PointOfInstantiation;
11387 }
11388 return N->getLocation();
11389}
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:6861
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:1982
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:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2011
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1989
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2022
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:2100
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2229
bool isFileContext() const
Definition: DeclBase.h:2171
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2053
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:2035
bool isNamespace() const
Definition: DeclBase.h:2189
bool isTranslationUnit() const
Definition: DeclBase.h:2176
bool isRecord() const
Definition: DeclBase.h:2180
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1998
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:2016
bool isFunctionOrMethod() const
Definition: DeclBase.h:2152
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:2780
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:7637
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:4361
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:5003
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:6129
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:6114
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:6257
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:5821
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:16961
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:16936
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:9841
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:14940
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
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:4746
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:17145
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:14975
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:6075
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.