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 bool *MatchedPackOnParmToNonPackOnArg) {
5209 // Check template type parameters.
5210 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5211 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5212 CanonicalConverted);
5213
5214 // Check non-type template parameters.
5215 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5216 // Do substitution on the type of the non-type template parameter
5217 // with the template arguments we've seen thus far. But if the
5218 // template has a dependent context then we cannot substitute yet.
5219 QualType NTTPType = NTTP->getType();
5220 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5221 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5222
5223 if (NTTPType->isInstantiationDependentType() &&
5224 !isa<TemplateTemplateParmDecl>(Template) &&
5225 !Template->getDeclContext()->isDependentContext()) {
5226 // Do substitution on the type of the non-type template parameter.
5227 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5228 SugaredConverted,
5229 SourceRange(TemplateLoc, RAngleLoc));
5230 if (Inst.isInvalid())
5231 return true;
5232
5233 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5234 /*Final=*/true);
5235 // If the parameter is a pack expansion, expand this slice of the pack.
5236 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5238 ArgumentPackIndex);
5239 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5240 NTTP->getDeclName());
5241 } else {
5242 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5243 NTTP->getDeclName());
5244 }
5245
5246 // If that worked, check the non-type template parameter type
5247 // for validity.
5248 if (!NTTPType.isNull())
5249 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5250 NTTP->getLocation());
5251 if (NTTPType.isNull())
5252 return true;
5253 }
5254
5255 switch (Arg.getArgument().getKind()) {
5257 llvm_unreachable("Should never see a NULL template argument here");
5258
5260 Expr *E = Arg.getArgument().getAsExpr();
5261 TemplateArgument SugaredResult, CanonicalResult;
5262 unsigned CurSFINAEErrors = NumSFINAEErrors;
5263 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5264 CanonicalResult, CTAK);
5265 if (Res.isInvalid())
5266 return true;
5267 // If the current template argument causes an error, give up now.
5268 if (CurSFINAEErrors < NumSFINAEErrors)
5269 return true;
5270
5271 // If the resulting expression is new, then use it in place of the
5272 // old expression in the template argument.
5273 if (Res.get() != E) {
5274 TemplateArgument TA(Res.get());
5275 Arg = TemplateArgumentLoc(TA, Res.get());
5276 }
5277
5278 SugaredConverted.push_back(SugaredResult);
5279 CanonicalConverted.push_back(CanonicalResult);
5280 break;
5281 }
5282
5287 // We've already checked this template argument, so just copy
5288 // it to the list of converted arguments.
5289 SugaredConverted.push_back(Arg.getArgument());
5290 CanonicalConverted.push_back(
5292 break;
5293
5296 // We were given a template template argument. It may not be ill-formed;
5297 // see below.
5298 if (DependentTemplateName *DTN
5301 // We have a template argument such as \c T::template X, which we
5302 // parsed as a template template argument. However, since we now
5303 // know that we need a non-type template argument, convert this
5304 // template name into an expression.
5305
5306 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5307 Arg.getTemplateNameLoc());
5308
5309 CXXScopeSpec SS;
5311 // FIXME: the template-template arg was a DependentTemplateName,
5312 // so it was provided with a template keyword. However, its source
5313 // location is not stored in the template argument structure.
5314 SourceLocation TemplateKWLoc;
5316 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5317 nullptr);
5318
5319 // If we parsed the template argument as a pack expansion, create a
5320 // pack expansion expression.
5323 if (E.isInvalid())
5324 return true;
5325 }
5326
5327 TemplateArgument SugaredResult, CanonicalResult;
5328 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5329 CanonicalResult, CTAK_Specified);
5330 if (E.isInvalid())
5331 return true;
5332
5333 SugaredConverted.push_back(SugaredResult);
5334 CanonicalConverted.push_back(CanonicalResult);
5335 break;
5336 }
5337
5338 // We have a template argument that actually does refer to a class
5339 // template, alias template, or template template parameter, and
5340 // therefore cannot be a non-type template argument.
5341 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5342 << Arg.getSourceRange();
5344
5345 return true;
5346
5348 // We have a non-type template parameter but the template
5349 // argument is a type.
5350
5351 // C++ [temp.arg]p2:
5352 // In a template-argument, an ambiguity between a type-id and
5353 // an expression is resolved to a type-id, regardless of the
5354 // form of the corresponding template-parameter.
5355 //
5356 // We warn specifically about this case, since it can be rather
5357 // confusing for users.
5358 QualType T = Arg.getArgument().getAsType();
5359 SourceRange SR = Arg.getSourceRange();
5360 if (T->isFunctionType())
5361 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5362 else
5363 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5365 return true;
5366 }
5367
5369 llvm_unreachable("Caller must expand template argument packs");
5370 }
5371
5372 return false;
5373 }
5374
5375
5376 // Check template template parameters.
5377 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5378
5379 TemplateParameterList *Params = TempParm->getTemplateParameters();
5380 if (TempParm->isExpandedParameterPack())
5381 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5382
5383 // Substitute into the template parameter list of the template
5384 // template parameter, since previously-supplied template arguments
5385 // may appear within the template template parameter.
5386 //
5387 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5388 {
5389 // Set up a template instantiation context.
5391 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5392 SugaredConverted,
5393 SourceRange(TemplateLoc, RAngleLoc));
5394 if (Inst.isInvalid())
5395 return true;
5396
5397 Params =
5400 Template, SugaredConverted, /*Final=*/true),
5401 /*EvaluateConstraints=*/false);
5402 if (!Params)
5403 return true;
5404 }
5405
5406 // C++1z [temp.local]p1: (DR1004)
5407 // When [the injected-class-name] is used [...] as a template-argument for
5408 // a template template-parameter [...] it refers to the class template
5409 // itself.
5413 if (!ConvertedArg.getArgument().isNull())
5414 Arg = ConvertedArg;
5415 }
5416
5417 switch (Arg.getArgument().getKind()) {
5419 llvm_unreachable("Should never see a NULL template argument here");
5420
5423 if (CheckTemplateTemplateArgument(TempParm, Params, Arg, PartialOrdering,
5424 MatchedPackOnParmToNonPackOnArg))
5425 return true;
5426
5427 SugaredConverted.push_back(Arg.getArgument());
5428 CanonicalConverted.push_back(
5430 break;
5431
5434 // We have a template template parameter but the template
5435 // argument does not refer to a template.
5436 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5437 << getLangOpts().CPlusPlus11;
5438 return true;
5439
5444 llvm_unreachable("non-type argument with template template parameter");
5445
5447 llvm_unreachable("Caller must expand template argument packs");
5448 }
5449
5450 return false;
5451}
5452
5453/// Diagnose a missing template argument.
5454template<typename TemplateParmDecl>
5456 TemplateDecl *TD,
5457 const TemplateParmDecl *D,
5459 // Dig out the most recent declaration of the template parameter; there may be
5460 // declarations of the template that are more recent than TD.
5461 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5462 ->getTemplateParameters()
5463 ->getParam(D->getIndex()));
5464
5465 // If there's a default argument that's not reachable, diagnose that we're
5466 // missing a module import.
5468 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5469 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5470 D->getDefaultArgumentLoc(), Modules,
5472 /*Recover*/true);
5473 return true;
5474 }
5475
5476 // FIXME: If there's a more recent default argument that *is* visible,
5477 // diagnose that it was declared too late.
5478
5480
5481 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5482 << /*not enough args*/0
5484 << TD;
5485 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5486 return true;
5487}
5488
5489/// Check that the given template argument list is well-formed
5490/// for specializing the given template.
5492 TemplateDecl *Template, SourceLocation TemplateLoc,
5493 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5494 bool PartialTemplateArgs,
5495 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5496 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5497 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5498 bool PartialOrderingTTP, bool *MatchedPackOnParmToNonPackOnArg) {
5499
5501 *ConstraintsNotSatisfied = false;
5502
5503 // Make a copy of the template arguments for processing. Only make the
5504 // changes at the end when successful in matching the arguments to the
5505 // template.
5506 TemplateArgumentListInfo NewArgs = TemplateArgs;
5507
5509
5510 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5511
5512 // C++23 [temp.arg.general]p1:
5513 // [...] The type and form of each template-argument specified in
5514 // a template-id shall match the type and form specified for the
5515 // corresponding parameter declared by the template in its
5516 // template-parameter-list.
5517 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5518 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5519 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5520 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5521 LocalInstantiationScope InstScope(*this, true);
5522 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5523 ParamEnd = Params->end(),
5524 Param = ParamBegin;
5525 Param != ParamEnd;
5526 /* increment in loop */) {
5527 if (size_t ParamIdx = Param - ParamBegin;
5528 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5529 // All written arguments should have been consumed by this point.
5530 assert(ArgIdx == NumArgs && "bad default argument deduction");
5531 if (ParamIdx == DefaultArgs.StartPos) {
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 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5574 bool NonPackParameter =
5575 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);
5576 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5577
5578 if (ArgIsExpansion && PartialOrderingTTP) {
5579 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5580 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5581 ++Param) {
5582 TemplateArgument &Arg = Args[Param - First];
5583 Arg = ArgLoc.getArgument();
5584 if (!(*Param)->isTemplateParameterPack() ||
5585 getExpandedPackSize(*Param))
5586 Arg = Arg.getPackExpansionPattern();
5587 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5588 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,
5589 RAngleLoc, SugaredArgumentPack.size(),
5590 SugaredConverted, CanonicalConverted,
5591 CTAK_Specified, /*PartialOrdering=*/false,
5592 MatchedPackOnParmToNonPackOnArg))
5593 return true;
5594 Arg = NewArgLoc.getArgument();
5595 CanonicalConverted.back().setIsDefaulted(
5597 CanonicalConverted,
5598 Params->getDepth()));
5599 }
5600 ArgLoc =
5602 ArgLoc.getLocInfo());
5603 } else {
5604 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,
5605 RAngleLoc, SugaredArgumentPack.size(),
5606 SugaredConverted, CanonicalConverted,
5607 CTAK_Specified, /*PartialOrdering=*/false,
5608 MatchedPackOnParmToNonPackOnArg))
5609 return true;
5610 CanonicalConverted.back().setIsDefaulted(
5612 *Param, CanonicalConverted,
5613 Params->getDepth()));
5614 if (ArgIsExpansion && NonPackParameter) {
5615 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5616 // alias template or concept, and it's not part of a parameter pack.
5617 // This can't be canonicalized, so reject it now.
5618 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Template)) {
5619 Diag(ArgLoc.getLocation(),
5620 diag::err_template_expansion_into_fixed_list)
5621 << (isa<ConceptDecl>(Template) ? 1 : 0)
5622 << ArgLoc.getSourceRange();
5624 return true;
5625 }
5626 }
5627 }
5628
5629 // We're now done with this argument.
5630 ++ArgIdx;
5631
5632 if (ArgIsExpansion && (PartialOrderingTTP || NonPackParameter)) {
5633 // Directly convert the remaining arguments, because we don't know what
5634 // parameters they'll match up with.
5635
5636 if (!SugaredArgumentPack.empty()) {
5637 // If we were part way through filling in an expanded parameter pack,
5638 // fall back to just producing individual arguments.
5639 SugaredConverted.insert(SugaredConverted.end(),
5640 SugaredArgumentPack.begin(),
5641 SugaredArgumentPack.end());
5642 SugaredArgumentPack.clear();
5643
5644 CanonicalConverted.insert(CanonicalConverted.end(),
5645 CanonicalArgumentPack.begin(),
5646 CanonicalArgumentPack.end());
5647 CanonicalArgumentPack.clear();
5648 }
5649
5650 while (ArgIdx < NumArgs) {
5651 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5652 SugaredConverted.push_back(Arg);
5653 CanonicalConverted.push_back(
5655 ++ArgIdx;
5656 }
5657
5658 return false;
5659 }
5660
5661 if ((*Param)->isTemplateParameterPack()) {
5662 // The template parameter was a template parameter pack, so take the
5663 // deduced argument and place it on the argument pack. Note that we
5664 // stay on the same template parameter so that we can deduce more
5665 // arguments.
5666 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5667 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5668 } else {
5669 // Move to the next template parameter.
5670 ++Param;
5671 }
5672 continue;
5673 }
5674
5675 // If we're checking a partial template argument list, we're done.
5676 if (PartialTemplateArgs) {
5677 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5678 SugaredConverted.push_back(
5679 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5680 CanonicalConverted.push_back(
5681 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5682 }
5683 return false;
5684 }
5685
5686 // If we have a template parameter pack with no more corresponding
5687 // arguments, just break out now and we'll fill in the argument pack below.
5688 if ((*Param)->isTemplateParameterPack()) {
5689 assert(!getExpandedPackSize(*Param) &&
5690 "Should have dealt with this already");
5691
5692 // A non-expanded parameter pack before the end of the parameter list
5693 // only occurs for an ill-formed template parameter list, unless we've
5694 // got a partial argument list for a function template, so just bail out.
5695 if (Param + 1 != ParamEnd) {
5696 assert(
5697 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5698 "Concept templates must have parameter packs at the end.");
5699 return true;
5700 }
5701
5702 SugaredConverted.push_back(
5703 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5704 SugaredArgumentPack.clear();
5705
5706 CanonicalConverted.push_back(
5707 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5708 CanonicalArgumentPack.clear();
5709
5710 ++Param;
5711 continue;
5712 }
5713
5714 // Check whether we have a default argument.
5715 bool HasDefaultArg;
5716
5717 // Retrieve the default template argument from the template
5718 // parameter. For each kind of template parameter, we substitute the
5719 // template arguments provided thus far and any "outer" template arguments
5720 // (when the template parameter was part of a nested template) into
5721 // the default argument.
5723 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5724 CanonicalConverted, HasDefaultArg);
5725
5726 if (Arg.getArgument().isNull()) {
5727 if (!HasDefaultArg) {
5728 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5729 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5730 NewArgs);
5731 if (NonTypeTemplateParmDecl *NTTP =
5732 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5733 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5734 NewArgs);
5735 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5736 cast<TemplateTemplateParmDecl>(*Param),
5737 NewArgs);
5738 }
5739 return true;
5740 }
5741
5742 // Introduce an instantiation record that describes where we are using
5743 // the default template argument. We're not actually instantiating a
5744 // template here, we just create this object to put a note into the
5745 // context stack.
5746 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5747 SugaredConverted,
5748 SourceRange(TemplateLoc, RAngleLoc));
5749 if (Inst.isInvalid())
5750 return true;
5751
5752 // Check the default template argument.
5753 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5754 SugaredConverted, CanonicalConverted,
5755 CTAK_Specified, /*PartialOrdering=*/false,
5756 /*MatchedPackOnParmToNonPackOnArg=*/nullptr))
5757 return true;
5758
5759 SugaredConverted.back().setIsDefaulted(true);
5760 CanonicalConverted.back().setIsDefaulted(true);
5761
5762 // Core issue 150 (assumed resolution): if this is a template template
5763 // parameter, keep track of the default template arguments from the
5764 // template definition.
5765 if (isTemplateTemplateParameter)
5766 NewArgs.addArgument(Arg);
5767
5768 // Move to the next template parameter and argument.
5769 ++Param;
5770 ++ArgIdx;
5771 }
5772
5773 // If we're performing a partial argument substitution, allow any trailing
5774 // pack expansions; they might be empty. This can happen even if
5775 // PartialTemplateArgs is false (the list of arguments is complete but
5776 // still dependent).
5777 if (PartialOrderingTTP ||
5780 while (ArgIdx < NumArgs &&
5781 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5782 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5783 SugaredConverted.push_back(Arg);
5784 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5785 }
5786 }
5787
5788 // If we have any leftover arguments, then there were too many arguments.
5789 // Complain and fail.
5790 if (ArgIdx < NumArgs) {
5791 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5792 << /*too many args*/1
5794 << Template
5795 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5796 NoteTemplateLocation(*Template, Params->getSourceRange());
5797 return true;
5798 }
5799
5800 // No problems found with the new argument list, propagate changes back
5801 // to caller.
5802 if (UpdateArgsWithConversions)
5803 TemplateArgs = std::move(NewArgs);
5804
5805 if (!PartialTemplateArgs) {
5806 // Setup the context/ThisScope for the case where we are needing to
5807 // re-instantiate constraints outside of normal instantiation.
5808 DeclContext *NewContext = Template->getDeclContext();
5809
5810 // If this template is in a template, make sure we extract the templated
5811 // decl.
5812 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5813 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5814 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5815
5816 Qualifiers ThisQuals;
5817 if (const auto *Method =
5818 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5819 ThisQuals = Method->getMethodQualifiers();
5820
5821 ContextRAII Context(*this, NewContext);
5822 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5823
5825 Template, NewContext, /*Final=*/false, CanonicalConverted,
5826 /*RelativeToPrimary=*/true,
5827 /*Pattern=*/nullptr,
5828 /*ForConceptInstantiation=*/true);
5830 Template, MLTAL,
5831 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5834 return true;
5835 }
5836 }
5837
5838 return false;
5839}
5840
5841namespace {
5842 class UnnamedLocalNoLinkageFinder
5843 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5844 {
5845 Sema &S;
5846 SourceRange SR;
5847
5849
5850 public:
5851 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5852
5853 bool Visit(QualType T) {
5854 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5855 }
5856
5857#define TYPE(Class, Parent) \
5858 bool Visit##Class##Type(const Class##Type *);
5859#define ABSTRACT_TYPE(Class, Parent) \
5860 bool Visit##Class##Type(const Class##Type *) { return false; }
5861#define NON_CANONICAL_TYPE(Class, Parent) \
5862 bool Visit##Class##Type(const Class##Type *) { return false; }
5863#include "clang/AST/TypeNodes.inc"
5864
5865 bool VisitTagDecl(const TagDecl *Tag);
5866 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5867 };
5868} // end anonymous namespace
5869
5870bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5871 return false;
5872}
5873
5874bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5875 return Visit(T->getElementType());
5876}
5877
5878bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5879 return Visit(T->getPointeeType());
5880}
5881
5882bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5883 const BlockPointerType* T) {
5884 return Visit(T->getPointeeType());
5885}
5886
5887bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5888 const LValueReferenceType* T) {
5889 return Visit(T->getPointeeType());
5890}
5891
5892bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5893 const RValueReferenceType* T) {
5894 return Visit(T->getPointeeType());
5895}
5896
5897bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5898 const MemberPointerType* T) {
5899 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5900}
5901
5902bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5903 const ConstantArrayType* T) {
5904 return Visit(T->getElementType());
5905}
5906
5907bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5908 const IncompleteArrayType* T) {
5909 return Visit(T->getElementType());
5910}
5911
5912bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5913 const VariableArrayType* T) {
5914 return Visit(T->getElementType());
5915}
5916
5917bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5918 const DependentSizedArrayType* T) {
5919 return Visit(T->getElementType());
5920}
5921
5922bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5924 return Visit(T->getElementType());
5925}
5926
5927bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5928 const DependentSizedMatrixType *T) {
5929 return Visit(T->getElementType());
5930}
5931
5932bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5934 return Visit(T->getPointeeType());
5935}
5936
5937bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5938 return Visit(T->getElementType());
5939}
5940
5941bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5942 const DependentVectorType *T) {
5943 return Visit(T->getElementType());
5944}
5945
5946bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5947 return Visit(T->getElementType());
5948}
5949
5950bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5951 const ConstantMatrixType *T) {
5952 return Visit(T->getElementType());
5953}
5954
5955bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5956 const FunctionProtoType* T) {
5957 for (const auto &A : T->param_types()) {
5958 if (Visit(A))
5959 return true;
5960 }
5961
5962 return Visit(T->getReturnType());
5963}
5964
5965bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5966 const FunctionNoProtoType* T) {
5967 return Visit(T->getReturnType());
5968}
5969
5970bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5971 const UnresolvedUsingType*) {
5972 return false;
5973}
5974
5975bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5976 return false;
5977}
5978
5979bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5980 return Visit(T->getUnmodifiedType());
5981}
5982
5983bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5984 return false;
5985}
5986
5987bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5988 const PackIndexingType *) {
5989 return false;
5990}
5991
5992bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5993 const UnaryTransformType*) {
5994 return false;
5995}
5996
5997bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5998 return Visit(T->getDeducedType());
5999}
6000
6001bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6003 return Visit(T->getDeducedType());
6004}
6005
6006bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6007 return VisitTagDecl(T->getDecl());
6008}
6009
6010bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6011 return VisitTagDecl(T->getDecl());
6012}
6013
6014bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6015 const TemplateTypeParmType*) {
6016 return false;
6017}
6018
6019bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6021 return false;
6022}
6023
6024bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6026 return false;
6027}
6028
6029bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6030 const InjectedClassNameType* T) {
6031 return VisitTagDecl(T->getDecl());
6032}
6033
6034bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6035 const DependentNameType* T) {
6036 return VisitNestedNameSpecifier(T->getQualifier());
6037}
6038
6039bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6041 if (auto *Q = T->getQualifier())
6042 return VisitNestedNameSpecifier(Q);
6043 return false;
6044}
6045
6046bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6047 const PackExpansionType* T) {
6048 return Visit(T->getPattern());
6049}
6050
6051bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6052 return false;
6053}
6054
6055bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6056 const ObjCInterfaceType *) {
6057 return false;
6058}
6059
6060bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6061 const ObjCObjectPointerType *) {
6062 return false;
6063}
6064
6065bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6066 return Visit(T->getValueType());
6067}
6068
6069bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6070 return false;
6071}
6072
6073bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6074 return false;
6075}
6076
6077bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6078 const ArrayParameterType *T) {
6079 return VisitConstantArrayType(T);
6080}
6081
6082bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6083 const DependentBitIntType *T) {
6084 return false;
6085}
6086
6087bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6088 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6089 S.Diag(SR.getBegin(),
6090 S.getLangOpts().CPlusPlus11 ?
6091 diag::warn_cxx98_compat_template_arg_local_type :
6092 diag::ext_template_arg_local_type)
6093 << S.Context.getTypeDeclType(Tag) << SR;
6094 return true;
6095 }
6096
6097 if (!Tag->hasNameForLinkage()) {
6098 S.Diag(SR.getBegin(),
6099 S.getLangOpts().CPlusPlus11 ?
6100 diag::warn_cxx98_compat_template_arg_unnamed_type :
6101 diag::ext_template_arg_unnamed_type) << SR;
6102 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6103 return true;
6104 }
6105
6106 return false;
6107}
6108
6109bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6110 NestedNameSpecifier *NNS) {
6111 assert(NNS);
6112 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6113 return true;
6114
6115 switch (NNS->getKind()) {
6121 return false;
6122
6125 return Visit(QualType(NNS->getAsType(), 0));
6126 }
6127 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6128}
6129
6130bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6132 if (T->hasContainedType() && Visit(T->getContainedType()))
6133 return true;
6134 return Visit(T->getWrappedType());
6135}
6136
6138 assert(ArgInfo && "invalid TypeSourceInfo");
6139 QualType Arg = ArgInfo->getType();
6140 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6141 QualType CanonArg = Context.getCanonicalType(Arg);
6142
6143 if (CanonArg->isVariablyModifiedType()) {
6144 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6146 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6147 }
6148
6149 // C++03 [temp.arg.type]p2:
6150 // A local type, a type with no linkage, an unnamed type or a type
6151 // compounded from any of these types shall not be used as a
6152 // template-argument for a template type-parameter.
6153 //
6154 // C++11 allows these, and even in C++03 we allow them as an extension with
6155 // a warning.
6156 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6157 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6158 (void)Finder.Visit(CanonArg);
6159 }
6160
6161 return false;
6162}
6163
6167 NPV_Error
6169
6170/// Determine whether the given template argument is a null pointer
6171/// value of the appropriate type.
6174 QualType ParamType, Expr *Arg,
6175 Decl *Entity = nullptr) {
6176 if (Arg->isValueDependent() || Arg->isTypeDependent())
6177 return NPV_NotNullPointer;
6178
6179 // dllimport'd entities aren't constant but are available inside of template
6180 // arguments.
6181 if (Entity && Entity->hasAttr<DLLImportAttr>())
6182 return NPV_NotNullPointer;
6183
6184 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6185 llvm_unreachable(
6186 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6187
6188 if (!S.getLangOpts().CPlusPlus11)
6189 return NPV_NotNullPointer;
6190
6191 // Determine whether we have a constant expression.
6193 if (ArgRV.isInvalid())
6194 return NPV_Error;
6195 Arg = ArgRV.get();
6196
6197 Expr::EvalResult EvalResult;
6199 EvalResult.Diag = &Notes;
6200 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6201 EvalResult.HasSideEffects) {
6202 SourceLocation DiagLoc = Arg->getExprLoc();
6203
6204 // If our only note is the usual "invalid subexpression" note, just point
6205 // the caret at its location rather than producing an essentially
6206 // redundant note.
6207 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6208 diag::note_invalid_subexpr_in_const_expr) {
6209 DiagLoc = Notes[0].first;
6210 Notes.clear();
6211 }
6212
6213 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6214 << Arg->getType() << Arg->getSourceRange();
6215 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6216 S.Diag(Notes[I].first, Notes[I].second);
6217
6219 return NPV_Error;
6220 }
6221
6222 // C++11 [temp.arg.nontype]p1:
6223 // - an address constant expression of type std::nullptr_t
6224 if (Arg->getType()->isNullPtrType())
6225 return NPV_NullPointer;
6226
6227 // - a constant expression that evaluates to a null pointer value (4.10); or
6228 // - a constant expression that evaluates to a null member pointer value
6229 // (4.11); or
6230 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6231 (EvalResult.Val.isMemberPointer() &&
6232 !EvalResult.Val.getMemberPointerDecl())) {
6233 // If our expression has an appropriate type, we've succeeded.
6234 bool ObjCLifetimeConversion;
6235 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6236 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6237 ObjCLifetimeConversion))
6238 return NPV_NullPointer;
6239
6240 // The types didn't match, but we know we got a null pointer; complain,
6241 // then recover as if the types were correct.
6242 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6243 << Arg->getType() << ParamType << Arg->getSourceRange();
6245 return NPV_NullPointer;
6246 }
6247
6248 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6249 // We found a pointer that isn't null, but doesn't refer to an object.
6250 // We could just return NPV_NotNullPointer, but we can print a better
6251 // message with the information we have here.
6252 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6253 << EvalResult.Val.getAsString(S.Context, ParamType);
6255 return NPV_Error;
6256 }
6257
6258 // If we don't have a null pointer value, but we do have a NULL pointer
6259 // constant, suggest a cast to the appropriate type.
6261 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6262 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6263 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6265 ")");
6267 return NPV_NullPointer;
6268 }
6269
6270 // FIXME: If we ever want to support general, address-constant expressions
6271 // as non-type template arguments, we should return the ExprResult here to
6272 // be interpreted by the caller.
6273 return NPV_NotNullPointer;
6274}
6275
6276/// Checks whether the given template argument is compatible with its
6277/// template parameter.
6279 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6280 Expr *Arg, QualType ArgType) {
6281 bool ObjCLifetimeConversion;
6282 if (ParamType->isPointerType() &&
6283 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6284 S.IsQualificationConversion(ArgType, ParamType, false,
6285 ObjCLifetimeConversion)) {
6286 // For pointer-to-object types, qualification conversions are
6287 // permitted.
6288 } else {
6289 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6290 if (!ParamRef->getPointeeType()->isFunctionType()) {
6291 // C++ [temp.arg.nontype]p5b3:
6292 // For a non-type template-parameter of type reference to
6293 // object, no conversions apply. The type referred to by the
6294 // reference may be more cv-qualified than the (otherwise
6295 // identical) type of the template- argument. The
6296 // template-parameter is bound directly to the
6297 // template-argument, which shall be an lvalue.
6298
6299 // FIXME: Other qualifiers?
6300 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6301 unsigned ArgQuals = ArgType.getCVRQualifiers();
6302
6303 if ((ParamQuals | ArgQuals) != ParamQuals) {
6304 S.Diag(Arg->getBeginLoc(),
6305 diag::err_template_arg_ref_bind_ignores_quals)
6306 << ParamType << Arg->getType() << Arg->getSourceRange();
6308 return true;
6309 }
6310 }
6311 }
6312
6313 // At this point, the template argument refers to an object or
6314 // function with external linkage. We now need to check whether the
6315 // argument and parameter types are compatible.
6316 if (!S.Context.hasSameUnqualifiedType(ArgType,
6317 ParamType.getNonReferenceType())) {
6318 // We can't perform this conversion or binding.
6319 if (ParamType->isReferenceType())
6320 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6321 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6322 else
6323 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6324 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6326 return true;
6327 }
6328 }
6329
6330 return false;
6331}
6332
6333/// Checks whether the given template argument is the address
6334/// of an object or function according to C++ [temp.arg.nontype]p1.
6336 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6337 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6338 bool Invalid = false;
6339 Expr *Arg = ArgIn;
6340 QualType ArgType = Arg->getType();
6341
6342 bool AddressTaken = false;
6343 SourceLocation AddrOpLoc;
6344 if (S.getLangOpts().MicrosoftExt) {
6345 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6346 // dereference and address-of operators.
6347 Arg = Arg->IgnoreParenCasts();
6348
6349 bool ExtWarnMSTemplateArg = false;
6350 UnaryOperatorKind FirstOpKind;
6351 SourceLocation FirstOpLoc;
6352 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6353 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6354 if (UnOpKind == UO_Deref)
6355 ExtWarnMSTemplateArg = true;
6356 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6357 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6358 if (!AddrOpLoc.isValid()) {
6359 FirstOpKind = UnOpKind;
6360 FirstOpLoc = UnOp->getOperatorLoc();
6361 }
6362 } else
6363 break;
6364 }
6365 if (FirstOpLoc.isValid()) {
6366 if (ExtWarnMSTemplateArg)
6367 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6368 << ArgIn->getSourceRange();
6369
6370 if (FirstOpKind == UO_AddrOf)
6371 AddressTaken = true;
6372 else if (Arg->getType()->isPointerType()) {
6373 // We cannot let pointers get dereferenced here, that is obviously not a
6374 // constant expression.
6375 assert(FirstOpKind == UO_Deref);
6376 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6377 << Arg->getSourceRange();
6378 }
6379 }
6380 } else {
6381 // See through any implicit casts we added to fix the type.
6382 Arg = Arg->IgnoreImpCasts();
6383
6384 // C++ [temp.arg.nontype]p1:
6385 //
6386 // A template-argument for a non-type, non-template
6387 // template-parameter shall be one of: [...]
6388 //
6389 // -- the address of an object or function with external
6390 // linkage, including function templates and function
6391 // template-ids but excluding non-static class members,
6392 // expressed as & id-expression where the & is optional if
6393 // the name refers to a function or array, or if the
6394 // corresponding template-parameter is a reference; or
6395
6396 // In C++98/03 mode, give an extension warning on any extra parentheses.
6397 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6398 bool ExtraParens = false;
6399 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6400 if (!Invalid && !ExtraParens) {
6401 S.Diag(Arg->getBeginLoc(),
6402 S.getLangOpts().CPlusPlus11
6403 ? diag::warn_cxx98_compat_template_arg_extra_parens
6404 : diag::ext_template_arg_extra_parens)
6405 << Arg->getSourceRange();
6406 ExtraParens = true;
6407 }
6408
6409 Arg = Parens->getSubExpr();
6410 }
6411
6412 while (SubstNonTypeTemplateParmExpr *subst =
6413 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6414 Arg = subst->getReplacement()->IgnoreImpCasts();
6415
6416 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6417 if (UnOp->getOpcode() == UO_AddrOf) {
6418 Arg = UnOp->getSubExpr();
6419 AddressTaken = true;
6420 AddrOpLoc = UnOp->getOperatorLoc();
6421 }
6422 }
6423
6424 while (SubstNonTypeTemplateParmExpr *subst =
6425 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6426 Arg = subst->getReplacement()->IgnoreImpCasts();
6427 }
6428
6429 ValueDecl *Entity = nullptr;
6430 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6431 Entity = DRE->getDecl();
6432 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6433 Entity = CUE->getGuidDecl();
6434
6435 // If our parameter has pointer type, check for a null template value.
6436 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6437 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6438 Entity)) {
6439 case NPV_NullPointer:
6440 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6441 SugaredConverted = TemplateArgument(ParamType,
6442 /*isNullPtr=*/true);
6443 CanonicalConverted =
6445 /*isNullPtr=*/true);
6446 return false;
6447
6448 case NPV_Error:
6449 return true;
6450
6451 case NPV_NotNullPointer:
6452 break;
6453 }
6454 }
6455
6456 // Stop checking the precise nature of the argument if it is value dependent,
6457 // it should be checked when instantiated.
6458 if (Arg->isValueDependent()) {
6459 SugaredConverted = TemplateArgument(ArgIn);
6460 CanonicalConverted =
6461 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6462 return false;
6463 }
6464
6465 if (!Entity) {
6466 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6467 << Arg->getSourceRange();
6469 return true;
6470 }
6471
6472 // Cannot refer to non-static data members
6473 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6474 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6475 << Entity << Arg->getSourceRange();
6477 return true;
6478 }
6479
6480 // Cannot refer to non-static member functions
6481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6482 if (!Method->isStatic()) {
6483 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6484 << Method << Arg->getSourceRange();
6486 return true;
6487 }
6488 }
6489
6490 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6491 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6492 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6493
6494 // A non-type template argument must refer to an object or function.
6495 if (!Func && !Var && !Guid) {
6496 // We found something, but we don't know specifically what it is.
6497 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6498 << Arg->getSourceRange();
6499 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6500 return true;
6501 }
6502
6503 // Address / reference template args must have external linkage in C++98.
6504 if (Entity->getFormalLinkage() == Linkage::Internal) {
6505 S.Diag(Arg->getBeginLoc(),
6506 S.getLangOpts().CPlusPlus11
6507 ? diag::warn_cxx98_compat_template_arg_object_internal
6508 : diag::ext_template_arg_object_internal)
6509 << !Func << Entity << Arg->getSourceRange();
6510 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6511 << !Func;
6512 } else if (!Entity->hasLinkage()) {
6513 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6514 << !Func << Entity << Arg->getSourceRange();
6515 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6516 << !Func;
6517 return true;
6518 }
6519
6520 if (Var) {
6521 // A value of reference type is not an object.
6522 if (Var->getType()->isReferenceType()) {
6523 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6524 << Var->getType() << Arg->getSourceRange();
6526 return true;
6527 }
6528
6529 // A template argument must have static storage duration.
6530 if (Var->getTLSKind()) {
6531 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6532 << Arg->getSourceRange();
6533 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6534 return true;
6535 }
6536 }
6537
6538 if (AddressTaken && ParamType->isReferenceType()) {
6539 // If we originally had an address-of operator, but the
6540 // parameter has reference type, complain and (if things look
6541 // like they will work) drop the address-of operator.
6542 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6543 ParamType.getNonReferenceType())) {
6544 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6545 << ParamType;
6547 return true;
6548 }
6549
6550 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6551 << ParamType
6552 << FixItHint::CreateRemoval(AddrOpLoc);
6554
6555 ArgType = Entity->getType();
6556 }
6557
6558 // If the template parameter has pointer type, either we must have taken the
6559 // address or the argument must decay to a pointer.
6560 if (!AddressTaken && ParamType->isPointerType()) {
6561 if (Func) {
6562 // Function-to-pointer decay.
6563 ArgType = S.Context.getPointerType(Func->getType());
6564 } else if (Entity->getType()->isArrayType()) {
6565 // Array-to-pointer decay.
6566 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6567 } else {
6568 // If the template parameter has pointer type but the address of
6569 // this object was not taken, complain and (possibly) recover by
6570 // taking the address of the entity.
6571 ArgType = S.Context.getPointerType(Entity->getType());
6572 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6573 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6574 << ParamType;
6576 return true;
6577 }
6578
6579 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6580 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6581
6583 }
6584 }
6585
6586 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6587 Arg, ArgType))
6588 return true;
6589
6590 // Create the template argument.
6591 SugaredConverted = TemplateArgument(Entity, ParamType);
6592 CanonicalConverted =
6593 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6594 S.Context.getCanonicalType(ParamType));
6595 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6596 return false;
6597}
6598
6599/// Checks whether the given template argument is a pointer to
6600/// member constant according to C++ [temp.arg.nontype]p1.
6601static bool
6603 QualType ParamType, Expr *&ResultArg,
6604 TemplateArgument &SugaredConverted,
6605 TemplateArgument &CanonicalConverted) {
6606 bool Invalid = false;
6607
6608 Expr *Arg = ResultArg;
6609 bool ObjCLifetimeConversion;
6610
6611 // C++ [temp.arg.nontype]p1:
6612 //
6613 // A template-argument for a non-type, non-template
6614 // template-parameter shall be one of: [...]
6615 //
6616 // -- a pointer to member expressed as described in 5.3.1.
6617 DeclRefExpr *DRE = nullptr;
6618
6619 // In C++98/03 mode, give an extension warning on any extra parentheses.
6620 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6621 bool ExtraParens = false;
6622 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6623 if (!Invalid && !ExtraParens) {
6624 S.Diag(Arg->getBeginLoc(),
6625 S.getLangOpts().CPlusPlus11
6626 ? diag::warn_cxx98_compat_template_arg_extra_parens
6627 : diag::ext_template_arg_extra_parens)
6628 << Arg->getSourceRange();
6629 ExtraParens = true;
6630 }
6631
6632 Arg = Parens->getSubExpr();
6633 }
6634
6635 while (SubstNonTypeTemplateParmExpr *subst =
6636 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6637 Arg = subst->getReplacement()->IgnoreImpCasts();
6638
6639 // A pointer-to-member constant written &Class::member.
6640 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6641 if (UnOp->getOpcode() == UO_AddrOf) {
6642 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6643 if (DRE && !DRE->getQualifier())
6644 DRE = nullptr;
6645 }
6646 }
6647 // A constant of pointer-to-member type.
6648 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6649 ValueDecl *VD = DRE->getDecl();
6650 if (VD->getType()->isMemberPointerType()) {
6651 if (isa<NonTypeTemplateParmDecl>(VD)) {
6652 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6653 SugaredConverted = TemplateArgument(Arg);
6654 CanonicalConverted =
6655 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6656 } else {
6657 SugaredConverted = TemplateArgument(VD, ParamType);
6658 CanonicalConverted =
6659 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6660 S.Context.getCanonicalType(ParamType));
6661 }
6662 return Invalid;
6663 }
6664 }
6665
6666 DRE = nullptr;
6667 }
6668
6669 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6670
6671 // Check for a null pointer value.
6672 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6673 Entity)) {
6674 case NPV_Error:
6675 return true;
6676 case NPV_NullPointer:
6677 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6678 SugaredConverted = TemplateArgument(ParamType,
6679 /*isNullPtr*/ true);
6680 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6681 /*isNullPtr*/ true);
6682 return false;
6683 case NPV_NotNullPointer:
6684 break;
6685 }
6686
6687 if (S.IsQualificationConversion(ResultArg->getType(),
6688 ParamType.getNonReferenceType(), false,
6689 ObjCLifetimeConversion)) {
6690 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6691 ResultArg->getValueKind())
6692 .get();
6693 } else if (!S.Context.hasSameUnqualifiedType(
6694 ResultArg->getType(), ParamType.getNonReferenceType())) {
6695 // We can't perform this conversion.
6696 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6697 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6699 return true;
6700 }
6701
6702 if (!DRE)
6703 return S.Diag(Arg->getBeginLoc(),
6704 diag::err_template_arg_not_pointer_to_member_form)
6705 << Arg->getSourceRange();
6706
6707 if (isa<FieldDecl>(DRE->getDecl()) ||
6708 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6709 isa<CXXMethodDecl>(DRE->getDecl())) {
6710 assert((isa<FieldDecl>(DRE->getDecl()) ||
6711 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6712 cast<CXXMethodDecl>(DRE->getDecl())
6713 ->isImplicitObjectMemberFunction()) &&
6714 "Only non-static member pointers can make it here");
6715
6716 // Okay: this is the address of a non-static member, and therefore
6717 // a member pointer constant.
6718 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6719 SugaredConverted = TemplateArgument(Arg);
6720 CanonicalConverted =
6721 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6722 } else {
6723 ValueDecl *D = DRE->getDecl();
6724 SugaredConverted = TemplateArgument(D, ParamType);
6725 CanonicalConverted =
6726 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6727 S.Context.getCanonicalType(ParamType));
6728 }
6729 return Invalid;
6730 }
6731
6732 // We found something else, but we don't know specifically what it is.
6733 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6734 << Arg->getSourceRange();
6735 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6736 return true;
6737}
6738
6740 QualType ParamType, Expr *Arg,
6741 TemplateArgument &SugaredConverted,
6742 TemplateArgument &CanonicalConverted,
6744 SourceLocation StartLoc = Arg->getBeginLoc();
6745
6746 // If the parameter type somehow involves auto, deduce the type now.
6747 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6748 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6749 // During template argument deduction, we allow 'decltype(auto)' to
6750 // match an arbitrary dependent argument.
6751 // FIXME: The language rules don't say what happens in this case.
6752 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6753 // expression is merely instantiation-dependent; is this enough?
6754 if (Arg->isTypeDependent()) {
6755 auto *AT = dyn_cast<AutoType>(DeducedT);
6756 if (AT && AT->isDecltypeAuto()) {
6757 SugaredConverted = TemplateArgument(Arg);
6758 CanonicalConverted = TemplateArgument(
6759 Context.getCanonicalTemplateArgument(SugaredConverted));
6760 return Arg;
6761 }
6762 }
6763
6764 // When checking a deduced template argument, deduce from its type even if
6765 // the type is dependent, in order to check the types of non-type template
6766 // arguments line up properly in partial ordering.
6767 Expr *DeductionArg = Arg;
6768 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6769 DeductionArg = PE->getPattern();
6770 TypeSourceInfo *TSI =
6771 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6772 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6773 InitializedEntity Entity =
6776 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6777 Expr *Inits[1] = {DeductionArg};
6778 ParamType =
6779 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6780 if (ParamType.isNull())
6781 return ExprError();
6782 } else {
6783 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6784 Param->getDepth() + 1);
6785 ParamType = QualType();
6787 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6788 /*DependentDeduction=*/true,
6789 // We do not check constraints right now because the
6790 // immediately-declared constraint of the auto type is
6791 // also an associated constraint, and will be checked
6792 // along with the other associated constraints after
6793 // checking the template argument list.
6794 /*IgnoreConstraints=*/true);
6796 if (ParamType.isNull())
6797 return ExprError();
6799 Diag(Arg->getExprLoc(),
6800 diag::err_non_type_template_parm_type_deduction_failure)
6801 << Param->getDeclName() << Param->getType() << Arg->getType()
6802 << Arg->getSourceRange();
6804 return ExprError();
6805 }
6806 }
6807 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6808 // an error. The error message normally references the parameter
6809 // declaration, but here we'll pass the argument location because that's
6810 // where the parameter type is deduced.
6811 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6812 if (ParamType.isNull()) {
6814 return ExprError();
6815 }
6816 }
6817
6818 // We should have already dropped all cv-qualifiers by now.
6819 assert(!ParamType.hasQualifiers() &&
6820 "non-type template parameter type cannot be qualified");
6821
6822 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6823 if (CTAK == CTAK_Deduced &&
6824 (ParamType->isReferenceType()
6826 Arg->getType())
6827 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6828 // FIXME: If either type is dependent, we skip the check. This isn't
6829 // correct, since during deduction we're supposed to have replaced each
6830 // template parameter with some unique (non-dependent) placeholder.
6831 // FIXME: If the argument type contains 'auto', we carry on and fail the
6832 // type check in order to force specific types to be more specialized than
6833 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6834 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6835 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6836 !Arg->getType()->getContainedDeducedType()) {
6837 SugaredConverted = TemplateArgument(Arg);
6838 CanonicalConverted = TemplateArgument(
6839 Context.getCanonicalTemplateArgument(SugaredConverted));
6840 return Arg;
6841 }
6842 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6843 // we should actually be checking the type of the template argument in P,
6844 // not the type of the template argument deduced from A, against the
6845 // template parameter type.
6846 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6847 << Arg->getType()
6848 << ParamType.getUnqualifiedType();
6850 return ExprError();
6851 }
6852
6853 // If either the parameter has a dependent type or the argument is
6854 // type-dependent, there's nothing we can check now.
6855 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6856 // Force the argument to the type of the parameter to maintain invariants.
6857 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6858 if (PE)
6859 Arg = PE->getPattern();
6861 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6862 ParamType->isLValueReferenceType() ? VK_LValue
6863 : ParamType->isRValueReferenceType() ? VK_XValue
6864 : VK_PRValue);
6865 if (E.isInvalid())
6866 return ExprError();
6867 if (PE) {
6868 // Recreate a pack expansion if we unwrapped one.
6869 E = new (Context)
6870 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6871 PE->getNumExpansions());
6872 }
6873 SugaredConverted = TemplateArgument(E.get());
6874 CanonicalConverted = TemplateArgument(
6875 Context.getCanonicalTemplateArgument(SugaredConverted));
6876 return E;
6877 }
6878
6879 QualType CanonParamType = Context.getCanonicalType(ParamType);
6880 // Avoid making a copy when initializing a template parameter of class type
6881 // from a template parameter object of the same type. This is going beyond
6882 // the standard, but is required for soundness: in
6883 // template<A a> struct X { X *p; X<a> *q; };
6884 // ... we need p and q to have the same type.
6885 //
6886 // Similarly, don't inject a call to a copy constructor when initializing
6887 // from a template parameter of the same type.
6888 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6889 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6890 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6891 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6892 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6893
6894 SugaredConverted = TemplateArgument(TPO, ParamType);
6895 CanonicalConverted =
6896 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6897 return Arg;
6898 }
6899 if (isa<NonTypeTemplateParmDecl>(ND)) {
6900 SugaredConverted = TemplateArgument(Arg);
6901 CanonicalConverted =
6902 Context.getCanonicalTemplateArgument(SugaredConverted);
6903 return Arg;
6904 }
6905 }
6906
6907 // The initialization of the parameter from the argument is
6908 // a constant-evaluated context.
6911
6912 bool IsConvertedConstantExpression = true;
6913 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6915 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6916 Expr *Inits[1] = {Arg};
6917 InitializedEntity Entity =
6919 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6920 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6921 if (Result.isInvalid() || !Result.get())
6922 return ExprError();
6924 if (Result.isInvalid() || !Result.get())
6925 return ExprError();
6926 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6927 /*DiscardedValue=*/false,
6928 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6929 .get();
6930 IsConvertedConstantExpression = false;
6931 }
6932
6933 if (getLangOpts().CPlusPlus17) {
6934 // C++17 [temp.arg.nontype]p1:
6935 // A template-argument for a non-type template parameter shall be
6936 // a converted constant expression of the type of the template-parameter.
6937 APValue Value;
6938 ExprResult ArgResult;
6939 if (IsConvertedConstantExpression) {
6940 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6941 CCEK_TemplateArg, Param);
6942 if (ArgResult.isInvalid())
6943 return ExprError();
6944 } else {
6945 ArgResult = Arg;
6946 }
6947
6948 // For a value-dependent argument, CheckConvertedConstantExpression is
6949 // permitted (and expected) to be unable to determine a value.
6950 if (ArgResult.get()->isValueDependent()) {
6951 SugaredConverted = TemplateArgument(ArgResult.get());
6952 CanonicalConverted =
6953 Context.getCanonicalTemplateArgument(SugaredConverted);
6954 return ArgResult;
6955 }
6956
6957 APValue PreNarrowingValue;
6959 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6960 false, PreNarrowingValue);
6961 if (ArgResult.isInvalid())
6962 return ExprError();
6963
6964 if (Value.isLValue()) {
6965 APValue::LValueBase Base = Value.getLValueBase();
6966 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6967 // For a non-type template-parameter of pointer or reference type,
6968 // the value of the constant expression shall not refer to
6969 assert(ParamType->isPointerOrReferenceType() ||
6970 ParamType->isNullPtrType());
6971 // -- a temporary object
6972 // -- a string literal
6973 // -- the result of a typeid expression, or
6974 // -- a predefined __func__ variable
6975 if (Base &&
6976 (!VD ||
6977 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6978 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6979 << Arg->getSourceRange();
6980 return ExprError();
6981 }
6982
6983 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6984 VD->getType()->isArrayType() &&
6985 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6986 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6987 SugaredConverted = TemplateArgument(VD, ParamType);
6988 CanonicalConverted = TemplateArgument(
6989 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6990 return ArgResult.get();
6991 }
6992
6993 // -- a subobject [until C++20]
6994 if (!getLangOpts().CPlusPlus20) {
6995 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6996 Value.isLValueOnePastTheEnd()) {
6997 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6998 << Value.getAsString(Context, ParamType);
6999 return ExprError();
7000 }
7001 assert((VD || !ParamType->isReferenceType()) &&
7002 "null reference should not be a constant expression");
7003 assert((!VD || !ParamType->isNullPtrType()) &&
7004 "non-null value of type nullptr_t?");
7005 }
7006 }
7007
7008 if (Value.isAddrLabelDiff())
7009 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7010
7011 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7012 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
7013 return ArgResult.get();
7014 }
7015
7016 // C++ [temp.arg.nontype]p5:
7017 // The following conversions are performed on each expression used
7018 // as a non-type template-argument. If a non-type
7019 // template-argument cannot be converted to the type of the
7020 // corresponding template-parameter then the program is
7021 // ill-formed.
7022 if (ParamType->isIntegralOrEnumerationType()) {
7023 // C++11:
7024 // -- for a non-type template-parameter of integral or
7025 // enumeration type, conversions permitted in a converted
7026 // constant expression are applied.
7027 //
7028 // C++98:
7029 // -- for a non-type template-parameter of integral or
7030 // enumeration type, integral promotions (4.5) and integral
7031 // conversions (4.7) are applied.
7032
7033 if (getLangOpts().CPlusPlus11) {
7034 // C++ [temp.arg.nontype]p1:
7035 // A template-argument for a non-type, non-template template-parameter
7036 // shall be one of:
7037 //
7038 // -- for a non-type template-parameter of integral or enumeration
7039 // type, a converted constant expression of the type of the
7040 // template-parameter; or
7041 llvm::APSInt Value;
7042 ExprResult ArgResult =
7045 if (ArgResult.isInvalid())
7046 return ExprError();
7047
7048 // We can't check arbitrary value-dependent arguments.
7049 if (ArgResult.get()->isValueDependent()) {
7050 SugaredConverted = TemplateArgument(ArgResult.get());
7051 CanonicalConverted =
7052 Context.getCanonicalTemplateArgument(SugaredConverted);
7053 return ArgResult;
7054 }
7055
7056 // Widen the argument value to sizeof(parameter type). This is almost
7057 // always a no-op, except when the parameter type is bool. In
7058 // that case, this may extend the argument from 1 bit to 8 bits.
7059 QualType IntegerType = ParamType;
7060 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7061 IntegerType = Enum->getDecl()->getIntegerType();
7062 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7063 ? Context.getIntWidth(IntegerType)
7064 : Context.getTypeSize(IntegerType));
7065
7066 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7067 CanonicalConverted =
7069 return ArgResult;
7070 }
7071
7072 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7073 if (ArgResult.isInvalid())
7074 return ExprError();
7075 Arg = ArgResult.get();
7076
7077 QualType ArgType = Arg->getType();
7078
7079 // C++ [temp.arg.nontype]p1:
7080 // A template-argument for a non-type, non-template
7081 // template-parameter shall be one of:
7082 //
7083 // -- an integral constant-expression of integral or enumeration
7084 // type; or
7085 // -- the name of a non-type template-parameter; or
7086 llvm::APSInt Value;
7087 if (!ArgType->isIntegralOrEnumerationType()) {
7088 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7089 << ArgType << Arg->getSourceRange();
7091 return ExprError();
7092 } else if (!Arg->isValueDependent()) {
7093 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7094 QualType T;
7095
7096 public:
7097 TmplArgICEDiagnoser(QualType T) : T(T) { }
7098
7099 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7100 SourceLocation Loc) override {
7101 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7102 }
7103 } Diagnoser(ArgType);
7104
7105 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7106 if (!Arg)
7107 return ExprError();
7108 }
7109
7110 // From here on out, all we care about is the unqualified form
7111 // of the argument type.
7112 ArgType = ArgType.getUnqualifiedType();
7113
7114 // Try to convert the argument to the parameter's type.
7115 if (Context.hasSameType(ParamType, ArgType)) {
7116 // Okay: no conversion necessary
7117 } else if (ParamType->isBooleanType()) {
7118 // This is an integral-to-boolean conversion.
7119 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7120 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7121 !ParamType->isEnumeralType()) {
7122 // This is an integral promotion or conversion.
7123 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7124 } else {
7125 // We can't perform this conversion.
7126 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7127 << Arg->getType() << ParamType << Arg->getSourceRange();
7129 return ExprError();
7130 }
7131
7132 // Add the value of this argument to the list of converted
7133 // arguments. We use the bitwidth and signedness of the template
7134 // parameter.
7135 if (Arg->isValueDependent()) {
7136 // The argument is value-dependent. Create a new
7137 // TemplateArgument with the converted expression.
7138 SugaredConverted = TemplateArgument(Arg);
7139 CanonicalConverted =
7140 Context.getCanonicalTemplateArgument(SugaredConverted);
7141 return Arg;
7142 }
7143
7144 QualType IntegerType = ParamType;
7145 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7146 IntegerType = Enum->getDecl()->getIntegerType();
7147 }
7148
7149 if (ParamType->isBooleanType()) {
7150 // Value must be zero or one.
7151 Value = Value != 0;
7152 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7153 if (Value.getBitWidth() != AllowedBits)
7154 Value = Value.extOrTrunc(AllowedBits);
7155 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7156 } else {
7157 llvm::APSInt OldValue = Value;
7158
7159 // Coerce the template argument's value to the value it will have
7160 // based on the template parameter's type.
7161 unsigned AllowedBits = IntegerType->isBitIntType()
7162 ? Context.getIntWidth(IntegerType)
7163 : Context.getTypeSize(IntegerType);
7164 if (Value.getBitWidth() != AllowedBits)
7165 Value = Value.extOrTrunc(AllowedBits);
7166 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7167
7168 // Complain if an unsigned parameter received a negative value.
7169 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7170 (OldValue.isSigned() && OldValue.isNegative())) {
7171 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7172 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7173 << Arg->getSourceRange();
7175 }
7176
7177 // Complain if we overflowed the template parameter's type.
7178 unsigned RequiredBits;
7179 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7180 RequiredBits = OldValue.getActiveBits();
7181 else if (OldValue.isUnsigned())
7182 RequiredBits = OldValue.getActiveBits() + 1;
7183 else
7184 RequiredBits = OldValue.getSignificantBits();
7185 if (RequiredBits > AllowedBits) {
7186 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7187 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7188 << Arg->getSourceRange();
7190 }
7191 }
7192
7193 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7194 SugaredConverted = TemplateArgument(Context, Value, T);
7195 CanonicalConverted =
7197 return Arg;
7198 }
7199
7200 QualType ArgType = Arg->getType();
7201 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7202
7203 // Handle pointer-to-function, reference-to-function, and
7204 // pointer-to-member-function all in (roughly) the same way.
7205 if (// -- For a non-type template-parameter of type pointer to
7206 // function, only the function-to-pointer conversion (4.3) is
7207 // applied. If the template-argument represents a set of
7208 // overloaded functions (or a pointer to such), the matching
7209 // function is selected from the set (13.4).
7210 (ParamType->isPointerType() &&
7211 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7212 // -- For a non-type template-parameter of type reference to
7213 // function, no conversions apply. If the template-argument
7214 // represents a set of overloaded functions, the matching
7215 // function is selected from the set (13.4).
7216 (ParamType->isReferenceType() &&
7217 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7218 // -- For a non-type template-parameter of type pointer to
7219 // member function, no conversions apply. If the
7220 // template-argument represents a set of overloaded member
7221 // functions, the matching member function is selected from
7222 // the set (13.4).
7223 (ParamType->isMemberPointerType() &&
7224 ParamType->castAs<MemberPointerType>()->getPointeeType()
7225 ->isFunctionType())) {
7226
7227 if (Arg->getType() == Context.OverloadTy) {
7228 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7229 true,
7230 FoundResult)) {
7231 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7232 return ExprError();
7233
7234 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7235 if (Res.isInvalid())
7236 return ExprError();
7237 Arg = Res.get();
7238 ArgType = Arg->getType();
7239 } else
7240 return ExprError();
7241 }
7242
7243 if (!ParamType->isMemberPointerType()) {
7245 *this, Param, ParamType, Arg, SugaredConverted,
7246 CanonicalConverted))
7247 return ExprError();
7248 return Arg;
7249 }
7250
7252 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7253 return ExprError();
7254 return Arg;
7255 }
7256
7257 if (ParamType->isPointerType()) {
7258 // -- for a non-type template-parameter of type pointer to
7259 // object, qualification conversions (4.4) and the
7260 // array-to-pointer conversion (4.2) are applied.
7261 // C++0x also allows a value of std::nullptr_t.
7262 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7263 "Only object pointers allowed here");
7264
7266 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7267 return ExprError();
7268 return Arg;
7269 }
7270
7271 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7272 // -- For a non-type template-parameter of type reference to
7273 // object, no conversions apply. The type referred to by the
7274 // reference may be more cv-qualified than the (otherwise
7275 // identical) type of the template-argument. The
7276 // template-parameter is bound directly to the
7277 // template-argument, which must be an lvalue.
7278 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7279 "Only object references allowed here");
7280
7281 if (Arg->getType() == Context.OverloadTy) {
7283 ParamRefType->getPointeeType(),
7284 true,
7285 FoundResult)) {
7286 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7287 return ExprError();
7288 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7289 if (Res.isInvalid())
7290 return ExprError();
7291 Arg = Res.get();
7292 ArgType = Arg->getType();
7293 } else
7294 return ExprError();
7295 }
7296
7298 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7299 return ExprError();
7300 return Arg;
7301 }
7302
7303 // Deal with parameters of type std::nullptr_t.
7304 if (ParamType->isNullPtrType()) {
7305 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7306 SugaredConverted = TemplateArgument(Arg);
7307 CanonicalConverted =
7308 Context.getCanonicalTemplateArgument(SugaredConverted);
7309 return Arg;
7310 }
7311
7312 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7313 case NPV_NotNullPointer:
7314 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7315 << Arg->getType() << ParamType;
7317 return ExprError();
7318
7319 case NPV_Error:
7320 return ExprError();
7321
7322 case NPV_NullPointer:
7323 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7324 SugaredConverted = TemplateArgument(ParamType,
7325 /*isNullPtr=*/true);
7326 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7327 /*isNullPtr=*/true);
7328 return Arg;
7329 }
7330 }
7331
7332 // -- For a non-type template-parameter of type pointer to data
7333 // member, qualification conversions (4.4) are applied.
7334 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7335
7337 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7338 return ExprError();
7339 return Arg;
7340}
7341
7345
7349 bool *MatchedPackOnParmToNonPackOnArg) {
7351 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7352 if (!Template) {
7353 // Any dependent template name is fine.
7354 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7355 return false;
7356 }
7357
7358 if (Template->isInvalidDecl())
7359 return true;
7360
7361 // C++0x [temp.arg.template]p1:
7362 // A template-argument for a template template-parameter shall be
7363 // the name of a class template or an alias template, expressed as an
7364 // id-expression. When the template-argument names a class template, only
7365 // primary class templates are considered when matching the
7366 // template template argument with the corresponding parameter;
7367 // partial specializations are not considered even if their
7368 // parameter lists match that of the template template parameter.
7369 //
7370 // Note that we also allow template template parameters here, which
7371 // will happen when we are dealing with, e.g., class template
7372 // partial specializations.
7373 if (!isa<ClassTemplateDecl>(Template) &&
7374 !isa<TemplateTemplateParmDecl>(Template) &&
7375 !isa<TypeAliasTemplateDecl>(Template) &&
7376 !isa<BuiltinTemplateDecl>(Template)) {
7377 assert(isa<FunctionTemplateDecl>(Template) &&
7378 "Only function templates are possible here");
7379 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7380 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7381 << Template;
7382 }
7383
7384 if (!getLangOpts().RelaxedTemplateTemplateArgs)
7386 Template->getTemplateParameters(), Params, /*Complain=*/true,
7388
7389 // C++1z [temp.arg.template]p3: (DR 150)
7390 // A template-argument matches a template template-parameter P when P
7391 // is at least as specialized as the template-argument A.
7393 Params, Param, Template, DefaultArgs, Arg.getLocation(),
7394 PartialOrdering, MatchedPackOnParmToNonPackOnArg))
7395 return true;
7396 // P2113
7397 // C++20[temp.func.order]p2
7398 // [...] If both deductions succeed, the partial ordering selects the
7399 // more constrained template (if one exists) as determined below.
7400 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7401 Params->getAssociatedConstraints(ParamsAC);
7402 // C++20[temp.arg.template]p3
7403 // [...] In this comparison, if P is unconstrained, the constraints on A
7404 // are not considered.
7405 if (ParamsAC.empty())
7406 return false;
7407
7408 Template->getAssociatedConstraints(TemplateAC);
7409
7410 bool IsParamAtLeastAsConstrained;
7411 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7412 IsParamAtLeastAsConstrained))
7413 return true;
7414 if (!IsParamAtLeastAsConstrained) {
7415 Diag(Arg.getLocation(),
7416 diag::err_template_template_parameter_not_at_least_as_constrained)
7417 << Template << Param << Arg.getSourceRange();
7418 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7419 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;
7420 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7421 TemplateAC);
7422 return true;
7423 }
7424 return false;
7425}
7426
7428 unsigned HereDiagID,
7429 unsigned ExternalDiagID) {
7430 if (Decl.getLocation().isValid())
7431 return S.Diag(Decl.getLocation(), HereDiagID);
7432
7433 SmallString<128> Str;
7434 llvm::raw_svector_ostream Out(Str);
7436 PP.TerseOutput = 1;
7437 Decl.print(Out, PP);
7438 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7439}
7440
7442 std::optional<SourceRange> ParamRange) {
7444 noteLocation(*this, Decl, diag::note_template_decl_here,
7445 diag::note_template_decl_external);
7446 if (ParamRange && ParamRange->isValid()) {
7447 assert(Decl.getLocation().isValid() &&
7448 "Parameter range has location when Decl does not");
7449 DB << *ParamRange;
7450 }
7451}
7452
7454 noteLocation(*this, Decl, diag::note_template_param_here,
7455 diag::note_template_param_external);
7456}
7457
7459 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7461 // C++ [temp.param]p8:
7462 //
7463 // A non-type template-parameter of type "array of T" or
7464 // "function returning T" is adjusted to be of type "pointer to
7465 // T" or "pointer to function returning T", respectively.
7466 if (ParamType->isArrayType())
7467 ParamType = Context.getArrayDecayedType(ParamType);
7468 else if (ParamType->isFunctionType())
7469 ParamType = Context.getPointerType(ParamType);
7470
7471 // For a NULL non-type template argument, return nullptr casted to the
7472 // parameter's type.
7473 if (Arg.getKind() == TemplateArgument::NullPtr) {
7474 return ImpCastExprToType(
7476 ParamType,
7477 ParamType->getAs<MemberPointerType>()
7478 ? CK_NullToMemberPointer
7479 : CK_NullToPointer);
7480 }
7481 assert(Arg.getKind() == TemplateArgument::Declaration &&
7482 "Only declaration template arguments permitted here");
7483
7484 ValueDecl *VD = Arg.getAsDecl();
7485
7486 CXXScopeSpec SS;
7487 if (ParamType->isMemberPointerType()) {
7488 // If this is a pointer to member, we need to use a qualified name to
7489 // form a suitable pointer-to-member constant.
7490 assert(VD->getDeclContext()->isRecord() &&
7491 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7492 isa<IndirectFieldDecl>(VD)));
7493 QualType ClassType
7494 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7495 NestedNameSpecifier *Qualifier
7496 = NestedNameSpecifier::Create(Context, nullptr, false,
7497 ClassType.getTypePtr());
7498 SS.MakeTrivial(Context, Qualifier, Loc);
7499 }
7500
7502 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7503 if (RefExpr.isInvalid())
7504 return ExprError();
7505
7506 // For a pointer, the argument declaration is the pointee. Take its address.
7507 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7508 if (ParamType->isPointerType() && !ElemT.isNull() &&
7509 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7510 // Decay an array argument if we want a pointer to its first element.
7511 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7512 if (RefExpr.isInvalid())
7513 return ExprError();
7514 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7515 // For any other pointer, take the address (or form a pointer-to-member).
7516 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7517 if (RefExpr.isInvalid())
7518 return ExprError();
7519 } else if (ParamType->isRecordType()) {
7520 assert(isa<TemplateParamObjectDecl>(VD) &&
7521 "arg for class template param not a template parameter object");
7522 // No conversions apply in this case.
7523 return RefExpr;
7524 } else {
7525 assert(ParamType->isReferenceType() &&
7526 "unexpected type for decl template argument");
7527 if (NonTypeTemplateParmDecl *NTTP =
7528 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7529 QualType TemplateParamType = NTTP->getType();
7530 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7531 if (AT && AT->isDecltypeAuto()) {
7533 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7534 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7535 /*PackIndex=*/std::nullopt,
7536 /*RefParam=*/true);
7537 }
7538 }
7539 }
7540
7541 // At this point we should have the right value category.
7542 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7543 "value kind mismatch for non-type template argument");
7544
7545 // The type of the template parameter can differ from the type of the
7546 // argument in various ways; convert it now if necessary.
7547 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7548 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7549 CastKind CK;
7550 QualType Ignored;
7551 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7552 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7553 CK = CK_NoOp;
7554 } else if (ParamType->isVoidPointerType() &&
7555 RefExpr.get()->getType()->isPointerType()) {
7556 CK = CK_BitCast;
7557 } else {
7558 // FIXME: Pointers to members can need conversion derived-to-base or
7559 // base-to-derived conversions. We currently don't retain enough
7560 // information to convert properly (we need to track a cast path or
7561 // subobject number in the template argument).
7562 llvm_unreachable(
7563 "unexpected conversion required for non-type template argument");
7564 }
7565 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7566 RefExpr.get()->getValueKind());
7567 }
7568
7569 return RefExpr;
7570}
7571
7572/// Construct a new expression that refers to the given
7573/// integral template argument with the given source-location
7574/// information.
7575///
7576/// This routine takes care of the mapping from an integral template
7577/// argument (which may have any integral type) to the appropriate
7578/// literal value.
7580 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7581 assert(OrigT->isIntegralOrEnumerationType());
7582
7583 // If this is an enum type that we're instantiating, we need to use an integer
7584 // type the same size as the enumerator. We don't want to build an
7585 // IntegerLiteral with enum type. The integer type of an enum type can be of
7586 // any integral type with C++11 enum classes, make sure we create the right
7587 // type of literal for it.
7588 QualType T = OrigT;
7589 if (const EnumType *ET = OrigT->getAs<EnumType>())
7590 T = ET->getDecl()->getIntegerType();
7591
7592 Expr *E;
7593 if (T->isAnyCharacterType()) {
7595 if (T->isWideCharType())
7597 else if (T->isChar8Type() && S.getLangOpts().Char8)
7599 else if (T->isChar16Type())
7601 else if (T->isChar32Type())
7603 else
7605
7606 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7607 } else if (T->isBooleanType()) {
7608 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7609 } else {
7610 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7611 }
7612
7613 if (OrigT->isEnumeralType()) {
7614 // FIXME: This is a hack. We need a better way to handle substituted
7615 // non-type template parameters.
7616 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7617 nullptr, S.CurFPFeatureOverrides(),
7619 Loc, Loc);
7620 }
7621
7622 return E;
7623}
7624
7626 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7627 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7628 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7629 ILE->setType(T);
7630 return ILE;
7631 };
7632
7633 switch (Val.getKind()) {
7635 // This cannot occur in a template argument at all.
7636 case APValue::Array:
7637 case APValue::Struct:
7638 case APValue::Union:
7639 // These can only occur within a template parameter object, which is
7640 // represented as a TemplateArgument::Declaration.
7641 llvm_unreachable("unexpected template argument value");
7642
7643 case APValue::Int:
7645 Loc);
7646
7647 case APValue::Float:
7648 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7649 T, Loc);
7650
7653 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7654 Val.getFixedPoint().getScale());
7655
7656 case APValue::ComplexInt: {
7657 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7659 S, ElemT, Val.getComplexIntReal(), Loc),
7661 S, ElemT, Val.getComplexIntImag(), Loc)});
7662 }
7663
7664 case APValue::ComplexFloat: {
7665 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7666 return MakeInitList(
7668 ElemT, Loc),
7670 ElemT, Loc)});
7671 }
7672
7673 case APValue::Vector: {
7674 QualType ElemT = T->castAs<VectorType>()->getElementType();
7676 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7678 S, ElemT, Val.getVectorElt(I), Loc));
7679 return MakeInitList(Elts);
7680 }
7681
7682 case APValue::None:
7684 llvm_unreachable("Unexpected APValue kind.");
7685 case APValue::LValue:
7687 // There isn't necessarily a valid equivalent source-level syntax for
7688 // these; in particular, a naive lowering might violate access control.
7689 // So for now we lower to a ConstantExpr holding the value, wrapped around
7690 // an OpaqueValueExpr.
7691 // FIXME: We should have a better representation for this.
7693 if (T->isReferenceType()) {
7694 T = T->getPointeeType();
7695 VK = VK_LValue;
7696 }
7697 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7698 return ConstantExpr::Create(S.Context, OVE, Val);
7699 }
7700 llvm_unreachable("Unhandled APValue::ValueKind enum");
7701}
7702
7706 switch (Arg.getKind()) {
7712 llvm_unreachable("not a non-type template argument");
7713
7715 return Arg.getAsExpr();
7716
7721
7724 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7725
7728 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7729 }
7730 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7731}
7732
7733/// Match two template parameters within template parameter lists.
7735 Sema &S, NamedDecl *New,
7736 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7737 const NamedDecl *OldInstFrom, bool Complain,
7739 // Check the actual kind (type, non-type, template).
7740 if (Old->getKind() != New->getKind()) {
7741 if (Complain) {
7742 unsigned NextDiag = diag::err_template_param_different_kind;
7743 if (TemplateArgLoc.isValid()) {
7744 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7745 NextDiag = diag::note_template_param_different_kind;
7746 }
7747 S.Diag(New->getLocation(), NextDiag)
7748 << (Kind != Sema::TPL_TemplateMatch);
7749 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7750 << (Kind != Sema::TPL_TemplateMatch);
7751 }
7752
7753 return false;
7754 }
7755
7756 // Check that both are parameter packs or neither are parameter packs.
7757 // However, if we are matching a template template argument to a
7758 // template template parameter, the template template parameter can have
7759 // a parameter pack where the template template argument does not.
7760 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7762 Old->isTemplateParameterPack())) {
7763 if (Complain) {
7764 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7765 if (TemplateArgLoc.isValid()) {
7766 S.Diag(TemplateArgLoc,
7767 diag::err_template_arg_template_params_mismatch);
7768 NextDiag = diag::note_template_parameter_pack_non_pack;
7769 }
7770
7771 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7772 : isa<NonTypeTemplateParmDecl>(New)? 1
7773 : 2;
7774 S.Diag(New->getLocation(), NextDiag)
7775 << ParamKind << New->isParameterPack();
7776 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7777 << ParamKind << Old->isParameterPack();
7778 }
7779
7780 return false;
7781 }
7782
7783 // For non-type template parameters, check the type of the parameter.
7784 if (NonTypeTemplateParmDecl *OldNTTP
7785 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7786 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7787
7788 // If we are matching a template template argument to a template
7789 // template parameter and one of the non-type template parameter types
7790 // is dependent, then we must wait until template instantiation time
7791 // to actually compare the arguments.
7793 (!OldNTTP->getType()->isDependentType() &&
7794 !NewNTTP->getType()->isDependentType())) {
7795 // C++20 [temp.over.link]p6:
7796 // Two [non-type] template-parameters are equivalent [if] they have
7797 // equivalent types ignoring the use of type-constraints for
7798 // placeholder types
7799 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7800 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7801 if (!S.Context.hasSameType(OldType, NewType)) {
7802 if (Complain) {
7803 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7804 if (TemplateArgLoc.isValid()) {
7805 S.Diag(TemplateArgLoc,
7806 diag::err_template_arg_template_params_mismatch);
7807 NextDiag = diag::note_template_nontype_parm_different_type;
7808 }
7809 S.Diag(NewNTTP->getLocation(), NextDiag)
7810 << NewNTTP->getType()
7811 << (Kind != Sema::TPL_TemplateMatch);
7812 S.Diag(OldNTTP->getLocation(),
7813 diag::note_template_nontype_parm_prev_declaration)
7814 << OldNTTP->getType();
7815 }
7816
7817 return false;
7818 }
7819 }
7820 }
7821 // For template template parameters, check the template parameter types.
7822 // The template parameter lists of template template
7823 // parameters must agree.
7824 else if (TemplateTemplateParmDecl *OldTTP =
7825 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7826 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7828 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7829 OldTTP->getTemplateParameters(), Complain,
7832 : Kind),
7833 TemplateArgLoc))
7834 return false;
7835 }
7836
7839 !isa<TemplateTemplateParmDecl>(Old)) {
7840 const Expr *NewC = nullptr, *OldC = nullptr;
7841
7842 if (isa<TemplateTypeParmDecl>(New)) {
7843 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7844 NewC = TC->getImmediatelyDeclaredConstraint();
7845 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7846 OldC = TC->getImmediatelyDeclaredConstraint();
7847 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7848 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7849 ->getPlaceholderTypeConstraint())
7850 NewC = E;
7851 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7852 ->getPlaceholderTypeConstraint())
7853 OldC = E;
7854 } else
7855 llvm_unreachable("unexpected template parameter type");
7856
7857 auto Diagnose = [&] {
7858 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7859 diag::err_template_different_type_constraint);
7860 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7861 diag::note_template_prev_declaration) << /*declaration*/0;
7862 };
7863
7864 if (!NewC != !OldC) {
7865 if (Complain)
7866 Diagnose();
7867 return false;
7868 }
7869
7870 if (NewC) {
7871 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7872 NewC)) {
7873 if (Complain)
7874 Diagnose();
7875 return false;
7876 }
7877 }
7878 }
7879
7880 return true;
7881}
7882
7883/// Diagnose a known arity mismatch when comparing template argument
7884/// lists.
7885static
7890 SourceLocation TemplateArgLoc) {
7891 unsigned NextDiag = diag::err_template_param_list_different_arity;
7892 if (TemplateArgLoc.isValid()) {
7893 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7894 NextDiag = diag::note_template_param_list_different_arity;
7895 }
7896 S.Diag(New->getTemplateLoc(), NextDiag)
7897 << (New->size() > Old->size())
7898 << (Kind != Sema::TPL_TemplateMatch)
7899 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7900 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7901 << (Kind != Sema::TPL_TemplateMatch)
7902 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7903}
7904
7906 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7907 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7908 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7909 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7910 if (Complain)
7911 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7912 TemplateArgLoc);
7913
7914 return false;
7915 }
7916
7917 // C++0x [temp.arg.template]p3:
7918 // A template-argument matches a template template-parameter (call it P)
7919 // when each of the template parameters in the template-parameter-list of
7920 // the template-argument's corresponding class template or alias template
7921 // (call it A) matches the corresponding template parameter in the
7922 // template-parameter-list of P. [...]
7923 TemplateParameterList::iterator NewParm = New->begin();
7924 TemplateParameterList::iterator NewParmEnd = New->end();
7925 for (TemplateParameterList::iterator OldParm = Old->begin(),
7926 OldParmEnd = Old->end();
7927 OldParm != OldParmEnd; ++OldParm) {
7929 !(*OldParm)->isTemplateParameterPack()) {
7930 if (NewParm == NewParmEnd) {
7931 if (Complain)
7932 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7933 TemplateArgLoc);
7934
7935 return false;
7936 }
7937
7938 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7939 OldInstFrom, Complain, Kind,
7940 TemplateArgLoc))
7941 return false;
7942
7943 ++NewParm;
7944 continue;
7945 }
7946
7947 // C++0x [temp.arg.template]p3:
7948 // [...] When P's template- parameter-list contains a template parameter
7949 // pack (14.5.3), the template parameter pack will match zero or more
7950 // template parameters or template parameter packs in the
7951 // template-parameter-list of A with the same type and form as the
7952 // template parameter pack in P (ignoring whether those template
7953 // parameters are template parameter packs).
7954 for (; NewParm != NewParmEnd; ++NewParm) {
7955 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7956 OldInstFrom, Complain, Kind,
7957 TemplateArgLoc))
7958 return false;
7959 }
7960 }
7961
7962 // Make sure we exhausted all of the arguments.
7963 if (NewParm != NewParmEnd) {
7964 if (Complain)
7965 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7966 TemplateArgLoc);
7967
7968 return false;
7969 }
7970
7973 const Expr *NewRC = New->getRequiresClause();
7974 const Expr *OldRC = Old->getRequiresClause();
7975
7976 auto Diagnose = [&] {
7977 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7978 diag::err_template_different_requires_clause);
7979 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7980 diag::note_template_prev_declaration) << /*declaration*/0;
7981 };
7982
7983 if (!NewRC != !OldRC) {
7984 if (Complain)
7985 Diagnose();
7986 return false;
7987 }
7988
7989 if (NewRC) {
7990 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7991 NewRC)) {
7992 if (Complain)
7993 Diagnose();
7994 return false;
7995 }
7996 }
7997 }
7998
7999 return true;
8000}
8001
8002bool
8004 if (!S)
8005 return false;
8006
8007 // Find the nearest enclosing declaration scope.
8008 S = S->getDeclParent();
8009
8010 // C++ [temp.pre]p6: [P2096]
8011 // A template, explicit specialization, or partial specialization shall not
8012 // have C linkage.
8013 DeclContext *Ctx = S->getEntity();
8014 if (Ctx && Ctx->isExternCContext()) {
8015 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8016 << TemplateParams->getSourceRange();
8017 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8018 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8019 return true;
8020 }
8021 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8022
8023 // C++ [temp]p2:
8024 // A template-declaration can appear only as a namespace scope or
8025 // class scope declaration.
8026 // C++ [temp.expl.spec]p3:
8027 // An explicit specialization may be declared in any scope in which the
8028 // corresponding primary template may be defined.
8029 // C++ [temp.class.spec]p6: [P2096]
8030 // A partial specialization may be declared in any scope in which the
8031 // corresponding primary template may be defined.
8032 if (Ctx) {
8033 if (Ctx->isFileContext())
8034 return false;
8035 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8036 // C++ [temp.mem]p2:
8037 // A local class shall not have member templates.
8038 if (RD->isLocalClass())
8039 return Diag(TemplateParams->getTemplateLoc(),
8040 diag::err_template_inside_local_class)
8041 << TemplateParams->getSourceRange();
8042 else
8043 return false;
8044 }
8045 }
8046
8047 return Diag(TemplateParams->getTemplateLoc(),
8048 diag::err_template_outside_namespace_or_class_scope)
8049 << TemplateParams->getSourceRange();
8050}
8051
8052/// Determine what kind of template specialization the given declaration
8053/// is.
8055 if (!D)
8056 return TSK_Undeclared;
8057
8058 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8059 return Record->getTemplateSpecializationKind();
8060 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8061 return Function->getTemplateSpecializationKind();
8062 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8063 return Var->getTemplateSpecializationKind();
8064
8065 return TSK_Undeclared;
8066}
8067
8068/// Check whether a specialization is well-formed in the current
8069/// context.
8070///
8071/// This routine determines whether a template specialization can be declared
8072/// in the current context (C++ [temp.expl.spec]p2).
8073///
8074/// \param S the semantic analysis object for which this check is being
8075/// performed.
8076///
8077/// \param Specialized the entity being specialized or instantiated, which
8078/// may be a kind of template (class template, function template, etc.) or
8079/// a member of a class template (member function, static data member,
8080/// member class).
8081///
8082/// \param PrevDecl the previous declaration of this entity, if any.
8083///
8084/// \param Loc the location of the explicit specialization or instantiation of
8085/// this entity.
8086///
8087/// \param IsPartialSpecialization whether this is a partial specialization of
8088/// a class template.
8089///
8090/// \returns true if there was an error that we cannot recover from, false
8091/// otherwise.
8093 NamedDecl *Specialized,
8094 NamedDecl *PrevDecl,
8097 // Keep these "kind" numbers in sync with the %select statements in the
8098 // various diagnostics emitted by this routine.
8099 int EntityKind = 0;
8100 if (isa<ClassTemplateDecl>(Specialized))
8101 EntityKind = IsPartialSpecialization? 1 : 0;
8102 else if (isa<VarTemplateDecl>(Specialized))
8103 EntityKind = IsPartialSpecialization ? 3 : 2;
8104 else if (isa<FunctionTemplateDecl>(Specialized))
8105 EntityKind = 4;
8106 else if (isa<CXXMethodDecl>(Specialized))
8107 EntityKind = 5;
8108 else if (isa<VarDecl>(Specialized))
8109 EntityKind = 6;
8110 else if (isa<RecordDecl>(Specialized))
8111 EntityKind = 7;
8112 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8113 EntityKind = 8;
8114 else {
8115 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8116 << S.getLangOpts().CPlusPlus11;
8117 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8118 return true;
8119 }
8120
8121 // C++ [temp.expl.spec]p2:
8122 // An explicit specialization may be declared in any scope in which
8123 // the corresponding primary template may be defined.
8125 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8126 << Specialized;
8127 return true;
8128 }
8129
8130 // C++ [temp.class.spec]p6:
8131 // A class template partial specialization may be declared in any
8132 // scope in which the primary template may be defined.
8133 DeclContext *SpecializedContext =
8134 Specialized->getDeclContext()->getRedeclContext();
8136
8137 // Make sure that this redeclaration (or definition) occurs in the same
8138 // scope or an enclosing namespace.
8139 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8140 : DC->Equals(SpecializedContext))) {
8141 if (isa<TranslationUnitDecl>(SpecializedContext))
8142 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8143 << EntityKind << Specialized;
8144 else {
8145 auto *ND = cast<NamedDecl>(SpecializedContext);
8146 int Diag = diag::err_template_spec_redecl_out_of_scope;
8147 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8148 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8149 S.Diag(Loc, Diag) << EntityKind << Specialized
8150 << ND << isa<CXXRecordDecl>(ND);
8151 }
8152
8153 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8154
8155 // Don't allow specializing in the wrong class during error recovery.
8156 // Otherwise, things can go horribly wrong.
8157 if (DC->isRecord())
8158 return true;
8159 }
8160
8161 return false;
8162}
8163
8165 if (!E->isTypeDependent())
8166 return SourceLocation();
8167 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8168 Checker.TraverseStmt(E);
8169 if (Checker.MatchLoc.isInvalid())
8170 return E->getSourceRange();
8171 return Checker.MatchLoc;
8172}
8173
8174static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8175 if (!TL.getType()->isDependentType())
8176 return SourceLocation();
8177 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8178 Checker.TraverseTypeLoc(TL);
8179 if (Checker.MatchLoc.isInvalid())
8180 return TL.getSourceRange();
8181 return Checker.MatchLoc;
8182}
8183
8184/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8185/// that checks non-type template partial specialization arguments.
8187 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8188 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8189 for (unsigned I = 0; I != NumArgs; ++I) {
8190 if (Args[I].getKind() == TemplateArgument::Pack) {
8192 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8193 Args[I].pack_size(), IsDefaultArgument))
8194 return true;
8195
8196 continue;
8197 }
8198
8199 if (Args[I].getKind() != TemplateArgument::Expression)
8200 continue;
8201
8202 Expr *ArgExpr = Args[I].getAsExpr();
8203
8204 // We can have a pack expansion of any of the bullets below.
8205 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8206 ArgExpr = Expansion->getPattern();
8207
8208 // Strip off any implicit casts we added as part of type checking.
8209 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8210 ArgExpr = ICE->getSubExpr();
8211
8212 // C++ [temp.class.spec]p8:
8213 // A non-type argument is non-specialized if it is the name of a
8214 // non-type parameter. All other non-type arguments are
8215 // specialized.
8216 //
8217 // Below, we check the two conditions that only apply to
8218 // specialized non-type arguments, so skip any non-specialized
8219 // arguments.
8220 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8221 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8222 continue;
8223
8224 // C++ [temp.class.spec]p9:
8225 // Within the argument list of a class template partial
8226 // specialization, the following restrictions apply:
8227 // -- A partially specialized non-type argument expression
8228 // shall not involve a template parameter of the partial
8229 // specialization except when the argument expression is a
8230 // simple identifier.
8231 // -- The type of a template parameter corresponding to a
8232 // specialized non-type argument shall not be dependent on a
8233 // parameter of the specialization.
8234 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8235 // We implement a compromise between the original rules and DR1315:
8236 // -- A specialized non-type template argument shall not be
8237 // type-dependent and the corresponding template parameter
8238 // shall have a non-dependent type.
8239 SourceRange ParamUseRange =
8240 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8241 if (ParamUseRange.isValid()) {
8242 if (IsDefaultArgument) {
8243 S.Diag(TemplateNameLoc,
8244 diag::err_dependent_non_type_arg_in_partial_spec);
8245 S.Diag(ParamUseRange.getBegin(),
8246 diag::note_dependent_non_type_default_arg_in_partial_spec)
8247 << ParamUseRange;
8248 } else {
8249 S.Diag(ParamUseRange.getBegin(),
8250 diag::err_dependent_non_type_arg_in_partial_spec)
8251 << ParamUseRange;
8252 }
8253 return true;
8254 }
8255
8256 ParamUseRange = findTemplateParameter(
8257 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8258 if (ParamUseRange.isValid()) {
8259 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8260 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8261 << Param->getType();
8263 return true;
8264 }
8265 }
8266
8267 return false;
8268}
8269
8271 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8272 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8273 // We have to be conservative when checking a template in a dependent
8274 // context.
8275 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8276 return false;
8277
8278 TemplateParameterList *TemplateParams =
8279 PrimaryTemplate->getTemplateParameters();
8280 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8282 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8283 if (!Param)
8284 continue;
8285
8286 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8287 Param, &TemplateArgs[I],
8288 1, I >= NumExplicit))
8289 return true;
8290 }
8291
8292 return false;
8293}
8294
8296 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8297 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8299 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8300 assert(TUK != TagUseKind::Reference && "References are not specializations");
8301
8302 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8303 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8304 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8305
8306 // Find the class template we're specializing
8307 TemplateName Name = TemplateId.Template.get();
8309 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8310
8311 if (!ClassTemplate) {
8312 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8313 << (Name.getAsTemplateDecl() &&
8314 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8315 return true;
8316 }
8317
8318 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8319 auto Message = DSA->getMessage();
8320 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8321 << ClassTemplate << !Message.empty() << Message;
8322 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8323 }
8324
8325 if (S->isTemplateParamScope())
8326 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8327
8328 DeclContext *DC = ClassTemplate->getDeclContext();
8329
8330 bool isMemberSpecialization = false;
8331 bool isPartialSpecialization = false;
8332
8333 if (SS.isSet()) {
8334 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8335 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8336 TemplateNameLoc, &TemplateId,
8337 /*IsMemberSpecialization=*/false))
8338 return true;
8339 }
8340
8341 // Check the validity of the template headers that introduce this
8342 // template.
8343 // FIXME: We probably shouldn't complain about these headers for
8344 // friend declarations.
8345 bool Invalid = false;
8346 TemplateParameterList *TemplateParams =
8348 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8349 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8350 if (Invalid)
8351 return true;
8352
8353 // Check that we can declare a template specialization here.
8354 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8355 return true;
8356
8357 if (TemplateParams && DC->isDependentContext()) {
8358 ContextRAII SavedContext(*this, DC);
8360 return true;
8361 }
8362
8363 if (TemplateParams && TemplateParams->size() > 0) {
8364 isPartialSpecialization = true;
8365
8366 if (TUK == TagUseKind::Friend) {
8367 Diag(KWLoc, diag::err_partial_specialization_friend)
8368 << SourceRange(LAngleLoc, RAngleLoc);
8369 return true;
8370 }
8371
8372 // C++ [temp.class.spec]p10:
8373 // The template parameter list of a specialization shall not
8374 // contain default template argument values.
8375 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8376 Decl *Param = TemplateParams->getParam(I);
8377 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8378 if (TTP->hasDefaultArgument()) {
8379 Diag(TTP->getDefaultArgumentLoc(),
8380 diag::err_default_arg_in_partial_spec);
8381 TTP->removeDefaultArgument();
8382 }
8383 } else if (NonTypeTemplateParmDecl *NTTP
8384 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8385 if (NTTP->hasDefaultArgument()) {
8386 Diag(NTTP->getDefaultArgumentLoc(),
8387 diag::err_default_arg_in_partial_spec)
8388 << NTTP->getDefaultArgument().getSourceRange();
8389 NTTP->removeDefaultArgument();
8390 }
8391 } else {
8392 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8393 if (TTP->hasDefaultArgument()) {
8395 diag::err_default_arg_in_partial_spec)
8397 TTP->removeDefaultArgument();
8398 }
8399 }
8400 }
8401 } else if (TemplateParams) {
8402 if (TUK == TagUseKind::Friend)
8403 Diag(KWLoc, diag::err_template_spec_friend)
8405 SourceRange(TemplateParams->getTemplateLoc(),
8406 TemplateParams->getRAngleLoc()))
8407 << SourceRange(LAngleLoc, RAngleLoc);
8408 } else {
8409 assert(TUK == TagUseKind::Friend &&
8410 "should have a 'template<>' for this decl");
8411 }
8412
8413 // Check that the specialization uses the same tag kind as the
8414 // original template.
8416 assert(Kind != TagTypeKind::Enum &&
8417 "Invalid enum tag in class template spec!");
8418 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8419 TUK == TagUseKind::Definition, KWLoc,
8420 ClassTemplate->getIdentifier())) {
8421 Diag(KWLoc, diag::err_use_with_wrong_tag)
8422 << ClassTemplate
8424 ClassTemplate->getTemplatedDecl()->getKindName());
8425 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8426 diag::note_previous_use);
8427 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8428 }
8429
8430 // Translate the parser's template argument list in our AST format.
8431 TemplateArgumentListInfo TemplateArgs =
8432 makeTemplateArgumentListInfo(*this, TemplateId);
8433
8434 // Check for unexpanded parameter packs in any of the template arguments.
8435 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8436 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8437 isPartialSpecialization
8440 return true;
8441
8442 // Check that the template argument list is well-formed for this
8443 // template.
8444 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8445 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8446 /*DefaultArgs=*/{},
8447 /*PartialTemplateArgs=*/false, SugaredConverted,
8448 CanonicalConverted,
8449 /*UpdateArgsWithConversions=*/true))
8450 return true;
8451
8452 // Find the class template (partial) specialization declaration that
8453 // corresponds to these arguments.
8454 if (isPartialSpecialization) {
8456 TemplateArgs.size(),
8457 CanonicalConverted))
8458 return true;
8459
8460 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8461 // also do it during instantiation.
8462 if (!Name.isDependent() &&
8464 TemplateArgs, CanonicalConverted)) {
8465 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8466 << ClassTemplate->getDeclName();
8467 isPartialSpecialization = false;
8468 Invalid = true;
8469 }
8470 }
8471
8472 void *InsertPos = nullptr;
8473 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8474
8475 if (isPartialSpecialization)
8476 PrevDecl = ClassTemplate->findPartialSpecialization(
8477 CanonicalConverted, TemplateParams, InsertPos);
8478 else
8479 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8480
8482
8483 // Check whether we can declare a class template specialization in
8484 // the current scope.
8485 if (TUK != TagUseKind::Friend &&
8487 TemplateNameLoc,
8488 isPartialSpecialization))
8489 return true;
8490
8491 // The canonical type
8492 QualType CanonType;
8493 if (isPartialSpecialization) {
8494 // Build the canonical type that describes the converted template
8495 // arguments of the class template partial specialization.
8496 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8497 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8498 CanonicalConverted);
8499
8500 if (Context.hasSameType(CanonType,
8501 ClassTemplate->getInjectedClassNameSpecialization()) &&
8502 (!Context.getLangOpts().CPlusPlus20 ||
8503 !TemplateParams->hasAssociatedConstraints())) {
8504 // C++ [temp.class.spec]p9b3:
8505 //
8506 // -- The argument list of the specialization shall not be identical
8507 // to the implicit argument list of the primary template.
8508 //
8509 // This rule has since been removed, because it's redundant given DR1495,
8510 // but we keep it because it produces better diagnostics and recovery.
8511 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8512 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8513 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8514 return CheckClassTemplate(
8515 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8516 TemplateNameLoc, Attr, TemplateParams, AS_none,
8517 /*ModulePrivateLoc=*/SourceLocation(),
8518 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8519 TemplateParameterLists.data());
8520 }
8521
8522 // Create a new class template partial specialization declaration node.
8524 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8527 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8528 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8529 Partial->setTemplateArgsAsWritten(TemplateArgs);
8530 SetNestedNameSpecifier(*this, Partial, SS);
8531 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8533 Context, TemplateParameterLists.drop_back(1));
8534 }
8535
8536 if (!PrevPartial)
8537 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8538 Specialization = Partial;
8539
8540 // If we are providing an explicit specialization of a member class
8541 // template specialization, make a note of that.
8542 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8543 PrevPartial->setMemberSpecialization();
8544
8546 } else {
8547 // Create a new class template specialization declaration node for
8548 // this explicit specialization or friend declaration.
8550 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8551 CanonicalConverted, PrevDecl);
8552 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8554 if (TemplateParameterLists.size() > 0) {
8555 Specialization->setTemplateParameterListsInfo(Context,
8556 TemplateParameterLists);
8557 }
8558
8559 if (!PrevDecl)
8560 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8561
8563 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8564 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8565 CanonicalConverted);
8566 } else {
8568 }
8569 }
8570
8571 // C++ [temp.expl.spec]p6:
8572 // If a template, a member template or the member of a class template is
8573 // explicitly specialized then that specialization shall be declared
8574 // before the first use of that specialization that would cause an implicit
8575 // instantiation to take place, in every translation unit in which such a
8576 // use occurs; no diagnostic is required.
8577 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8578 bool Okay = false;
8579 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8580 // Is there any previous explicit specialization declaration?
8582 Okay = true;
8583 break;
8584 }
8585 }
8586
8587 if (!Okay) {
8588 SourceRange Range(TemplateNameLoc, RAngleLoc);
8589 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8591
8592 Diag(PrevDecl->getPointOfInstantiation(),
8593 diag::note_instantiation_required_here)
8594 << (PrevDecl->getTemplateSpecializationKind()
8596 return true;
8597 }
8598 }
8599
8600 // If this is not a friend, note that this is an explicit specialization.
8601 if (TUK != TagUseKind::Friend)
8602 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8603
8604 // Check that this isn't a redefinition of this specialization.
8605 if (TUK == TagUseKind::Definition) {
8606 RecordDecl *Def = Specialization->getDefinition();
8607 NamedDecl *Hidden = nullptr;
8608 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8609 SkipBody->ShouldSkip = true;
8610 SkipBody->Previous = Def;
8612 } else if (Def) {
8613 SourceRange Range(TemplateNameLoc, RAngleLoc);
8614 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8615 Diag(Def->getLocation(), diag::note_previous_definition);
8616 Specialization->setInvalidDecl();
8617 return true;
8618 }
8619 }
8620
8623
8624 // Add alignment attributes if necessary; these attributes are checked when
8625 // the ASTContext lays out the structure.
8626 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8629 }
8630
8631 if (ModulePrivateLoc.isValid())
8632 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8633 << (isPartialSpecialization? 1 : 0)
8634 << FixItHint::CreateRemoval(ModulePrivateLoc);
8635
8636 // C++ [temp.expl.spec]p9:
8637 // A template explicit specialization is in the scope of the
8638 // namespace in which the template was defined.
8639 //
8640 // We actually implement this paragraph where we set the semantic
8641 // context (in the creation of the ClassTemplateSpecializationDecl),
8642 // but we also maintain the lexical context where the actual
8643 // definition occurs.
8644 Specialization->setLexicalDeclContext(CurContext);
8645
8646 // We may be starting the definition of this specialization.
8647 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8648 Specialization->startDefinition();
8649
8650 if (TUK == TagUseKind::Friend) {
8651 // Build the fully-sugared type for this class template
8652 // specialization as the user wrote in the specialization
8653 // itself. This means that we'll pretty-print the type retrieved
8654 // from the specialization's declaration the way that the user
8655 // actually wrote the specialization, rather than formatting the
8656 // name based on the "canonical" representation used to store the
8657 // template arguments in the specialization.
8659 Name, TemplateNameLoc, TemplateArgs, CanonType);
8661 TemplateNameLoc,
8662 WrittenTy,
8663 /*FIXME:*/KWLoc);
8664 Friend->setAccess(AS_public);
8666 } else {
8667 // Add the specialization into its lexical context, so that it can
8668 // be seen when iterating through the list of declarations in that
8669 // context. However, specializations are not found by name lookup.
8671 }
8672
8673 if (SkipBody && SkipBody->ShouldSkip)
8674 return SkipBody->Previous;
8675
8676 Specialization->setInvalidDecl(Invalid);
8678 return Specialization;
8679}
8680
8682 MultiTemplateParamsArg TemplateParameterLists,
8683 Declarator &D) {
8684 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8685 ActOnDocumentableDecl(NewDecl);
8686 return NewDecl;
8687}
8688
8690 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8691 const IdentifierInfo *Name, SourceLocation NameLoc) {
8692 DeclContext *DC = CurContext;
8693
8694 if (!DC->getRedeclContext()->isFileContext()) {
8695 Diag(NameLoc,
8696 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8697 return nullptr;
8698 }
8699
8700 if (TemplateParameterLists.size() > 1) {
8701 Diag(NameLoc, diag::err_concept_extra_headers);
8702 return nullptr;
8703 }
8704
8705 TemplateParameterList *Params = TemplateParameterLists.front();
8706
8707 if (Params->size() == 0) {
8708 Diag(NameLoc, diag::err_concept_no_parameters);
8709 return nullptr;
8710 }
8711
8712 // Ensure that the parameter pack, if present, is the last parameter in the
8713 // template.
8714 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8715 ParamEnd = Params->end();
8716 ParamIt != ParamEnd; ++ParamIt) {
8717 Decl const *Param = *ParamIt;
8718 if (Param->isParameterPack()) {
8719 if (++ParamIt == ParamEnd)
8720 break;
8721 Diag(Param->getLocation(),
8722 diag::err_template_param_pack_must_be_last_template_parameter);
8723 return nullptr;
8724 }
8725 }
8726
8727 ConceptDecl *NewDecl =
8728 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8729
8730 if (NewDecl->hasAssociatedConstraints()) {
8731 // C++2a [temp.concept]p4:
8732 // A concept shall not have associated constraints.
8733 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8734 NewDecl->setInvalidDecl();
8735 }
8736
8737 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8738 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8740 LookupName(Previous, S);
8741 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8742 /*AllowInlineNamespace*/ false);
8743
8744 // We cannot properly handle redeclarations until we parse the constraint
8745 // expression, so only inject the name if we are sure we are not redeclaring a
8746 // symbol
8747 if (Previous.empty())
8748 PushOnScopeChains(NewDecl, S, true);
8749
8750 return NewDecl;
8751}
8752
8754 bool Found = false;
8756 while (F.hasNext()) {
8757 NamedDecl *D = F.next();
8758 if (D == C) {
8759 F.erase();
8760 Found = true;
8761 break;
8762 }
8763 }
8764 F.done();
8765 return Found;
8766}
8767
8770 Expr *ConstraintExpr,
8771 const ParsedAttributesView &Attrs) {
8772 assert(!C->hasDefinition() && "Concept already defined");
8773 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8774 return nullptr;
8775 C->setDefinition(ConstraintExpr);
8776 ProcessDeclAttributeList(S, C, Attrs);
8777
8778 // Check for conflicting previous declaration.
8779 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8780 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8782 LookupName(Previous, S);
8783 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8784 /*AllowInlineNamespace*/ false);
8785 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8786 bool AddToScope = true;
8787 CheckConceptRedefinition(C, Previous, AddToScope);
8788
8790 if (!WasAlreadyAdded && AddToScope)
8791 PushOnScopeChains(C, S);
8792
8793 return C;
8794}
8795
8797 LookupResult &Previous, bool &AddToScope) {
8798 AddToScope = true;
8799
8800 if (Previous.empty())
8801 return;
8802
8803 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8804 if (!OldConcept) {
8805 auto *Old = Previous.getRepresentativeDecl();
8806 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8807 << NewDecl->getDeclName();
8808 notePreviousDefinition(Old, NewDecl->getLocation());
8809 AddToScope = false;
8810 return;
8811 }
8812 // Check if we can merge with a concept declaration.
8813 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8814 if (!IsSame) {
8815 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8816 << NewDecl->getDeclName();
8817 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8818 AddToScope = false;
8819 return;
8820 }
8821 if (hasReachableDefinition(OldConcept) &&
8822 IsRedefinitionInModule(NewDecl, OldConcept)) {
8823 Diag(NewDecl->getLocation(), diag::err_redefinition)
8824 << NewDecl->getDeclName();
8825 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8826 AddToScope = false;
8827 return;
8828 }
8829 if (!Previous.isSingleResult()) {
8830 // FIXME: we should produce an error in case of ambig and failed lookups.
8831 // Other decls (e.g. namespaces) also have this shortcoming.
8832 return;
8833 }
8834 // We unwrap canonical decl late to check for module visibility.
8835 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8836}
8837
8840 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8841 Diag(Loc, diag::err_recursive_concept) << Concept;
8842 Diag(Concept->getLocation(), diag::note_declared_at);
8843 return true;
8844 }
8845 return false;
8846}
8847
8848/// \brief Strips various properties off an implicit instantiation
8849/// that has just been explicitly specialized.
8850static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8851 if (MinGW || (isa<FunctionDecl>(D) &&
8852 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8853 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8854
8855 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8856 FD->setInlineSpecified(false);
8857}
8858
8859/// Compute the diagnostic location for an explicit instantiation
8860// declaration or definition.
8862 NamedDecl* D, SourceLocation PointOfInstantiation) {
8863 // Explicit instantiations following a specialization have no effect and
8864 // hence no PointOfInstantiation. In that case, walk decl backwards
8865 // until a valid name loc is found.
8866 SourceLocation PrevDiagLoc = PointOfInstantiation;
8867 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8868 Prev = Prev->getPreviousDecl()) {
8869 PrevDiagLoc = Prev->getLocation();
8870 }
8871 assert(PrevDiagLoc.isValid() &&
8872 "Explicit instantiation without point of instantiation?");
8873 return PrevDiagLoc;
8874}
8875
8876bool
8879 NamedDecl *PrevDecl,
8881 SourceLocation PrevPointOfInstantiation,
8882 bool &HasNoEffect) {
8883 HasNoEffect = false;
8884
8885 switch (NewTSK) {
8886 case TSK_Undeclared:
8888 assert(
8889 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8890 "previous declaration must be implicit!");
8891 return false;
8892
8894 switch (PrevTSK) {
8895 case TSK_Undeclared:
8897 // Okay, we're just specializing something that is either already
8898 // explicitly specialized or has merely been mentioned without any
8899 // instantiation.
8900 return false;
8901
8903 if (PrevPointOfInstantiation.isInvalid()) {
8904 // The declaration itself has not actually been instantiated, so it is
8905 // still okay to specialize it.
8907 PrevDecl,
8908 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8909 return false;
8910 }
8911 // Fall through
8912 [[fallthrough]];
8913
8916 assert((PrevTSK == TSK_ImplicitInstantiation ||
8917 PrevPointOfInstantiation.isValid()) &&
8918 "Explicit instantiation without point of instantiation?");
8919
8920 // C++ [temp.expl.spec]p6:
8921 // If a template, a member template or the member of a class template
8922 // is explicitly specialized then that specialization shall be declared
8923 // before the first use of that specialization that would cause an
8924 // implicit instantiation to take place, in every translation unit in
8925 // which such a use occurs; no diagnostic is required.
8926 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8927 // Is there any previous explicit specialization declaration?
8929 return false;
8930 }
8931
8932 Diag(NewLoc, diag::err_specialization_after_instantiation)
8933 << PrevDecl;
8934 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8935 << (PrevTSK != TSK_ImplicitInstantiation);
8936
8937 return true;
8938 }
8939 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8940
8942 switch (PrevTSK) {
8944 // This explicit instantiation declaration is redundant (that's okay).
8945 HasNoEffect = true;
8946 return false;
8947
8948 case TSK_Undeclared:
8950 // We're explicitly instantiating something that may have already been
8951 // implicitly instantiated; that's fine.
8952 return false;
8953
8955 // C++0x [temp.explicit]p4:
8956 // For a given set of template parameters, if an explicit instantiation
8957 // of a template appears after a declaration of an explicit
8958 // specialization for that template, the explicit instantiation has no
8959 // effect.
8960 HasNoEffect = true;
8961 return false;
8962
8964 // C++0x [temp.explicit]p10:
8965 // If an entity is the subject of both an explicit instantiation
8966 // declaration and an explicit instantiation definition in the same
8967 // translation unit, the definition shall follow the declaration.
8968 Diag(NewLoc,
8969 diag::err_explicit_instantiation_declaration_after_definition);
8970
8971 // Explicit instantiations following a specialization have no effect and
8972 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8973 // until a valid name loc is found.
8974 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8975 diag::note_explicit_instantiation_definition_here);
8976 HasNoEffect = true;
8977 return false;
8978 }
8979 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8980
8982 switch (PrevTSK) {
8983 case TSK_Undeclared:
8985 // We're explicitly instantiating something that may have already been
8986 // implicitly instantiated; that's fine.
8987 return false;
8988
8990 // C++ DR 259, C++0x [temp.explicit]p4:
8991 // For a given set of template parameters, if an explicit
8992 // instantiation of a template appears after a declaration of
8993 // an explicit specialization for that template, the explicit
8994 // instantiation has no effect.
8995 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8996 << PrevDecl;
8997 Diag(PrevDecl->getLocation(),
8998 diag::note_previous_template_specialization);
8999 HasNoEffect = true;
9000 return false;
9001
9003 // We're explicitly instantiating a definition for something for which we
9004 // were previously asked to suppress instantiations. That's fine.
9005
9006 // C++0x [temp.explicit]p4:
9007 // For a given set of template parameters, if an explicit instantiation
9008 // of a template appears after a declaration of an explicit
9009 // specialization for that template, the explicit instantiation has no
9010 // effect.
9011 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9012 // Is there any previous explicit specialization declaration?
9014 HasNoEffect = true;
9015 break;
9016 }
9017 }
9018
9019 return false;
9020
9022 // C++0x [temp.spec]p5:
9023 // For a given template and a given set of template-arguments,
9024 // - an explicit instantiation definition shall appear at most once
9025 // in a program,
9026
9027 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9028 Diag(NewLoc, (getLangOpts().MSVCCompat)
9029 ? diag::ext_explicit_instantiation_duplicate
9030 : diag::err_explicit_instantiation_duplicate)
9031 << PrevDecl;
9032 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9033 diag::note_previous_explicit_instantiation);
9034 HasNoEffect = true;
9035 return false;
9036 }
9037 }
9038
9039 llvm_unreachable("Missing specialization/instantiation case?");
9040}
9041
9043 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9045 // Remove anything from Previous that isn't a function template in
9046 // the correct context.
9047 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9048 LookupResult::Filter F = Previous.makeFilter();
9049 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9050 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9051 while (F.hasNext()) {
9053 if (!isa<FunctionTemplateDecl>(D)) {
9054 F.erase();
9055 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9056 continue;
9057 }
9058
9059 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9061 F.erase();
9062 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9063 continue;
9064 }
9065 }
9066 F.done();
9067
9068 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9069 if (Previous.empty()) {
9070 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9071 << IsFriend;
9072 for (auto &P : DiscardedCandidates)
9073 Diag(P.second->getLocation(),
9074 diag::note_dependent_function_template_spec_discard_reason)
9075 << P.first << IsFriend;
9076 return true;
9077 }
9078
9080 ExplicitTemplateArgs);
9081 return false;
9082}
9083
9085 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9086 LookupResult &Previous, bool QualifiedFriend) {
9087 // The set of function template specializations that could match this
9088 // explicit function template specialization.
9089 UnresolvedSet<8> Candidates;
9090 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9091 /*ForTakingAddress=*/false);
9092
9093 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9094 ConvertedTemplateArgs;
9095
9096 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9097 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9098 I != E; ++I) {
9099 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9100 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9101 // Only consider templates found within the same semantic lookup scope as
9102 // FD.
9103 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9105 continue;
9106
9107 QualType FT = FD->getType();
9108 // C++11 [dcl.constexpr]p8:
9109 // A constexpr specifier for a non-static member function that is not
9110 // a constructor declares that member function to be const.
9111 //
9112 // When matching a constexpr member function template specialization
9113 // against the primary template, we don't yet know whether the
9114 // specialization has an implicit 'const' (because we don't know whether
9115 // it will be a static member function until we know which template it
9116 // specializes). This rule was removed in C++14.
9117 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9118 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9119 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9120 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9121 if (OldMD && OldMD->isConst()) {
9122 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9124 EPI.TypeQuals.addConst();
9126 FPT->getParamTypes(), EPI);
9127 }
9128 }
9129
9131 if (ExplicitTemplateArgs)
9132 Args = *ExplicitTemplateArgs;
9133
9134 // C++ [temp.expl.spec]p11:
9135 // A trailing template-argument can be left unspecified in the
9136 // template-id naming an explicit function template specialization
9137 // provided it can be deduced from the function argument type.
9138 // Perform template argument deduction to determine whether we may be
9139 // specializing this template.
9140 // FIXME: It is somewhat wasteful to build
9141 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9142 FunctionDecl *Specialization = nullptr;
9144 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9145 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9147 // Template argument deduction failed; record why it failed, so
9148 // that we can provide nifty diagnostics.
9149 FailedCandidates.addCandidate().set(
9150 I.getPair(), FunTmpl->getTemplatedDecl(),
9151 MakeDeductionFailureInfo(Context, TDK, Info));
9152 (void)TDK;
9153 continue;
9154 }
9155
9156 // Target attributes are part of the cuda function signature, so
9157 // the deduced template's cuda target must match that of the
9158 // specialization. Given that C++ template deduction does not
9159 // take target attributes into account, we reject candidates
9160 // here that have a different target.
9161 if (LangOpts.CUDA &&
9163 /* IgnoreImplicitHDAttr = */ true) !=
9164 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9165 FailedCandidates.addCandidate().set(
9166 I.getPair(), FunTmpl->getTemplatedDecl(),
9169 continue;
9170 }
9171
9172 // Record this candidate.
9173 if (ExplicitTemplateArgs)
9174 ConvertedTemplateArgs[Specialization] = std::move(Args);
9175 Candidates.addDecl(Specialization, I.getAccess());
9176 }
9177 }
9178
9179 // For a qualified friend declaration (with no explicit marker to indicate
9180 // that a template specialization was intended), note all (template and
9181 // non-template) candidates.
9182 if (QualifiedFriend && Candidates.empty()) {
9183 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9184 << FD->getDeclName() << FDLookupContext;
9185 // FIXME: We should form a single candidate list and diagnose all
9186 // candidates at once, to get proper sorting and limiting.
9187 for (auto *OldND : Previous) {
9188 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9189 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9190 }
9191 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9192 return true;
9193 }
9194
9195 // Find the most specialized function template.
9197 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9198 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9199 PDiag(diag::err_function_template_spec_ambiguous)
9200 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9201 PDiag(diag::note_function_template_spec_matched));
9202
9203 if (Result == Candidates.end())
9204 return true;
9205
9206 // Ignore access information; it doesn't figure into redeclaration checking.
9207 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9208
9209 if (const auto *PT = Specialization->getPrimaryTemplate();
9210 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9211 auto Message = DSA->getMessage();
9212 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9213 << PT << !Message.empty() << Message;
9214 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9215 }
9216
9217 // C++23 [except.spec]p13:
9218 // An exception specification is considered to be needed when:
9219 // - [...]
9220 // - the exception specification is compared to that of another declaration
9221 // (e.g., an explicit specialization or an overriding virtual function);
9222 // - [...]
9223 //
9224 // The exception specification of a defaulted function is evaluated as
9225 // described above only when needed; similarly, the noexcept-specifier of a
9226 // specialization of a function template or member function of a class
9227 // template is instantiated only when needed.
9228 //
9229 // The standard doesn't specify what the "comparison with another declaration"
9230 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9231 // not state which properties of an explicit specialization must match the
9232 // primary template.
9233 //
9234 // We assume that an explicit specialization must correspond with (per
9235 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9236 // the declaration produced by substitution into the function template.
9237 //
9238 // Since the determination whether two function declarations correspond does
9239 // not consider exception specification, we only need to instantiate it once
9240 // we determine the primary template when comparing types per
9241 // [basic.link]p11.1.
9242 auto *SpecializationFPT =
9243 Specialization->getType()->castAs<FunctionProtoType>();
9244 // If the function has a dependent exception specification, resolve it after
9245 // we have selected the primary template so we can check whether it matches.
9246 if (getLangOpts().CPlusPlus17 &&
9247 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9248 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9249 return true;
9250
9252 = Specialization->getTemplateSpecializationInfo();
9253 assert(SpecInfo && "Function template specialization info missing?");
9254
9255 // Note: do not overwrite location info if previous template
9256 // specialization kind was explicit.
9258 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9259 Specialization->setLocation(FD->getLocation());
9260 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9261 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9262 // function can differ from the template declaration with respect to
9263 // the constexpr specifier.
9264 // FIXME: We need an update record for this AST mutation.
9265 // FIXME: What if there are multiple such prior declarations (for instance,
9266 // from different modules)?
9267 Specialization->setConstexprKind(FD->getConstexprKind());
9268 }
9269
9270 // FIXME: Check if the prior specialization has a point of instantiation.
9271 // If so, we have run afoul of .
9272
9273 // If this is a friend declaration, then we're not really declaring
9274 // an explicit specialization.
9275 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9276
9277 // Check the scope of this explicit specialization.
9278 if (!isFriend &&
9280 Specialization->getPrimaryTemplate(),
9282 false))
9283 return true;
9284
9285 // C++ [temp.expl.spec]p6:
9286 // If a template, a member template or the member of a class template is
9287 // explicitly specialized then that specialization shall be declared
9288 // before the first use of that specialization that would cause an implicit
9289 // instantiation to take place, in every translation unit in which such a
9290 // use occurs; no diagnostic is required.
9291 bool HasNoEffect = false;
9292 if (!isFriend &&
9297 SpecInfo->getPointOfInstantiation(),
9298 HasNoEffect))
9299 return true;
9300
9301 // Mark the prior declaration as an explicit specialization, so that later
9302 // clients know that this is an explicit specialization.
9303 if (!isFriend) {
9304 // Since explicit specializations do not inherit '=delete' from their
9305 // primary function template - check if the 'specialization' that was
9306 // implicitly generated (during template argument deduction for partial
9307 // ordering) from the most specialized of all the function templates that
9308 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9309 // first check that it was implicitly generated during template argument
9310 // deduction by making sure it wasn't referenced, and then reset the deleted
9311 // flag to not-deleted, so that we can inherit that information from 'FD'.
9312 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9313 !Specialization->getCanonicalDecl()->isReferenced()) {
9314 // FIXME: This assert will not hold in the presence of modules.
9315 assert(
9316 Specialization->getCanonicalDecl() == Specialization &&
9317 "This must be the only existing declaration of this specialization");
9318 // FIXME: We need an update record for this AST mutation.
9319 Specialization->setDeletedAsWritten(false);
9320 }
9321 // FIXME: We need an update record for this AST mutation.
9324 }
9325
9326 // Turn the given function declaration into a function template
9327 // specialization, with the template arguments from the previous
9328 // specialization.
9329 // Take copies of (semantic and syntactic) template argument lists.
9331 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9332 FD->setFunctionTemplateSpecialization(
9333 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9335 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9336
9337 // A function template specialization inherits the target attributes
9338 // of its template. (We require the attributes explicitly in the
9339 // code to match, but a template may have implicit attributes by
9340 // virtue e.g. of being constexpr, and it passes these implicit
9341 // attributes on to its specializations.)
9342 if (LangOpts.CUDA)
9343 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9344
9345 // The "previous declaration" for this function template specialization is
9346 // the prior function template specialization.
9347 Previous.clear();
9348 Previous.addDecl(Specialization);
9349 return false;
9350}
9351
9352bool
9354 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9355 "Only for non-template members");
9356
9357 // Try to find the member we are instantiating.
9358 NamedDecl *FoundInstantiation = nullptr;
9359 NamedDecl *Instantiation = nullptr;
9360 NamedDecl *InstantiatedFrom = nullptr;
9361 MemberSpecializationInfo *MSInfo = nullptr;
9362
9363 if (Previous.empty()) {
9364 // Nowhere to look anyway.
9365 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9366 UnresolvedSet<8> Candidates;
9367 for (NamedDecl *Candidate : Previous) {
9368 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9369 // Ignore any candidates that aren't member functions.
9370 if (!Method)
9371 continue;
9372
9373 QualType Adjusted = Function->getType();
9374 if (!hasExplicitCallingConv(Adjusted))
9375 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9376 // Ignore any candidates with the wrong type.
9377 // This doesn't handle deduced return types, but both function
9378 // declarations should be undeduced at this point.
9379 // FIXME: The exception specification should probably be ignored when
9380 // comparing the types.
9381 if (!Context.hasSameType(Adjusted, Method->getType()))
9382 continue;
9383
9384 // Ignore any candidates with unsatisfied constraints.
9385 if (ConstraintSatisfaction Satisfaction;
9386 Method->getTrailingRequiresClause() &&
9387 (CheckFunctionConstraints(Method, Satisfaction,
9388 /*UsageLoc=*/Member->getLocation(),
9389 /*ForOverloadResolution=*/true) ||
9390 !Satisfaction.IsSatisfied))
9391 continue;
9392
9393 Candidates.addDecl(Candidate);
9394 }
9395
9396 // If we have no viable candidates left after filtering, we are done.
9397 if (Candidates.empty())
9398 return false;
9399
9400 // Find the function that is more constrained than every other function it
9401 // has been compared to.
9402 UnresolvedSetIterator Best = Candidates.begin();
9403 CXXMethodDecl *BestMethod = nullptr;
9404 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9405 I != E; ++I) {
9406 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9407 if (I == Best ||
9408 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9409 Best = I;
9410 BestMethod = Method;
9411 }
9412 }
9413
9414 FoundInstantiation = *Best;
9415 Instantiation = BestMethod;
9416 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9417 MSInfo = BestMethod->getMemberSpecializationInfo();
9418
9419 // Make sure the best candidate is more constrained than all of the others.
9420 bool Ambiguous = false;
9421 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9422 I != E; ++I) {
9423 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9424 if (I != Best &&
9425 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9426 Ambiguous = true;
9427 break;
9428 }
9429 }
9430
9431 if (Ambiguous) {
9432 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9433 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9434 for (NamedDecl *Candidate : Candidates) {
9435 Candidate = Candidate->getUnderlyingDecl();
9436 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9437 << Candidate;
9438 }
9439 return true;
9440 }
9441 } else if (isa<VarDecl>(Member)) {
9442 VarDecl *PrevVar;
9443 if (Previous.isSingleResult() &&
9444 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9445 if (PrevVar->isStaticDataMember()) {
9446 FoundInstantiation = Previous.getRepresentativeDecl();
9447 Instantiation = PrevVar;
9448 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9449 MSInfo = PrevVar->getMemberSpecializationInfo();
9450 }
9451 } else if (isa<RecordDecl>(Member)) {
9452 CXXRecordDecl *PrevRecord;
9453 if (Previous.isSingleResult() &&
9454 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9455 FoundInstantiation = Previous.getRepresentativeDecl();
9456 Instantiation = PrevRecord;
9457 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9458 MSInfo = PrevRecord->getMemberSpecializationInfo();
9459 }
9460 } else if (isa<EnumDecl>(Member)) {
9461 EnumDecl *PrevEnum;
9462 if (Previous.isSingleResult() &&
9463 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9464 FoundInstantiation = Previous.getRepresentativeDecl();
9465 Instantiation = PrevEnum;
9466 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9467 MSInfo = PrevEnum->getMemberSpecializationInfo();
9468 }
9469 }
9470
9471 if (!Instantiation) {
9472 // There is no previous declaration that matches. Since member
9473 // specializations are always out-of-line, the caller will complain about
9474 // this mismatch later.
9475 return false;
9476 }
9477
9478 // A member specialization in a friend declaration isn't really declaring
9479 // an explicit specialization, just identifying a specific (possibly implicit)
9480 // specialization. Don't change the template specialization kind.
9481 //
9482 // FIXME: Is this really valid? Other compilers reject.
9483 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9484 // Preserve instantiation information.
9485 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9486 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9487 cast<CXXMethodDecl>(InstantiatedFrom),
9488 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9489 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9490 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9491 cast<CXXRecordDecl>(InstantiatedFrom),
9492 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9493 }
9494
9495 Previous.clear();
9496 Previous.addDecl(FoundInstantiation);
9497 return false;
9498 }
9499
9500 // Make sure that this is a specialization of a member.
9501 if (!InstantiatedFrom) {
9502 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9503 << Member;
9504 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9505 return true;
9506 }
9507
9508 // C++ [temp.expl.spec]p6:
9509 // If a template, a member template or the member of a class template is
9510 // explicitly specialized then that specialization shall be declared
9511 // before the first use of that specialization that would cause an implicit
9512 // instantiation to take place, in every translation unit in which such a
9513 // use occurs; no diagnostic is required.
9514 assert(MSInfo && "Member specialization info missing?");
9515
9516 bool HasNoEffect = false;
9519 Instantiation,
9521 MSInfo->getPointOfInstantiation(),
9522 HasNoEffect))
9523 return true;
9524
9525 // Check the scope of this explicit specialization.
9527 InstantiatedFrom,
9528 Instantiation, Member->getLocation(),
9529 false))
9530 return true;
9531
9532 // Note that this member specialization is an "instantiation of" the
9533 // corresponding member of the original template.
9534 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9535 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9536 if (InstantiationFunction->getTemplateSpecializationKind() ==
9538 // Explicit specializations of member functions of class templates do not
9539 // inherit '=delete' from the member function they are specializing.
9540 if (InstantiationFunction->isDeleted()) {
9541 // FIXME: This assert will not hold in the presence of modules.
9542 assert(InstantiationFunction->getCanonicalDecl() ==
9543 InstantiationFunction);
9544 // FIXME: We need an update record for this AST mutation.
9545 InstantiationFunction->setDeletedAsWritten(false);
9546 }
9547 }
9548
9549 MemberFunction->setInstantiationOfMemberFunction(
9550 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9551 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9552 MemberVar->setInstantiationOfStaticDataMember(
9553 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9554 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9555 MemberClass->setInstantiationOfMemberClass(
9556 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9557 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9558 MemberEnum->setInstantiationOfMemberEnum(
9559 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9560 } else {
9561 llvm_unreachable("unknown member specialization kind");
9562 }
9563
9564 // Save the caller the trouble of having to figure out which declaration
9565 // this specialization matches.
9566 Previous.clear();
9567 Previous.addDecl(FoundInstantiation);
9568 return false;
9569}
9570
9571/// Complete the explicit specialization of a member of a class template by
9572/// updating the instantiated member to be marked as an explicit specialization.
9573///
9574/// \param OrigD The member declaration instantiated from the template.
9575/// \param Loc The location of the explicit specialization of the member.
9576template<typename DeclT>
9577static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9579 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9580 return;
9581
9582 // FIXME: Inform AST mutation listeners of this AST mutation.
9583 // FIXME: If there are multiple in-class declarations of the member (from
9584 // multiple modules, or a declaration and later definition of a member type),
9585 // should we update all of them?
9586 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9587 OrigD->setLocation(Loc);
9588}
9589
9592 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9593 if (Instantiation == Member)
9594 return;
9595
9596 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9597 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9598 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9599 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9600 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9601 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9602 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9603 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9604 else
9605 llvm_unreachable("unknown member specialization kind");
9606}
9607
9608/// Check the scope of an explicit instantiation.
9609///
9610/// \returns true if a serious error occurs, false otherwise.
9612 SourceLocation InstLoc,
9613 bool WasQualifiedName) {
9615 DeclContext *CurContext = S.CurContext->getRedeclContext();
9616
9617 if (CurContext->isRecord()) {
9618 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9619 << D;
9620 return true;
9621 }
9622
9623 // C++11 [temp.explicit]p3:
9624 // An explicit instantiation shall appear in an enclosing namespace of its
9625 // template. If the name declared in the explicit instantiation is an
9626 // unqualified name, the explicit instantiation shall appear in the
9627 // namespace where its template is declared or, if that namespace is inline
9628 // (7.3.1), any namespace from its enclosing namespace set.
9629 //
9630 // This is DR275, which we do not retroactively apply to C++98/03.
9631 if (WasQualifiedName) {
9632 if (CurContext->Encloses(OrigContext))
9633 return false;
9634 } else {
9635 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9636 return false;
9637 }
9638
9639 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9640 if (WasQualifiedName)
9641 S.Diag(InstLoc,
9642 S.getLangOpts().CPlusPlus11?
9643 diag::err_explicit_instantiation_out_of_scope :
9644 diag::warn_explicit_instantiation_out_of_scope_0x)
9645 << D << NS;
9646 else
9647 S.Diag(InstLoc,
9648 S.getLangOpts().CPlusPlus11?
9649 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9650 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9651 << D << NS;
9652 } else
9653 S.Diag(InstLoc,
9654 S.getLangOpts().CPlusPlus11?
9655 diag::err_explicit_instantiation_must_be_global :
9656 diag::warn_explicit_instantiation_must_be_global_0x)
9657 << D;
9658 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9659 return false;
9660}
9661
9662/// Common checks for whether an explicit instantiation of \p D is valid.
9664 SourceLocation InstLoc,
9665 bool WasQualifiedName,
9667 // C++ [temp.explicit]p13:
9668 // An explicit instantiation declaration shall not name a specialization of
9669 // a template with internal linkage.
9671 D->getFormalLinkage() == Linkage::Internal) {
9672 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9673 return true;
9674 }
9675
9676 // C++11 [temp.explicit]p3: [DR 275]
9677 // An explicit instantiation shall appear in an enclosing namespace of its
9678 // template.
9679 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9680 return true;
9681
9682 return false;
9683}
9684
9685/// Determine whether the given scope specifier has a template-id in it.
9687 if (!SS.isSet())
9688 return false;
9689
9690 // C++11 [temp.explicit]p3:
9691 // If the explicit instantiation is for a member function, a member class
9692 // or a static data member of a class template specialization, the name of
9693 // the class template specialization in the qualified-id for the member
9694 // name shall be a simple-template-id.
9695 //
9696 // C++98 has the same restriction, just worded differently.
9697 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9698 NNS = NNS->getPrefix())
9699 if (const Type *T = NNS->getAsType())
9700 if (isa<TemplateSpecializationType>(T))
9701 return true;
9702
9703 return false;
9704}
9705
9706/// Make a dllexport or dllimport attr on a class template specialization take
9707/// effect.
9710 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9711 assert(A && "dllExportImportClassTemplateSpecialization called "
9712 "on Def without dllexport or dllimport");
9713
9714 // We reject explicit instantiations in class scope, so there should
9715 // never be any delayed exported classes to worry about.
9716 assert(S.DelayedDllExportClasses.empty() &&
9717 "delayed exports present at explicit instantiation");
9719
9720 // Propagate attribute to base class templates.
9721 for (auto &B : Def->bases()) {
9722 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9723 B.getType()->getAsCXXRecordDecl()))
9725 }
9726
9728}
9729
9731 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9732 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9733 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9734 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9735 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9736 // Find the class template we're specializing
9737 TemplateName Name = TemplateD.get();
9738 TemplateDecl *TD = Name.getAsTemplateDecl();
9739 // Check that the specialization uses the same tag kind as the
9740 // original template.
9742 assert(Kind != TagTypeKind::Enum &&
9743 "Invalid enum tag in class template explicit instantiation!");
9744
9745 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9746
9747 if (!ClassTemplate) {
9748 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9749 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9750 << TD << NTK << llvm::to_underlying(Kind);
9751 Diag(TD->getLocation(), diag::note_previous_use);
9752 return true;
9753 }
9754
9755 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9756 Kind, /*isDefinition*/false, KWLoc,
9757 ClassTemplate->getIdentifier())) {
9758 Diag(KWLoc, diag::err_use_with_wrong_tag)
9759 << ClassTemplate
9761 ClassTemplate->getTemplatedDecl()->getKindName());
9762 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9763 diag::note_previous_use);
9764 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9765 }
9766
9767 // C++0x [temp.explicit]p2:
9768 // There are two forms of explicit instantiation: an explicit instantiation
9769 // definition and an explicit instantiation declaration. An explicit
9770 // instantiation declaration begins with the extern keyword. [...]
9771 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9774
9776 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9777 // Check for dllexport class template instantiation declarations,
9778 // except for MinGW mode.
9779 for (const ParsedAttr &AL : Attr) {
9780 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9781 Diag(ExternLoc,
9782 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9783 Diag(AL.getLoc(), diag::note_attribute);
9784 break;
9785 }
9786 }
9787
9788 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9789 Diag(ExternLoc,
9790 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9791 Diag(A->getLocation(), diag::note_attribute);
9792 }
9793 }
9794
9795 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9796 // instantiation declarations for most purposes.
9797 bool DLLImportExplicitInstantiationDef = false;
9800 // Check for dllimport class template instantiation definitions.
9801 bool DLLImport =
9802 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9803 for (const ParsedAttr &AL : Attr) {
9804 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9805 DLLImport = true;
9806 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9807 // dllexport trumps dllimport here.
9808 DLLImport = false;
9809 break;
9810 }
9811 }
9812 if (DLLImport) {
9814 DLLImportExplicitInstantiationDef = true;
9815 }
9816 }
9817
9818 // Translate the parser's template argument list in our AST format.
9819 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9820 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9821
9822 // Check that the template argument list is well-formed for this
9823 // template.
9824 bool PrimaryHasMatchedPackOnParmToNonPackOnArg = false;
9825 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9827 ClassTemplate, TemplateNameLoc, TemplateArgs,
9828 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
9829 /*UpdateArgsWithConversions=*/true,
9830 /*ConstraintsNotSatisfied=*/nullptr, /*PartialOrderingTTP=*/false,
9831 &PrimaryHasMatchedPackOnParmToNonPackOnArg))
9832 return true;
9833
9834 // Find the class template specialization declaration that
9835 // corresponds to these arguments.
9836 void *InsertPos = nullptr;
9838 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9839
9840 TemplateSpecializationKind PrevDecl_TSK
9841 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9842
9843 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9844 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9845 // Check for dllexport class template instantiation definitions in MinGW
9846 // mode, if a previous declaration of the instantiation was seen.
9847 for (const ParsedAttr &AL : Attr) {
9848 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9849 Diag(AL.getLoc(),
9850 diag::warn_attribute_dllexport_explicit_instantiation_def);
9851 break;
9852 }
9853 }
9854 }
9855
9856 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9857 SS.isSet(), TSK))
9858 return true;
9859
9861
9862 bool HasNoEffect = false;
9863 if (PrevDecl) {
9864 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9865 PrevDecl, PrevDecl_TSK,
9866 PrevDecl->getPointOfInstantiation(),
9867 HasNoEffect))
9868 return PrevDecl;
9869
9870 // Even though HasNoEffect == true means that this explicit instantiation
9871 // has no effect on semantics, we go on to put its syntax in the AST.
9872
9873 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9874 PrevDecl_TSK == TSK_Undeclared) {
9875 // Since the only prior class template specialization with these
9876 // arguments was referenced but not declared, reuse that
9877 // declaration node as our own, updating the source location
9878 // for the template name to reflect our new declaration.
9879 // (Other source locations will be updated later.)
9880 Specialization = PrevDecl;
9881 Specialization->setLocation(TemplateNameLoc);
9882 PrevDecl = nullptr;
9883 }
9884
9885 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9886 DLLImportExplicitInstantiationDef) {
9887 // The new specialization might add a dllimport attribute.
9888 HasNoEffect = false;
9889 }
9890 }
9891
9892 if (!Specialization) {
9893 // Create a new class template specialization declaration node for
9894 // this explicit specialization.
9896 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9897 ClassTemplate, CanonicalConverted, PrevDecl);
9899
9900 // A MSInheritanceAttr attached to the previous declaration must be
9901 // propagated to the new node prior to instantiation.
9902 if (PrevDecl) {
9903 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9904 auto *Clone = A->clone(getASTContext());
9905 Clone->setInherited(true);
9906 Specialization->addAttr(Clone);
9908 }
9909 }
9910
9911 if (!HasNoEffect && !PrevDecl) {
9912 // Insert the new specialization.
9913 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9914 }
9915 }
9916
9917 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9918
9919 // Set source locations for keywords.
9920 Specialization->setExternKeywordLoc(ExternLoc);
9921 Specialization->setTemplateKeywordLoc(TemplateLoc);
9922 Specialization->setBraceRange(SourceRange());
9923
9924 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9927
9928 // Add the explicit instantiation into its lexical context. However,
9929 // since explicit instantiations are never found by name lookup, we
9930 // just put it into the declaration context directly.
9931 Specialization->setLexicalDeclContext(CurContext);
9933
9934 // Syntax is now OK, so return if it has no other effect on semantics.
9935 if (HasNoEffect) {
9936 // Set the template specialization kind.
9937 Specialization->setTemplateSpecializationKind(TSK);
9938 return Specialization;
9939 }
9940
9941 // C++ [temp.explicit]p3:
9942 // A definition of a class template or class member template
9943 // shall be in scope at the point of the explicit instantiation of
9944 // the class template or class member template.
9945 //
9946 // This check comes when we actually try to perform the
9947 // instantiation.
9949 = cast_or_null<ClassTemplateSpecializationDecl>(
9950 Specialization->getDefinition());
9951 if (!Def)
9953 TemplateNameLoc, Specialization, TSK,
9954 /*Complain=*/true, PrimaryHasMatchedPackOnParmToNonPackOnArg);
9955 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9956 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9957 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9958 }
9959
9960 // Instantiate the members of this class template specialization.
9961 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9962 Specialization->getDefinition());
9963 if (Def) {
9965 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9966 // TSK_ExplicitInstantiationDefinition
9967 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9969 DLLImportExplicitInstantiationDef)) {
9970 // FIXME: Need to notify the ASTMutationListener that we did this.
9972
9973 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9975 // An explicit instantiation definition can add a dll attribute to a
9976 // template with a previous instantiation declaration. MinGW doesn't
9977 // allow this.
9978 auto *A = cast<InheritableAttr>(
9980 A->setInherited(true);
9981 Def->addAttr(A);
9983 }
9984 }
9985
9986 // Fix a TSK_ImplicitInstantiation followed by a
9987 // TSK_ExplicitInstantiationDefinition
9988 bool NewlyDLLExported =
9989 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9990 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9992 // An explicit instantiation definition can add a dll attribute to a
9993 // template with a previous implicit instantiation. MinGW doesn't allow
9994 // this. We limit clang to only adding dllexport, to avoid potentially
9995 // strange codegen behavior. For example, if we extend this conditional
9996 // to dllimport, and we have a source file calling a method on an
9997 // implicitly instantiated template class instance and then declaring a
9998 // dllimport explicit instantiation definition for the same template
9999 // class, the codegen for the method call will not respect the dllimport,
10000 // while it will with cl. The Def will already have the DLL attribute,
10001 // since the Def and Specialization will be the same in the case of
10002 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10003 // attribute to the Specialization; we just need to make it take effect.
10004 assert(Def == Specialization &&
10005 "Def and Specialization should match for implicit instantiation");
10007 }
10008
10009 // In MinGW mode, export the template instantiation if the declaration
10010 // was marked dllexport.
10011 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10012 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10013 PrevDecl->hasAttr<DLLExportAttr>()) {
10015 }
10016
10017 // Set the template specialization kind. Make sure it is set before
10018 // instantiating the members which will trigger ASTConsumer callbacks.
10019 Specialization->setTemplateSpecializationKind(TSK);
10020 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10021 } else {
10022
10023 // Set the template specialization kind.
10024 Specialization->setTemplateSpecializationKind(TSK);
10025 }
10026
10027 return Specialization;
10028}
10029
10032 SourceLocation TemplateLoc, unsigned TagSpec,
10033 SourceLocation KWLoc, CXXScopeSpec &SS,
10034 IdentifierInfo *Name, SourceLocation NameLoc,
10035 const ParsedAttributesView &Attr) {
10036
10037 bool Owned = false;
10038 bool IsDependent = false;
10039 Decl *TagD =
10040 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10041 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10042 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10043 false, TypeResult(), /*IsTypeSpecifier*/ false,
10044 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10045 .get();
10046 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10047
10048 if (!TagD)
10049 return true;
10050
10051 TagDecl *Tag = cast<TagDecl>(TagD);
10052 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10053
10054 if (Tag->isInvalidDecl())
10055 return true;
10056
10057 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10059 if (!Pattern) {
10060 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10062 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10063 return true;
10064 }
10065
10066 // C++0x [temp.explicit]p2:
10067 // If the explicit instantiation is for a class or member class, the
10068 // elaborated-type-specifier in the declaration shall include a
10069 // simple-template-id.
10070 //
10071 // C++98 has the same restriction, just worded differently.
10073 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10074 << Record << SS.getRange();
10075
10076 // C++0x [temp.explicit]p2:
10077 // There are two forms of explicit instantiation: an explicit instantiation
10078 // definition and an explicit instantiation declaration. An explicit
10079 // instantiation declaration begins with the extern keyword. [...]
10083
10084 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10085
10086 // Verify that it is okay to explicitly instantiate here.
10087 CXXRecordDecl *PrevDecl
10088 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10089 if (!PrevDecl && Record->getDefinition())
10090 PrevDecl = Record;
10091 if (PrevDecl) {
10093 bool HasNoEffect = false;
10094 assert(MSInfo && "No member specialization information?");
10095 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10096 PrevDecl,
10098 MSInfo->getPointOfInstantiation(),
10099 HasNoEffect))
10100 return true;
10101 if (HasNoEffect)
10102 return TagD;
10103 }
10104
10105 CXXRecordDecl *RecordDef
10106 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10107 if (!RecordDef) {
10108 // C++ [temp.explicit]p3:
10109 // A definition of a member class of a class template shall be in scope
10110 // at the point of an explicit instantiation of the member class.
10111 CXXRecordDecl *Def
10112 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10113 if (!Def) {
10114 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10115 << 0 << Record->getDeclName() << Record->getDeclContext();
10116 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10117 << Pattern;
10118 return true;
10119 } else {
10120 if (InstantiateClass(NameLoc, Record, Def,
10122 TSK))
10123 return true;
10124
10125 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10126 if (!RecordDef)
10127 return true;
10128 }
10129 }
10130
10131 // Instantiate all of the members of the class.
10132 InstantiateClassMembers(NameLoc, RecordDef,
10134
10136 MarkVTableUsed(NameLoc, RecordDef, true);
10137
10138 // FIXME: We don't have any representation for explicit instantiations of
10139 // member classes. Such a representation is not needed for compilation, but it
10140 // should be available for clients that want to see all of the declarations in
10141 // the source code.
10142 return TagD;
10143}
10144
10146 SourceLocation ExternLoc,
10147 SourceLocation TemplateLoc,
10148 Declarator &D) {
10149 // Explicit instantiations always require a name.
10150 // TODO: check if/when DNInfo should replace Name.
10152 DeclarationName Name = NameInfo.getName();
10153 if (!Name) {
10154 if (!D.isInvalidType())
10155 Diag(D.getDeclSpec().getBeginLoc(),
10156 diag::err_explicit_instantiation_requires_name)
10157 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10158
10159 return true;
10160 }
10161
10162 // Get the innermost enclosing declaration scope.
10163 S = S->getDeclParent();
10164
10165 // Determine the type of the declaration.
10167 QualType R = T->getType();
10168 if (R.isNull())
10169 return true;
10170
10171 // C++ [dcl.stc]p1:
10172 // A storage-class-specifier shall not be specified in [...] an explicit
10173 // instantiation (14.7.2) directive.
10174 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10175 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10176 << Name;
10177 return true;
10178 } else if (D.getDeclSpec().getStorageClassSpec()
10180 // Complain about then remove the storage class specifier.
10181 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10182 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10183
10184 D.getMutableDeclSpec().ClearStorageClassSpecs();
10185 }
10186
10187 // C++0x [temp.explicit]p1:
10188 // [...] An explicit instantiation of a function template shall not use the
10189 // inline or constexpr specifiers.
10190 // Presumably, this also applies to member functions of class templates as
10191 // well.
10192 if (D.getDeclSpec().isInlineSpecified())
10193 Diag(D.getDeclSpec().getInlineSpecLoc(),
10195 diag::err_explicit_instantiation_inline :
10196 diag::warn_explicit_instantiation_inline_0x)
10197 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10198 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10199 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10200 // not already specified.
10201 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10202 diag::err_explicit_instantiation_constexpr);
10203
10204 // A deduction guide is not on the list of entities that can be explicitly
10205 // instantiated.
10206 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10207 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10208 << /*explicit instantiation*/ 0;
10209 return true;
10210 }
10211
10212 // C++0x [temp.explicit]p2:
10213 // There are two forms of explicit instantiation: an explicit instantiation
10214 // definition and an explicit instantiation declaration. An explicit
10215 // instantiation declaration begins with the extern keyword. [...]
10219
10220 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10221 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10222 /*ObjectType=*/QualType());
10223
10224 if (!R->isFunctionType()) {
10225 // C++ [temp.explicit]p1:
10226 // A [...] static data member of a class template can be explicitly
10227 // instantiated from the member definition associated with its class
10228 // template.
10229 // C++1y [temp.explicit]p1:
10230 // A [...] variable [...] template specialization can be explicitly
10231 // instantiated from its template.
10232 if (Previous.isAmbiguous())
10233 return true;
10234
10235 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10236 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10237
10238 if (!PrevTemplate) {
10239 if (!Prev || !Prev->isStaticDataMember()) {
10240 // We expect to see a static data member here.
10241 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10242 << Name;
10243 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10244 P != PEnd; ++P)
10245 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10246 return true;
10247 }
10248
10250 // FIXME: Check for explicit specialization?
10251 Diag(D.getIdentifierLoc(),
10252 diag::err_explicit_instantiation_data_member_not_instantiated)
10253 << Prev;
10254 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10255 // FIXME: Can we provide a note showing where this was declared?
10256 return true;
10257 }
10258 } else {
10259 // Explicitly instantiate a variable template.
10260
10261 // C++1y [dcl.spec.auto]p6:
10262 // ... A program that uses auto or decltype(auto) in a context not
10263 // explicitly allowed in this section is ill-formed.
10264 //
10265 // This includes auto-typed variable template instantiations.
10266 if (R->isUndeducedType()) {
10267 Diag(T->getTypeLoc().getBeginLoc(),
10268 diag::err_auto_not_allowed_var_inst);
10269 return true;
10270 }
10271
10272 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10273 // C++1y [temp.explicit]p3:
10274 // If the explicit instantiation is for a variable, the unqualified-id
10275 // in the declaration shall be a template-id.
10276 Diag(D.getIdentifierLoc(),
10277 diag::err_explicit_instantiation_without_template_id)
10278 << PrevTemplate;
10279 Diag(PrevTemplate->getLocation(),
10280 diag::note_explicit_instantiation_here);
10281 return true;
10282 }
10283
10284 // Translate the parser's template argument list into our AST format.
10285 TemplateArgumentListInfo TemplateArgs =
10286 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10287
10288 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10289 D.getIdentifierLoc(), TemplateArgs);
10290 if (Res.isInvalid())
10291 return true;
10292
10293 if (!Res.isUsable()) {
10294 // We somehow specified dependent template arguments in an explicit
10295 // instantiation. This should probably only happen during error
10296 // recovery.
10297 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10298 return true;
10299 }
10300
10301 // Ignore access control bits, we don't need them for redeclaration
10302 // checking.
10303 Prev = cast<VarDecl>(Res.get());
10304 }
10305
10306 // C++0x [temp.explicit]p2:
10307 // If the explicit instantiation is for a member function, a member class
10308 // or a static data member of a class template specialization, the name of
10309 // the class template specialization in the qualified-id for the member
10310 // name shall be a simple-template-id.
10311 //
10312 // C++98 has the same restriction, just worded differently.
10313 //
10314 // This does not apply to variable template specializations, where the
10315 // template-id is in the unqualified-id instead.
10316 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10317 Diag(D.getIdentifierLoc(),
10318 diag::ext_explicit_instantiation_without_qualified_id)
10319 << Prev << D.getCXXScopeSpec().getRange();
10320
10321 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10322
10323 // Verify that it is okay to explicitly instantiate here.
10326 bool HasNoEffect = false;
10327 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10328 PrevTSK, POI, HasNoEffect))
10329 return true;
10330
10331 if (!HasNoEffect) {
10332 // Instantiate static data member or variable template.
10333 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10334 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10335 VTSD->setExternKeywordLoc(ExternLoc);
10336 VTSD->setTemplateKeywordLoc(TemplateLoc);
10337 }
10338
10339 // Merge attributes.
10340 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10341 if (PrevTemplate)
10342 ProcessAPINotes(Prev);
10343
10345 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10346 }
10347
10348 // Check the new variable specialization against the parsed input.
10349 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10350 Diag(T->getTypeLoc().getBeginLoc(),
10351 diag::err_invalid_var_template_spec_type)
10352 << 0 << PrevTemplate << R << Prev->getType();
10353 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10354 << 2 << PrevTemplate->getDeclName();
10355 return true;
10356 }
10357
10358 // FIXME: Create an ExplicitInstantiation node?
10359 return (Decl*) nullptr;
10360 }
10361
10362 // If the declarator is a template-id, translate the parser's template
10363 // argument list into our AST format.
10364 bool HasExplicitTemplateArgs = false;
10365 TemplateArgumentListInfo TemplateArgs;
10366 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10367 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10368 HasExplicitTemplateArgs = true;
10369 }
10370
10371 // C++ [temp.explicit]p1:
10372 // A [...] function [...] can be explicitly instantiated from its template.
10373 // A member function [...] of a class template can be explicitly
10374 // instantiated from the member definition associated with its class
10375 // template.
10376 UnresolvedSet<8> TemplateMatches;
10377 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10379 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10380 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10381 P != PEnd; ++P) {
10382 NamedDecl *Prev = *P;
10383 if (!HasExplicitTemplateArgs) {
10384 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10385 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10386 /*AdjustExceptionSpec*/true);
10387 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10388 if (Method->getPrimaryTemplate()) {
10389 TemplateMatches.addDecl(Method, P.getAccess());
10390 } else {
10391 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10392 C.FoundDecl = P.getPair();
10393 C.Function = Method;
10394 C.Viable = true;
10396 if (Method->getTrailingRequiresClause() &&
10397 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10398 /*ForOverloadResolution=*/true) ||
10399 !S.IsSatisfied)) {
10400 C.Viable = false;
10402 }
10403 }
10404 }
10405 }
10406 }
10407
10408 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10409 if (!FunTmpl)
10410 continue;
10411
10412 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10413 FunctionDecl *Specialization = nullptr;
10415 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10416 Specialization, Info);
10418 // Keep track of almost-matches.
10419 FailedTemplateCandidates.addCandidate().set(
10420 P.getPair(), FunTmpl->getTemplatedDecl(),
10421 MakeDeductionFailureInfo(Context, TDK, Info));
10422 (void)TDK;
10423 continue;
10424 }
10425
10426 // Target attributes are part of the cuda function signature, so
10427 // the cuda target of the instantiated function must match that of its
10428 // template. Given that C++ template deduction does not take
10429 // target attributes into account, we reject candidates here that
10430 // have a different target.
10431 if (LangOpts.CUDA &&
10433 /* IgnoreImplicitHDAttr = */ true) !=
10434 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10435 FailedTemplateCandidates.addCandidate().set(
10436 P.getPair(), FunTmpl->getTemplatedDecl(),
10439 continue;
10440 }
10441
10442 TemplateMatches.addDecl(Specialization, P.getAccess());
10443 }
10444
10445 FunctionDecl *Specialization = nullptr;
10446 if (!NonTemplateMatches.empty()) {
10447 unsigned Msg = 0;
10448 OverloadCandidateDisplayKind DisplayKind;
10450 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10451 Best)) {
10452 case OR_Success:
10453 case OR_Deleted:
10454 Specialization = cast<FunctionDecl>(Best->Function);
10455 break;
10456 case OR_Ambiguous:
10457 Msg = diag::err_explicit_instantiation_ambiguous;
10458 DisplayKind = OCD_AmbiguousCandidates;
10459 break;
10461 Msg = diag::err_explicit_instantiation_no_candidate;
10462 DisplayKind = OCD_AllCandidates;
10463 break;
10464 }
10465 if (Msg) {
10466 PartialDiagnostic Diag = PDiag(Msg) << Name;
10467 NonTemplateMatches.NoteCandidates(
10468 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10469 {});
10470 return true;
10471 }
10472 }
10473
10474 if (!Specialization) {
10475 // Find the most specialized function template specialization.
10477 TemplateMatches.begin(), TemplateMatches.end(),
10478 FailedTemplateCandidates, D.getIdentifierLoc(),
10479 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10480 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10481 PDiag(diag::note_explicit_instantiation_candidate));
10482
10483 if (Result == TemplateMatches.end())
10484 return true;
10485
10486 // Ignore access control bits, we don't need them for redeclaration checking.
10487 Specialization = cast<FunctionDecl>(*Result);
10488 }
10489
10490 // C++11 [except.spec]p4
10491 // In an explicit instantiation an exception-specification may be specified,
10492 // but is not required.
10493 // If an exception-specification is specified in an explicit instantiation
10494 // directive, it shall be compatible with the exception-specifications of
10495 // other declarations of that function.
10496 if (auto *FPT = R->getAs<FunctionProtoType>())
10497 if (FPT->hasExceptionSpec()) {
10498 unsigned DiagID =
10499 diag::err_mismatched_exception_spec_explicit_instantiation;
10500 if (getLangOpts().MicrosoftExt)
10501 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10503 PDiag(DiagID) << Specialization->getType(),
10504 PDiag(diag::note_explicit_instantiation_here),
10505 Specialization->getType()->getAs<FunctionProtoType>(),
10506 Specialization->getLocation(), FPT, D.getBeginLoc());
10507 // In Microsoft mode, mismatching exception specifications just cause a
10508 // warning.
10509 if (!getLangOpts().MicrosoftExt && Result)
10510 return true;
10511 }
10512
10513 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10514 Diag(D.getIdentifierLoc(),
10515 diag::err_explicit_instantiation_member_function_not_instantiated)
10517 << (Specialization->getTemplateSpecializationKind() ==
10519 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10520 return true;
10521 }
10522
10523 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10524 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10525 PrevDecl = Specialization;
10526
10527 if (PrevDecl) {
10528 bool HasNoEffect = false;
10529 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10530 PrevDecl,
10532 PrevDecl->getPointOfInstantiation(),
10533 HasNoEffect))
10534 return true;
10535
10536 // FIXME: We may still want to build some representation of this
10537 // explicit specialization.
10538 if (HasNoEffect)
10539 return (Decl*) nullptr;
10540 }
10541
10542 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10543 // functions
10544 // valarray<size_t>::valarray(size_t) and
10545 // valarray<size_t>::~valarray()
10546 // that it declared to have internal linkage with the internal_linkage
10547 // attribute. Ignore the explicit instantiation declaration in this case.
10548 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10550 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10551 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10552 RD->isInStdNamespace())
10553 return (Decl*) nullptr;
10554 }
10555
10556 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10558
10559 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10560 // instantiation declarations.
10562 Specialization->hasAttr<DLLImportAttr>() &&
10565
10566 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10567
10568 if (Specialization->isDefined()) {
10569 // Let the ASTConsumer know that this function has been explicitly
10570 // instantiated now, and its linkage might have changed.
10572 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10573 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10574
10575 // C++0x [temp.explicit]p2:
10576 // If the explicit instantiation is for a member function, a member class
10577 // or a static data member of a class template specialization, the name of
10578 // the class template specialization in the qualified-id for the member
10579 // name shall be a simple-template-id.
10580 //
10581 // C++98 has the same restriction, just worded differently.
10582 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10583 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10584 D.getCXXScopeSpec().isSet() &&
10585 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10586 Diag(D.getIdentifierLoc(),
10587 diag::ext_explicit_instantiation_without_qualified_id)
10588 << Specialization << D.getCXXScopeSpec().getRange();
10589
10591 *this,
10592 FunTmpl ? (NamedDecl *)FunTmpl
10593 : Specialization->getInstantiatedFromMemberFunction(),
10594 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10595
10596 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10597 return (Decl*) nullptr;
10598}
10599
10601 const CXXScopeSpec &SS,
10602 const IdentifierInfo *Name,
10603 SourceLocation TagLoc,
10604 SourceLocation NameLoc) {
10605 // This has to hold, because SS is expected to be defined.
10606 assert(Name && "Expected a name in a dependent tag");
10607
10608 NestedNameSpecifier *NNS = SS.getScopeRep();
10609 if (!NNS)
10610 return true;
10611
10613
10614 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10615 Diag(NameLoc, diag::err_dependent_tag_decl)
10616 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10617 << SS.getRange();
10618 return true;
10619 }
10620
10621 // Create the resulting type.
10623 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10624
10625 // Create type-source location information for this type.
10626 TypeLocBuilder TLB;
10628 TL.setElaboratedKeywordLoc(TagLoc);
10630 TL.setNameLoc(NameLoc);
10632}
10633
10635 const CXXScopeSpec &SS,
10636 const IdentifierInfo &II,
10637 SourceLocation IdLoc,
10638 ImplicitTypenameContext IsImplicitTypename) {
10639 if (SS.isInvalid())
10640 return true;
10641
10642 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10643 Diag(TypenameLoc,
10645 diag::warn_cxx98_compat_typename_outside_of_template :
10646 diag::ext_typename_outside_of_template)
10647 << FixItHint::CreateRemoval(TypenameLoc);
10648
10650 TypeSourceInfo *TSI = nullptr;
10651 QualType T =
10652 CheckTypenameType((TypenameLoc.isValid() ||
10653 IsImplicitTypename == ImplicitTypenameContext::Yes)
10656 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10657 /*DeducedTSTContext=*/true);
10658 if (T.isNull())
10659 return true;
10660 return CreateParsedType(T, TSI);
10661}
10662
10665 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10666 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10667 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10668 ASTTemplateArgsPtr TemplateArgsIn,
10669 SourceLocation RAngleLoc) {
10670 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10671 Diag(TypenameLoc,
10673 diag::warn_cxx98_compat_typename_outside_of_template :
10674 diag::ext_typename_outside_of_template)
10675 << FixItHint::CreateRemoval(TypenameLoc);
10676
10677 // Strangely, non-type results are not ignored by this lookup, so the
10678 // program is ill-formed if it finds an injected-class-name.
10679 if (TypenameLoc.isValid()) {
10680 auto *LookupRD =
10681 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10682 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10683 Diag(TemplateIILoc,
10684 diag::ext_out_of_line_qualified_id_type_names_constructor)
10685 << TemplateII << 0 /*injected-class-name used as template name*/
10686 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10687 }
10688 }
10689
10690 // Translate the parser's template argument list in our AST format.
10691 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10692 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10693
10694 TemplateName Template = TemplateIn.get();
10695 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10696 // Construct a dependent template specialization type.
10697 assert(DTN && "dependent template has non-dependent name?");
10698 assert(DTN->getQualifier() == SS.getScopeRep());
10699
10700 if (!DTN->isIdentifier()) {
10701 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10702 NoteAllFoundTemplates(Template);
10703 return true;
10704 }
10705
10707 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10708 DTN->getIdentifier(), TemplateArgs.arguments());
10709
10710 // Create source-location information for this type.
10711 TypeLocBuilder Builder;
10714 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10716 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10717 SpecTL.setTemplateNameLoc(TemplateIILoc);
10718 SpecTL.setLAngleLoc(LAngleLoc);
10719 SpecTL.setRAngleLoc(RAngleLoc);
10720 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10721 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10722 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10723 }
10724
10725 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10726 if (T.isNull())
10727 return true;
10728
10729 // Provide source-location information for the template specialization type.
10730 TypeLocBuilder Builder;
10732 = Builder.push<TemplateSpecializationTypeLoc>(T);
10733 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10734 SpecTL.setTemplateNameLoc(TemplateIILoc);
10735 SpecTL.setLAngleLoc(LAngleLoc);
10736 SpecTL.setRAngleLoc(RAngleLoc);
10737 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10738 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10739
10741 SS.getScopeRep(), T);
10742 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10743 TL.setElaboratedKeywordLoc(TypenameLoc);
10745
10746 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10747 return CreateParsedType(T, TSI);
10748}
10749
10750/// Determine whether this failed name lookup should be treated as being
10751/// disabled by a usage of std::enable_if.
10753 SourceRange &CondRange, Expr *&Cond) {
10754 // We must be looking for a ::type...
10755 if (!II.isStr("type"))
10756 return false;
10757
10758 // ... within an explicitly-written template specialization...
10759 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10760 return false;
10761 TypeLoc EnableIfTy = NNS.getTypeLoc();
10762 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10764 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10765 return false;
10766 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10767
10768 // ... which names a complete class template declaration...
10769 const TemplateDecl *EnableIfDecl =
10770 EnableIfTST->getTemplateName().getAsTemplateDecl();
10771 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10772 return false;
10773
10774 // ... called "enable_if".
10775 const IdentifierInfo *EnableIfII =
10776 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10777 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10778 return false;
10779
10780 // Assume the first template argument is the condition.
10781 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10782
10783 // Dig out the condition.
10784 Cond = nullptr;
10785 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10787 return true;
10788
10789 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10790
10791 // Ignore Boolean literals; they add no value.
10792 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10793 Cond = nullptr;
10794
10795 return true;
10796}
10797
10800 SourceLocation KeywordLoc,
10801 NestedNameSpecifierLoc QualifierLoc,
10802 const IdentifierInfo &II,
10803 SourceLocation IILoc,
10804 TypeSourceInfo **TSI,
10805 bool DeducedTSTContext) {
10806 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10807 DeducedTSTContext);
10808 if (T.isNull())
10809 return QualType();
10810
10812 if (isa<DependentNameType>(T)) {
10814 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10815 TL.setElaboratedKeywordLoc(KeywordLoc);
10816 TL.setQualifierLoc(QualifierLoc);
10817 TL.setNameLoc(IILoc);
10818 } else {
10819 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10820 TL.setElaboratedKeywordLoc(KeywordLoc);
10821 TL.setQualifierLoc(QualifierLoc);
10822 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10823 }
10824 return T;
10825}
10826
10827/// Build the type that describes a C++ typename specifier,
10828/// e.g., "typename T::type".
10831 SourceLocation KeywordLoc,
10832 NestedNameSpecifierLoc QualifierLoc,
10833 const IdentifierInfo &II,
10834 SourceLocation IILoc, bool DeducedTSTContext) {
10835 CXXScopeSpec SS;
10836 SS.Adopt(QualifierLoc);
10837
10838 DeclContext *Ctx = nullptr;
10839 if (QualifierLoc) {
10840 Ctx = computeDeclContext(SS);
10841 if (!Ctx) {
10842 // If the nested-name-specifier is dependent and couldn't be
10843 // resolved to a type, build a typename type.
10844 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10845 return Context.getDependentNameType(Keyword,
10846 QualifierLoc.getNestedNameSpecifier(),
10847 &II);
10848 }
10849
10850 // If the nested-name-specifier refers to the current instantiation,
10851 // the "typename" keyword itself is superfluous. In C++03, the
10852 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10853 // allows such extraneous "typename" keywords, and we retroactively
10854 // apply this DR to C++03 code with only a warning. In any case we continue.
10855
10856 if (RequireCompleteDeclContext(SS, Ctx))
10857 return QualType();
10858 }
10859
10860 DeclarationName Name(&II);
10861 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10862 if (Ctx)
10863 LookupQualifiedName(Result, Ctx, SS);
10864 else
10865 LookupName(Result, CurScope);
10866 unsigned DiagID = 0;
10867 Decl *Referenced = nullptr;
10868 switch (Result.getResultKind()) {
10870 // If we're looking up 'type' within a template named 'enable_if', produce
10871 // a more specific diagnostic.
10872 SourceRange CondRange;
10873 Expr *Cond = nullptr;
10874 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10875 // If we have a condition, narrow it down to the specific failed
10876 // condition.
10877 if (Cond) {
10878 Expr *FailedCond;
10879 std::string FailedDescription;
10880 std::tie(FailedCond, FailedDescription) =
10882
10883 Diag(FailedCond->getExprLoc(),
10884 diag::err_typename_nested_not_found_requirement)
10885 << FailedDescription
10886 << FailedCond->getSourceRange();
10887 return QualType();
10888 }
10889
10890 Diag(CondRange.getBegin(),
10891 diag::err_typename_nested_not_found_enable_if)
10892 << Ctx << CondRange;
10893 return QualType();
10894 }
10895
10896 DiagID = Ctx ? diag::err_typename_nested_not_found
10897 : diag::err_unknown_typename;
10898 break;
10899 }
10900
10902 // We found a using declaration that is a value. Most likely, the using
10903 // declaration itself is meant to have the 'typename' keyword.
10904 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10905 IILoc);
10906 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10907 << Name << Ctx << FullRange;
10908 if (UnresolvedUsingValueDecl *Using
10909 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10910 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10911 Diag(Loc, diag::note_using_value_decl_missing_typename)
10912 << FixItHint::CreateInsertion(Loc, "typename ");
10913 }
10914 }
10915 // Fall through to create a dependent typename type, from which we can recover
10916 // better.
10917 [[fallthrough]];
10918
10920 // Okay, it's a member of an unknown instantiation.
10921 return Context.getDependentNameType(Keyword,
10922 QualifierLoc.getNestedNameSpecifier(),
10923 &II);
10924
10926 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10927 // C++ [class.qual]p2:
10928 // In a lookup in which function names are not ignored and the
10929 // nested-name-specifier nominates a class C, if the name specified
10930 // after the nested-name-specifier, when looked up in C, is the
10931 // injected-class-name of C [...] then the name is instead considered
10932 // to name the constructor of class C.
10933 //
10934 // Unlike in an elaborated-type-specifier, function names are not ignored
10935 // in typename-specifier lookup. However, they are ignored in all the
10936 // contexts where we form a typename type with no keyword (that is, in
10937 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10938 //
10939 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10940 // ignore functions, but that appears to be an oversight.
10941 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10942 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10943 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10944 FoundRD->isInjectedClassName() &&
10945 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10946 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10947 << &II << 1 << 0 /*'typename' keyword used*/;
10948
10949 // We found a type. Build an ElaboratedType, since the
10950 // typename-specifier was just sugar.
10951 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10952 return Context.getElaboratedType(Keyword,
10953 QualifierLoc.getNestedNameSpecifier(),
10955 }
10956
10957 // C++ [dcl.type.simple]p2:
10958 // A type-specifier of the form
10959 // typename[opt] nested-name-specifier[opt] template-name
10960 // is a placeholder for a deduced class type [...].
10961 if (getLangOpts().CPlusPlus17) {
10962 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10963 if (!DeducedTSTContext) {
10964 QualType T(QualifierLoc
10965 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10966 : nullptr, 0);
10967 if (!T.isNull())
10968 Diag(IILoc, diag::err_dependent_deduced_tst)
10970 else
10971 Diag(IILoc, diag::err_deduced_tst)
10974 return QualType();
10975 }
10977 Keyword, QualifierLoc.getNestedNameSpecifier(),
10979 QualType(), false));
10980 }
10981 }
10982
10983 DiagID = Ctx ? diag::err_typename_nested_not_type
10984 : diag::err_typename_not_type;
10985 Referenced = Result.getFoundDecl();
10986 break;
10987
10989 DiagID = Ctx ? diag::err_typename_nested_not_type
10990 : diag::err_typename_not_type;
10991 Referenced = *Result.begin();
10992 break;
10993
10995 return QualType();
10996 }
10997
10998 // If we get here, it's because name lookup did not find a
10999 // type. Emit an appropriate diagnostic and return an error.
11000 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11001 IILoc);
11002 if (Ctx)
11003 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11004 else
11005 Diag(IILoc, DiagID) << FullRange << Name;
11006 if (Referenced)
11007 Diag(Referenced->getLocation(),
11008 Ctx ? diag::note_typename_member_refers_here
11009 : diag::note_typename_refers_here)
11010 << Name;
11011 return QualType();
11012}
11013
11014namespace {
11015 // See Sema::RebuildTypeInCurrentInstantiation
11016 class CurrentInstantiationRebuilder
11017 : public TreeTransform<CurrentInstantiationRebuilder> {
11019 DeclarationName Entity;
11020
11021 public:
11023
11024 CurrentInstantiationRebuilder(Sema &SemaRef,
11026 DeclarationName Entity)
11027 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11028 Loc(Loc), Entity(Entity) { }
11029
11030 /// Determine whether the given type \p T has already been
11031 /// transformed.
11032 ///
11033 /// For the purposes of type reconstruction, a type has already been
11034 /// transformed if it is NULL or if it is not dependent.
11035 bool AlreadyTransformed(QualType T) {
11036 return T.isNull() || !T->isInstantiationDependentType();
11037 }
11038
11039 /// Returns the location of the entity whose type is being
11040 /// rebuilt.
11041 SourceLocation getBaseLocation() { return Loc; }
11042
11043 /// Returns the name of the entity whose type is being rebuilt.
11044 DeclarationName getBaseEntity() { return Entity; }
11045
11046 /// Sets the "base" location and entity when that
11047 /// information is known based on another transformation.
11048 void setBase(SourceLocation Loc, DeclarationName Entity) {
11049 this->Loc = Loc;
11050 this->Entity = Entity;
11051 }
11052
11053 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11054 // Lambdas never need to be transformed.
11055 return E;
11056 }
11057 };
11058} // end anonymous namespace
11059
11062 DeclarationName Name) {
11063 if (!T || !T->getType()->isInstantiationDependentType())
11064 return T;
11065
11066 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11067 return Rebuilder.TransformType(T);
11068}
11069
11071 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11072 DeclarationName());
11073 return Rebuilder.TransformExpr(E);
11074}
11075
11077 if (SS.isInvalid())
11078 return true;
11079
11081 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11082 DeclarationName());
11084 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11085 if (!Rebuilt)
11086 return true;
11087
11088 SS.Adopt(Rebuilt);
11089 return false;
11090}
11091
11093 TemplateParameterList *Params) {
11094 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11095 Decl *Param = Params->getParam(I);
11096
11097 // There is nothing to rebuild in a type parameter.
11098 if (isa<TemplateTypeParmDecl>(Param))
11099 continue;
11100
11101 // Rebuild the template parameter list of a template template parameter.
11103 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11105 TTP->getTemplateParameters()))
11106 return true;
11107
11108 continue;
11109 }
11110
11111 // Rebuild the type of a non-type template parameter.
11112 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11113 TypeSourceInfo *NewTSI
11115 NTTP->getLocation(),
11116 NTTP->getDeclName());
11117 if (!NewTSI)
11118 return true;
11119
11120 if (NewTSI->getType()->isUndeducedType()) {
11121 // C++17 [temp.dep.expr]p3:
11122 // An id-expression is type-dependent if it contains
11123 // - an identifier associated by name lookup with a non-type
11124 // template-parameter declared with a type that contains a
11125 // placeholder type (7.1.7.4),
11126 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11127 }
11128
11129 if (NewTSI != NTTP->getTypeSourceInfo()) {
11130 NTTP->setTypeSourceInfo(NewTSI);
11131 NTTP->setType(NewTSI->getType());
11132 }
11133 }
11134
11135 return false;
11136}
11137
11138std::string
11140 const TemplateArgumentList &Args) {
11141 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11142}
11143
11144std::string
11146 const TemplateArgument *Args,
11147 unsigned NumArgs) {
11148 SmallString<128> Str;
11149 llvm::raw_svector_ostream Out(Str);
11150
11151 if (!Params || Params->size() == 0 || NumArgs == 0)
11152 return std::string();
11153
11154 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11155 if (I >= NumArgs)
11156 break;
11157
11158 if (I == 0)
11159 Out << "[with ";
11160 else
11161 Out << ", ";
11162
11163 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11164 Out << Id->getName();
11165 } else {
11166 Out << '$' << I;
11167 }
11168
11169 Out << " = ";
11170 Args[I].print(getPrintingPolicy(), Out,
11172 getPrintingPolicy(), Params, I));
11173 }
11174
11175 Out << ']';
11176 return std::string(Out.str());
11177}
11178
11180 CachedTokens &Toks) {
11181 if (!FD)
11182 return;
11183
11184 auto LPT = std::make_unique<LateParsedTemplate>();
11185
11186 // Take tokens to avoid allocations
11187 LPT->Toks.swap(Toks);
11188 LPT->D = FnD;
11189 LPT->FPO = getCurFPFeatures();
11190 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11191
11192 FD->setLateTemplateParsed(true);
11193}
11194
11196 if (!FD)
11197 return;
11198 FD->setLateTemplateParsed(false);
11199}
11200
11202 DeclContext *DC = CurContext;
11203
11204 while (DC) {
11205 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11206 const FunctionDecl *FD = RD->isLocalClass();
11207 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11208 } else if (DC->isTranslationUnit() || DC->isNamespace())
11209 return false;
11210
11211 DC = DC->getParent();
11212 }
11213 return false;
11214}
11215
11216namespace {
11217/// Walk the path from which a declaration was instantiated, and check
11218/// that every explicit specialization along that path is visible. This enforces
11219/// C++ [temp.expl.spec]/6:
11220///
11221/// If a template, a member template or a member of a class template is
11222/// explicitly specialized then that specialization shall be declared before
11223/// the first use of that specialization that would cause an implicit
11224/// instantiation to take place, in every translation unit in which such a
11225/// use occurs; no diagnostic is required.
11226///
11227/// and also C++ [temp.class.spec]/1:
11228///
11229/// A partial specialization shall be declared before the first use of a
11230/// class template specialization that would make use of the partial
11231/// specialization as the result of an implicit or explicit instantiation
11232/// in every translation unit in which such a use occurs; no diagnostic is
11233/// required.
11234class ExplicitSpecializationVisibilityChecker {
11235 Sema &S;
11239
11240public:
11241 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11243 : S(S), Loc(Loc), Kind(Kind) {}
11244
11245 void check(NamedDecl *ND) {
11246 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11247 return checkImpl(FD);
11248 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11249 return checkImpl(RD);
11250 if (auto *VD = dyn_cast<VarDecl>(ND))
11251 return checkImpl(VD);
11252 if (auto *ED = dyn_cast<EnumDecl>(ND))
11253 return checkImpl(ED);
11254 }
11255
11256private:
11257 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11258 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11259 : Sema::MissingImportKind::ExplicitSpecialization;
11260 const bool Recover = true;
11261
11262 // If we got a custom set of modules (because only a subset of the
11263 // declarations are interesting), use them, otherwise let
11264 // diagnoseMissingImport intelligently pick some.
11265 if (Modules.empty())
11266 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11267 else
11268 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11269 }
11270
11271 bool CheckMemberSpecialization(const NamedDecl *D) {
11272 return Kind == Sema::AcceptableKind::Visible
11275 }
11276
11277 bool CheckExplicitSpecialization(const NamedDecl *D) {
11278 return Kind == Sema::AcceptableKind::Visible
11281 }
11282
11283 bool CheckDeclaration(const NamedDecl *D) {
11284 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11286 }
11287
11288 // Check a specific declaration. There are three problematic cases:
11289 //
11290 // 1) The declaration is an explicit specialization of a template
11291 // specialization.
11292 // 2) The declaration is an explicit specialization of a member of an
11293 // templated class.
11294 // 3) The declaration is an instantiation of a template, and that template
11295 // is an explicit specialization of a member of a templated class.
11296 //
11297 // We don't need to go any deeper than that, as the instantiation of the
11298 // surrounding class / etc is not triggered by whatever triggered this
11299 // instantiation, and thus should be checked elsewhere.
11300 template<typename SpecDecl>
11301 void checkImpl(SpecDecl *Spec) {
11302 bool IsHiddenExplicitSpecialization = false;
11303 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11304 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11305 ? !CheckMemberSpecialization(Spec)
11306 : !CheckExplicitSpecialization(Spec);
11307 } else {
11308 checkInstantiated(Spec);
11309 }
11310
11311 if (IsHiddenExplicitSpecialization)
11312 diagnose(Spec->getMostRecentDecl(), false);
11313 }
11314
11315 void checkInstantiated(FunctionDecl *FD) {
11316 if (auto *TD = FD->getPrimaryTemplate())
11317 checkTemplate(TD);
11318 }
11319
11320 void checkInstantiated(CXXRecordDecl *RD) {
11321 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11322 if (!SD)
11323 return;
11324
11325 auto From = SD->getSpecializedTemplateOrPartial();
11326 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11327 checkTemplate(TD);
11328 else if (auto *TD =
11329 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11330 if (!CheckDeclaration(TD))
11331 diagnose(TD, true);
11332 checkTemplate(TD);
11333 }
11334 }
11335
11336 void checkInstantiated(VarDecl *RD) {
11337 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11338 if (!SD)
11339 return;
11340
11341 auto From = SD->getSpecializedTemplateOrPartial();
11342 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11343 checkTemplate(TD);
11344 else if (auto *TD =
11345 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11346 if (!CheckDeclaration(TD))
11347 diagnose(TD, true);
11348 checkTemplate(TD);
11349 }
11350 }
11351
11352 void checkInstantiated(EnumDecl *FD) {}
11353
11354 template<typename TemplDecl>
11355 void checkTemplate(TemplDecl *TD) {
11356 if (TD->isMemberSpecialization()) {
11357 if (!CheckMemberSpecialization(TD))
11358 diagnose(TD->getMostRecentDecl(), false);
11359 }
11360 }
11361};
11362} // end anonymous namespace
11363
11365 if (!getLangOpts().Modules)
11366 return;
11367
11368 ExplicitSpecializationVisibilityChecker(*this, Loc,
11370 .check(Spec);
11371}
11372
11374 NamedDecl *Spec) {
11375 if (!getLangOpts().CPlusPlusModules)
11376 return checkSpecializationVisibility(Loc, Spec);
11377
11378 ExplicitSpecializationVisibilityChecker(*this, Loc,
11380 .check(Spec);
11381}
11382
11385 return N->getLocation();
11386 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11388 return FD->getLocation();
11391 return N->getLocation();
11392 }
11393 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11394 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11395 continue;
11396 return CSC.PointOfInstantiation;
11397 }
11398 return N->getLocation();
11399}
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::@1727::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1181
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:984
APSInt & getInt()
Definition: APValue.h:489
APSInt & getComplexIntImag()
Definition: APValue.h:527
ValueKind getKind() const
Definition: APValue.h:461
APFixedPoint & getFixedPoint()
Definition: APValue.h:511
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1067
APValue & getVectorElt(unsigned I)
Definition: APValue.h:563
unsigned getVectorLength() const
Definition: APValue.h:571
bool isLValue() const
Definition: APValue.h:472
bool isMemberPointer() const
Definition: APValue.h:477
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:957
@ 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:1020
APSInt & getComplexIntReal()
Definition: APValue.h:519
APFloat & getComplexFloatImag()
Definition: APValue.h:543
APFloat & getComplexFloatReal()
Definition: APValue.h:535
APFloat & getFloat()
Definition: APValue.h:503
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h: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:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
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:2296
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:2770
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
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:2221
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2239
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2289
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2263
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2282
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2257
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2269
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:2012
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:2008
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:2023
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:422
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:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
bool isFileContext() const
Definition: DeclBase.h:2175
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2065
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1379
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
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:2047
bool isNamespace() const
Definition: DeclBase.h:2193
bool isTranslationUnit() const
Definition: DeclBase.h:2180
bool isRecord() const
Definition: DeclBase.h:2184
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2028
bool isFunctionOrMethod() const
Definition: DeclBase.h:2156
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1296
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1415
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:1054
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
T * getAttr() const
Definition: DeclBase.h:576
void addAttr(Attr *A)
Definition: DeclBase.cpp:1019
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1210
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:289
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:254
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:1012
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1060
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:1173
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2784
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:237
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:911
bool hasAttr() const
Definition: DeclBase.h:580
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:367
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
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:2455
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2435
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2444
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:2504
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2524
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2548
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2540
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2556
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2532
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:2397
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2355
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2393
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
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:4977
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:4075
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4384
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4042
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3634
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:4014
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:4248
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:4288
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:4035
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:958
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:471
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:546
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:557
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:529
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:515
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:706
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:619
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:641
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:659
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:1021
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1025
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1198
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:1222
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:742
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:858
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:863
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:5080
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:13218
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:11093
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11101
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12093
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12123
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:13152
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12652
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:15504
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:19660
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
Check that the given template argument corresponds to the given template parameter.
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:17158
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 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, bool *MatchedPackOnParmToNonPackOnArg=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
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:11064
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11638
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11641
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11645
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
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
Check a template argument against its corresponding template template parameter.
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
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:16974
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:11054
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11788
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11806
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11817
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11796
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11827
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:11114
@ 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 RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:11047
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:13971
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13959
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13968
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13962
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13986
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:14401
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:20072
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:16949
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)
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true, bool PrimaryHasMatchedPackOnParmToNonPackOnArg=false)
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:14964
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:8409
@ 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:17158
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 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:11091
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:11280
@ TPC_ClassTemplate
Definition: Sema.h:11281
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11286
@ TPC_ClassTemplateMember
Definition: Sema.h:11284
@ TPC_FunctionTemplate
Definition: Sema.h:11283
@ TPC_FriendClassTemplate
Definition: Sema.h:11285
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11287
@ TPC_TypeAliasTemplate
Definition: Sema.h:11288
@ TPC_VarTemplate
Definition: Sema.h:11282
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:21174
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:11056
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:12496
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:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
Represents 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:4776
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4859
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
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:576
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:398
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:430
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
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:1719
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1695
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1727
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1736
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1703
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1711
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:759
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:761
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:529
SourceLocation getNameLoc() const
Definition: TypeLoc.h:536
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:91
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h: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:1278
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:12669
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12776
A stack object to be created when performing template instantiation.
Definition: Sema.h:12857
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13017
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.