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"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/BitVector.h"
41#include "llvm/ADT/SmallBitVector.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44
45#include <iterator>
46#include <optional>
47using namespace clang;
48using namespace sema;
49
50// Exported for use by Parser.
53 unsigned N) {
54 if (!N) return SourceRange();
55 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56}
57
58unsigned Sema::getTemplateDepth(Scope *S) const {
59 unsigned Depth = 0;
60
61 // Each template parameter scope represents one level of template parameter
62 // depth.
63 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65 ++Depth;
66 }
67
68 // Note that there are template parameters with the given depth.
69 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70
71 // Look for parameters of an enclosing generic lambda. We don't create a
72 // template parameter scope for these.
74 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75 if (!LSI->TemplateParams.empty()) {
76 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77 break;
78 }
79 if (LSI->GLTemplateParameterList) {
80 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81 break;
82 }
83 }
84 }
85
86 // Look for parameters of an enclosing terse function template. We don't
87 // create a template parameter scope for these either.
88 for (const InventedTemplateParameterInfo &Info :
90 if (!Info.TemplateParams.empty()) {
91 ParamsAtDepth(Info.AutoTemplateParameterDepth);
92 break;
93 }
94 }
95
96 return Depth;
97}
98
99/// \brief Determine whether the declaration found is acceptable as the name
100/// of a template and, if so, return that template declaration. Otherwise,
101/// returns null.
102///
103/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104/// is true. In all other cases it will return a TemplateDecl (or null).
106 bool AllowFunctionTemplates,
107 bool AllowDependent) {
108 D = D->getUnderlyingDecl();
109
110 if (isa<TemplateDecl>(D)) {
111 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112 return nullptr;
113
114 return D;
115 }
116
117 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118 // C++ [temp.local]p1:
119 // Like normal (non-template) classes, class templates have an
120 // injected-class-name (Clause 9). The injected-class-name
121 // can be used with or without a template-argument-list. When
122 // it is used without a template-argument-list, it is
123 // equivalent to the injected-class-name followed by the
124 // template-parameters of the class template enclosed in
125 // <>. When it is used with a template-argument-list, it
126 // refers to the specified class template specialization,
127 // which could be the current specialization or another
128 // specialization.
129 if (Record->isInjectedClassName()) {
130 Record = cast<CXXRecordDecl>(Record->getDeclContext());
131 if (Record->getDescribedClassTemplate())
132 return Record->getDescribedClassTemplate();
133
134 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135 return Spec->getSpecializedTemplate();
136 }
137
138 return nullptr;
139 }
140
141 // 'using Dependent::foo;' can resolve to a template name.
142 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143 // injected-class-name).
144 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145 return D;
146
147 return nullptr;
148}
149
151 bool AllowFunctionTemplates,
152 bool AllowDependent) {
153 LookupResult::Filter filter = R.makeFilter();
154 while (filter.hasNext()) {
155 NamedDecl *Orig = filter.next();
156 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157 filter.erase();
158 }
159 filter.done();
160}
161
163 bool AllowFunctionTemplates,
164 bool AllowDependent,
165 bool AllowNonTemplateFunctions) {
166 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168 return true;
169 if (AllowNonTemplateFunctions &&
170 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171 return true;
172 }
173
174 return false;
175}
176
178 CXXScopeSpec &SS,
179 bool hasTemplateKeyword,
180 const UnqualifiedId &Name,
181 ParsedType ObjectTypePtr,
182 bool EnteringContext,
183 TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool Disambiguation) {
186 assert(getLangOpts().CPlusPlus && "No template names in C!");
187
188 DeclarationName TName;
189 MemberOfUnknownSpecialization = false;
190
191 switch (Name.getKind()) {
193 TName = DeclarationName(Name.Identifier);
194 break;
195
198 Name.OperatorFunctionId.Operator);
199 break;
200
202 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203 break;
204
205 default:
206 return TNK_Non_template;
207 }
208
209 QualType ObjectType = ObjectTypePtr.get();
210
211 AssumedTemplateKind AssumedTemplate;
212 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214 /*RequiredTemplate=*/SourceLocation(),
215 &AssumedTemplate,
216 /*AllowTypoCorrection=*/!Disambiguation))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
268 TemplateName Template;
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
280 } else {
281 if (!D) {
283 assert(D && "unambiguous result is not a template name");
284 }
285
286 if (isa<UnresolvedUsingValueDecl>(D)) {
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
292 TemplateDecl *TD = cast<TemplateDecl>(D);
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier *Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299 Template);
300 }
301
302 if (isa<FunctionTemplateDecl>(TD)) {
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
307 } else {
308 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311 TemplateKind =
312 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
313 isa<ConceptDecl>(TD) ? TNK_Concept_template :
315 }
316 }
317
318 TemplateResult = TemplateTy::make(Template);
319 return TemplateKind;
320}
321
323 SourceLocation NameLoc, CXXScopeSpec &SS,
324 ParsedTemplateTy *Template /*=nullptr*/) {
325 // We could use redeclaration lookup here, but we don't need to: the
326 // syntactic form of a deduction guide is enough to identify it even
327 // if we can't look up the template name at all.
328 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330 /*EnteringContext*/ false))
331 return false;
332
333 if (R.empty()) return false;
334 if (R.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
337 return false;
338 }
339
340 // We only treat template-names that name type templates as valid deduction
341 // guide names.
343 if (!TD || !getAsTypeTemplateDecl(TD))
344 return false;
345
346 if (Template) {
348 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
349 *Template = TemplateTy::make(Name);
350 }
351 return true;
352}
353
355 SourceLocation IILoc,
356 Scope *S,
357 const CXXScopeSpec *SS,
358 TemplateTy &SuggestedTemplate,
359 TemplateNameKind &SuggestedKind) {
360 // We can't recover unless there's a dependent scope specifier preceding the
361 // template name.
362 // FIXME: Typo correction?
363 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
365 return false;
366
367 // The code is missing a 'template' keyword prior to the dependent template
368 // name.
370 Diag(IILoc, diag::err_template_kw_missing)
371 << Qualifier << II.getName()
372 << FixItHint::CreateInsertion(IILoc, "template ");
373 SuggestedTemplate
375 SuggestedKind = TNK_Dependent_template_name;
376 return true;
377}
378
380 QualType ObjectType, bool EnteringContext,
381 RequiredTemplateKind RequiredTemplate,
383 bool AllowTypoCorrection) {
384 if (ATK)
386
387 if (SS.isInvalid())
388 return true;
389
390 Found.setTemplateNameLookup(true);
391
392 // Determine where to perform name lookup
393 DeclContext *LookupCtx = nullptr;
394 bool IsDependent = false;
395 if (!ObjectType.isNull()) {
396 // This nested-name-specifier occurs in a member access expression, e.g.,
397 // x->B::f, and we are looking into the type of the object.
398 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399 LookupCtx = computeDeclContext(ObjectType);
400 IsDependent = !LookupCtx && ObjectType->isDependentType();
401 assert((IsDependent || !ObjectType->isIncompleteType() ||
402 !ObjectType->getAs<TagType>() ||
403 ObjectType->castAs<TagType>()->isBeingDefined()) &&
404 "Caller should have completed object type");
405
406 // Template names cannot appear inside an Objective-C class or object type
407 // or a vector type.
408 //
409 // FIXME: This is wrong. For example:
410 //
411 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412 // Vec<int> vi;
413 // vi.Vec<int>::~Vec<int>();
414 //
415 // ... should be accepted but we will not treat 'Vec' as a template name
416 // here. The right thing to do would be to check if the name is a valid
417 // vector component name, and look up a template name if not. And similarly
418 // for lookups into Objective-C class and object types, where the same
419 // problem can arise.
420 if (ObjectType->isObjCObjectOrInterfaceType() ||
421 ObjectType->isVectorType()) {
422 Found.clear();
423 return false;
424 }
425 } else if (SS.isNotEmpty()) {
426 // This nested-name-specifier occurs after another nested-name-specifier,
427 // so long into the context associated with the prior nested-name-specifier.
428 LookupCtx = computeDeclContext(SS, EnteringContext);
429 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430
431 // The declaration context must be complete.
432 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433 return true;
434 }
435
436 bool ObjectTypeSearchedInScope = false;
437 bool AllowFunctionTemplatesInLookup = true;
438 if (LookupCtx) {
439 // Perform "qualified" name lookup into the declaration context we
440 // computed, which is either the type of the base of a member access
441 // expression or the declaration context associated with a prior
442 // nested-name-specifier.
443 LookupQualifiedName(Found, LookupCtx);
444
445 // FIXME: The C++ standard does not clearly specify what happens in the
446 // case where the object type is dependent, and implementations vary. In
447 // Clang, we treat a name after a . or -> as a template-name if lookup
448 // finds a non-dependent member or member of the current instantiation that
449 // is a type template, or finds no such members and lookup in the context
450 // of the postfix-expression finds a type template. In the latter case, the
451 // name is nonetheless dependent, and we may resolve it to a member of an
452 // unknown specialization when we come to instantiate the template.
453 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454 }
455
456 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457 // C++ [basic.lookup.classref]p1:
458 // In a class member access expression (5.2.5), if the . or -> token is
459 // immediately followed by an identifier followed by a <, the
460 // identifier must be looked up to determine whether the < is the
461 // beginning of a template argument list (14.2) or a less-than operator.
462 // The identifier is first looked up in the class of the object
463 // expression. If the identifier is not found, it is then looked up in
464 // the context of the entire postfix-expression and shall name a class
465 // template.
466 if (S)
467 LookupName(Found, S);
468
469 if (!ObjectType.isNull()) {
470 // FIXME: We should filter out all non-type templates here, particularly
471 // variable templates and concepts. But the exclusion of alias templates
472 // and template template parameters is a wording defect.
473 AllowFunctionTemplatesInLookup = false;
474 ObjectTypeSearchedInScope = true;
475 }
476
477 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478 }
479
480 if (Found.isAmbiguous())
481 return false;
482
483 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484 !RequiredTemplate.hasTemplateKeyword()) {
485 // C++2a [temp.names]p2:
486 // A name is also considered to refer to a template if it is an
487 // unqualified-id followed by a < and name lookup finds either one or more
488 // functions or finds nothing.
489 //
490 // To keep our behavior consistent, we apply the "finds nothing" part in
491 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492 // successfully form a call to an undeclared template-id.
493 bool AllFunctions =
494 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495 return isa<FunctionDecl>(ND->getUnderlyingDecl());
496 });
497 if (AllFunctions || (Found.empty() && !IsDependent)) {
498 // If lookup found any functions, or if this is a name that can only be
499 // used for a function, then strongly assume this is a function
500 // template-id.
501 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
504 Found.clear();
505 return false;
506 }
507 }
508
509 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510 // If we did not find any names, and this is not a disambiguation, attempt
511 // to correct any typos.
512 DeclarationName Name = Found.getLookupName();
513 Found.clear();
514 // Simple filter callback that, for keywords, only accepts the C++ *_cast
515 DefaultFilterCCC FilterCCC{};
516 FilterCCC.WantTypeSpecifiers = false;
517 FilterCCC.WantExpressionKeywords = false;
518 FilterCCC.WantRemainingKeywords = false;
519 FilterCCC.WantCXXNamedCasts = true;
520 if (TypoCorrection Corrected =
521 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523 if (auto *ND = Corrected.getFoundDecl())
524 Found.addDecl(ND);
526 if (Found.isAmbiguous()) {
527 Found.clear();
528 } else if (!Found.empty()) {
529 Found.setLookupName(Corrected.getCorrection());
530 if (LookupCtx) {
531 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533 Name.getAsString() == CorrectedStr;
534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535 << Name << LookupCtx << DroppedSpecifier
536 << SS.getRange());
537 } else {
538 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539 }
540 }
541 }
542 }
543
544 NamedDecl *ExampleLookupResult =
545 Found.empty() ? nullptr : Found.getRepresentativeDecl();
546 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547 if (Found.empty()) {
548 if (IsDependent) {
549 Found.setNotFoundInCurrentInstantiation();
550 return false;
551 }
552
553 // If a 'template' keyword was used, a lookup that finds only non-template
554 // names is an error.
555 if (ExampleLookupResult && RequiredTemplate) {
556 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557 << Found.getLookupName() << SS.getRange()
558 << RequiredTemplate.hasTemplateKeyword()
559 << RequiredTemplate.getTemplateKeywordLoc();
560 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561 diag::note_template_kw_refers_to_non_template)
562 << Found.getLookupName();
563 return true;
564 }
565
566 return false;
567 }
568
569 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
571 // C++03 [basic.lookup.classref]p1:
572 // [...] If the lookup in the class of the object expression finds a
573 // template, the name is also looked up in the context of the entire
574 // postfix-expression and [...]
575 //
576 // Note: C++11 does not perform this second lookup.
577 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
579 FoundOuter.setTemplateNameLookup(true);
580 LookupName(FoundOuter, S);
581 // FIXME: We silently accept an ambiguous lookup here, in violation of
582 // [basic.lookup]/1.
583 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584
585 NamedDecl *OuterTemplate;
586 if (FoundOuter.empty()) {
587 // - if the name is not found, the name found in the class of the
588 // object expression is used, otherwise
589 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590 !(OuterTemplate =
591 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592 // - if the name is found in the context of the entire
593 // postfix-expression and does not name a class template, the name
594 // found in the class of the object expression is used, otherwise
595 FoundOuter.clear();
596 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597 // - if the name found is a class template, it must refer to the same
598 // entity as the one found in the class of the object expression,
599 // otherwise the program is ill-formed.
600 if (!Found.isSingleResult() ||
601 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602 OuterTemplate->getCanonicalDecl()) {
603 Diag(Found.getNameLoc(),
604 diag::ext_nested_name_member_ref_lookup_ambiguous)
605 << Found.getLookupName()
606 << ObjectType;
607 Diag(Found.getRepresentativeDecl()->getLocation(),
608 diag::note_ambig_member_ref_object_type)
609 << ObjectType;
610 Diag(FoundOuter.getFoundDecl()->getLocation(),
611 diag::note_ambig_member_ref_scope);
612
613 // Recover by taking the template that we found in the object
614 // expression's type.
615 }
616 }
617 }
618
619 return false;
620}
621
625 if (TemplateName.isInvalid())
626 return;
627
628 DeclarationNameInfo NameInfo;
629 CXXScopeSpec SS;
630 LookupNameKind LookupKind;
631
632 DeclContext *LookupCtx = nullptr;
633 NamedDecl *Found = nullptr;
634 bool MissingTemplateKeyword = false;
635
636 // Figure out what name we looked up.
637 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638 NameInfo = DRE->getNameInfo();
639 SS.Adopt(DRE->getQualifierLoc());
640 LookupKind = LookupOrdinaryName;
641 Found = DRE->getFoundDecl();
642 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643 NameInfo = ME->getMemberNameInfo();
644 SS.Adopt(ME->getQualifierLoc());
645 LookupKind = LookupMemberName;
646 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647 Found = ME->getMemberDecl();
648 } else if (auto *DSDRE =
649 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650 NameInfo = DSDRE->getNameInfo();
651 SS.Adopt(DSDRE->getQualifierLoc());
652 MissingTemplateKeyword = true;
653 } else if (auto *DSME =
654 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655 NameInfo = DSME->getMemberNameInfo();
656 SS.Adopt(DSME->getQualifierLoc());
657 MissingTemplateKeyword = true;
658 } else {
659 llvm_unreachable("unexpected kind of potential template name");
660 }
661
662 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663 // was missing.
664 if (MissingTemplateKeyword) {
665 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667 return;
668 }
669
670 // Try to correct the name by looking for templates and C++ named casts.
671 struct TemplateCandidateFilter : CorrectionCandidateCallback {
672 Sema &S;
673 TemplateCandidateFilter(Sema &S) : S(S) {
674 WantTypeSpecifiers = false;
675 WantExpressionKeywords = false;
676 WantRemainingKeywords = false;
677 WantCXXNamedCasts = true;
678 };
679 bool ValidateCandidate(const TypoCorrection &Candidate) override {
680 if (auto *ND = Candidate.getCorrectionDecl())
681 return S.getAsTemplateNameDecl(ND);
682 return Candidate.isKeyword();
683 }
684
685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
686 return std::make_unique<TemplateCandidateFilter>(*this);
687 }
688 };
689
690 DeclarationName Name = NameInfo.getName();
691 TemplateCandidateFilter CCC(*this);
692 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693 CTK_ErrorRecovery, LookupCtx)) {
694 auto *ND = Corrected.getFoundDecl();
695 if (ND)
696 ND = getAsTemplateNameDecl(ND);
697 if (ND || Corrected.isKeyword()) {
698 if (LookupCtx) {
699 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701 Name.getAsString() == CorrectedStr;
702 diagnoseTypo(Corrected,
703 PDiag(diag::err_non_template_in_member_template_id_suggest)
704 << Name << LookupCtx << DroppedSpecifier
705 << SS.getRange(), false);
706 } else {
707 diagnoseTypo(Corrected,
708 PDiag(diag::err_non_template_in_template_id_suggest)
709 << Name, false);
710 }
711 if (Found)
712 Diag(Found->getLocation(),
713 diag::note_non_template_in_template_id_found);
714 return;
715 }
716 }
717
718 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719 << Name << SourceRange(Less, Greater);
720 if (Found)
721 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722}
723
726 SourceLocation TemplateKWLoc,
727 const DeclarationNameInfo &NameInfo,
728 bool isAddressOfOperand,
729 const TemplateArgumentListInfo *TemplateArgs) {
730 if (SS.isEmpty()) {
731 // FIXME: This codepath is only used by dependent unqualified names
732 // (e.g. a dependent conversion-function-id, or operator= once we support
733 // it). It doesn't quite do the right thing, and it will silently fail if
734 // getCurrentThisType() returns null.
735 QualType ThisType = getCurrentThisType();
736 if (ThisType.isNull())
737 return ExprError();
738
740 Context, /*Base=*/nullptr, ThisType,
741 /*IsArrow=*/!Context.getLangOpts().HLSL,
742 /*OperatorLoc=*/SourceLocation(),
743 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
744 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
745 }
746 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
747}
748
751 SourceLocation TemplateKWLoc,
752 const DeclarationNameInfo &NameInfo,
753 const TemplateArgumentListInfo *TemplateArgs) {
754 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
755 if (!SS.isValid())
756 return CreateRecoveryExpr(
757 SS.getBeginLoc(),
758 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
759
761 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
762 TemplateArgs);
763}
764
766 NamedDecl *Instantiation,
767 bool InstantiatedFromMember,
768 const NamedDecl *Pattern,
769 const NamedDecl *PatternDef,
771 bool Complain /*= true*/) {
772 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
773 isa<VarDecl>(Instantiation));
774
775 bool IsEntityBeingDefined = false;
776 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
777 IsEntityBeingDefined = TD->isBeingDefined();
778
779 if (PatternDef && !IsEntityBeingDefined) {
780 NamedDecl *SuggestedDef = nullptr;
781 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
782 &SuggestedDef,
783 /*OnlyNeedComplete*/ false)) {
784 // If we're allowed to diagnose this and recover, do so.
785 bool Recover = Complain && !isSFINAEContext();
786 if (Complain)
787 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
789 return !Recover;
790 }
791 return false;
792 }
793
794 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
795 return true;
796
797 QualType InstantiationTy;
798 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
799 InstantiationTy = Context.getTypeDeclType(TD);
800 if (PatternDef) {
801 Diag(PointOfInstantiation,
802 diag::err_template_instantiate_within_definition)
803 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
804 << InstantiationTy;
805 // Not much point in noting the template declaration here, since
806 // we're lexically inside it.
807 Instantiation->setInvalidDecl();
808 } else if (InstantiatedFromMember) {
809 if (isa<FunctionDecl>(Instantiation)) {
810 Diag(PointOfInstantiation,
811 diag::err_explicit_instantiation_undefined_member)
812 << /*member function*/ 1 << Instantiation->getDeclName()
813 << Instantiation->getDeclContext();
814 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
815 } else {
816 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
817 Diag(PointOfInstantiation,
818 diag::err_implicit_instantiate_member_undefined)
819 << InstantiationTy;
820 Diag(Pattern->getLocation(), diag::note_member_declared_at);
821 }
822 } else {
823 if (isa<FunctionDecl>(Instantiation)) {
824 Diag(PointOfInstantiation,
825 diag::err_explicit_instantiation_undefined_func_template)
826 << Pattern;
827 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
828 } else if (isa<TagDecl>(Instantiation)) {
829 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
830 << (TSK != TSK_ImplicitInstantiation)
831 << InstantiationTy;
832 NoteTemplateLocation(*Pattern);
833 } else {
834 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
835 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
836 Diag(PointOfInstantiation,
837 diag::err_explicit_instantiation_undefined_var_template)
838 << Instantiation;
839 Instantiation->setInvalidDecl();
840 } else
841 Diag(PointOfInstantiation,
842 diag::err_explicit_instantiation_undefined_member)
843 << /*static data member*/ 2 << Instantiation->getDeclName()
844 << Instantiation->getDeclContext();
845 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
846 }
847 }
848
849 // In general, Instantiation isn't marked invalid to get more than one
850 // error for multiple undefined instantiations. But the code that does
851 // explicit declaration -> explicit definition conversion can't handle
852 // invalid declarations, so mark as invalid in that case.
854 Instantiation->setInvalidDecl();
855 return true;
856}
857
859 bool SupportedForCompatibility) {
860 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
861
862 // C++23 [temp.local]p6:
863 // The name of a template-parameter shall not be bound to any following.
864 // declaration whose locus is contained by the scope to which the
865 // template-parameter belongs.
866 //
867 // When MSVC compatibility is enabled, the diagnostic is always a warning
868 // by default. Otherwise, it an error unless SupportedForCompatibility is
869 // true, in which case it is a default-to-error warning.
870 unsigned DiagId =
871 getLangOpts().MSVCCompat
872 ? diag::ext_template_param_shadow
873 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
874 : diag::err_template_param_shadow);
875 const auto *ND = cast<NamedDecl>(PrevDecl);
876 Diag(Loc, DiagId) << ND->getDeclName();
878}
879
881 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
882 D = Temp->getTemplatedDecl();
883 return Temp;
884 }
885 return nullptr;
886}
887
889 SourceLocation EllipsisLoc) const {
890 assert(Kind == Template &&
891 "Only template template arguments can be pack expansions here");
892 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
893 "Template template argument pack expansion without packs");
895 Result.EllipsisLoc = EllipsisLoc;
896 return Result;
897}
898
900 const ParsedTemplateArgument &Arg) {
901
902 switch (Arg.getKind()) {
904 TypeSourceInfo *DI;
905 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
906 if (!DI)
907 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
909 }
910
912 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
914 }
915
917 TemplateName Template = Arg.getAsTemplate().get();
918 TemplateArgument TArg;
919 if (Arg.getEllipsisLoc().isValid())
920 TArg = TemplateArgument(Template, std::optional<unsigned int>());
921 else
922 TArg = Template;
923 return TemplateArgumentLoc(
924 SemaRef.Context, TArg,
926 Arg.getLocation(), Arg.getEllipsisLoc());
927 }
928 }
929
930 llvm_unreachable("Unhandled parsed template argument");
931}
932
934 TemplateArgumentListInfo &TemplateArgs) {
935 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
936 TemplateArgs.addArgument(translateTemplateArgument(*this,
937 TemplateArgsIn[I]));
938}
939
942 const IdentifierInfo *Name) {
943 NamedDecl *PrevDecl =
945 RedeclarationKind::ForVisibleRedeclaration);
946 if (PrevDecl && PrevDecl->isTemplateParameter())
947 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
948}
949
951 TypeSourceInfo *TInfo;
953 if (T.isNull())
954 return ParsedTemplateArgument();
955 assert(TInfo && "template argument with no location");
956
957 // If we might have formed a deduced template specialization type, convert
958 // it to a template template argument.
959 if (getLangOpts().CPlusPlus17) {
960 TypeLoc TL = TInfo->getTypeLoc();
961 SourceLocation EllipsisLoc;
962 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
963 EllipsisLoc = PET.getEllipsisLoc();
964 TL = PET.getPatternLoc();
965 }
966
967 CXXScopeSpec SS;
968 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
969 SS.Adopt(ET.getQualifierLoc());
970 TL = ET.getNamedTypeLoc();
971 }
972
973 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
974 TemplateName Name = DTST.getTypePtr()->getTemplateName();
976 DTST.getTemplateNameLoc());
977 if (EllipsisLoc.isValid())
978 Result = Result.getTemplatePackExpansion(EllipsisLoc);
979 return Result;
980 }
981 }
982
983 // This is a normal type template argument. Note, if the type template
984 // argument is an injected-class-name for a template, it has a dual nature
985 // and can be used as either a type or a template. We handle that in
986 // convertTypeTemplateArgumentToTemplate.
989 TInfo->getTypeLoc().getBeginLoc());
990}
991
993 SourceLocation EllipsisLoc,
994 SourceLocation KeyLoc,
995 IdentifierInfo *ParamName,
996 SourceLocation ParamNameLoc,
997 unsigned Depth, unsigned Position,
998 SourceLocation EqualLoc,
999 ParsedType DefaultArg,
1000 bool HasTypeConstraint) {
1001 assert(S->isTemplateParamScope() &&
1002 "Template type parameter not in template parameter scope!");
1003
1004 bool IsParameterPack = EllipsisLoc.isValid();
1007 KeyLoc, ParamNameLoc, Depth, Position,
1008 ParamName, Typename, IsParameterPack,
1009 HasTypeConstraint);
1010 Param->setAccess(AS_public);
1011
1012 if (Param->isParameterPack())
1013 if (auto *LSI = getEnclosingLambda())
1014 LSI->LocalPacks.push_back(Param);
1015
1016 if (ParamName) {
1017 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1018
1019 // Add the template parameter into the current scope.
1020 S->AddDecl(Param);
1021 IdResolver.AddDecl(Param);
1022 }
1023
1024 // C++0x [temp.param]p9:
1025 // A default template-argument may be specified for any kind of
1026 // template-parameter that is not a template parameter pack.
1027 if (DefaultArg && IsParameterPack) {
1028 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029 DefaultArg = nullptr;
1030 }
1031
1032 // Handle the default argument, if provided.
1033 if (DefaultArg) {
1034 TypeSourceInfo *DefaultTInfo;
1035 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1036
1037 assert(DefaultTInfo && "expected source information for type");
1038
1039 // Check for unexpanded parameter packs.
1040 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1042 return Param;
1043
1044 // Check the template argument itself.
1045 if (CheckTemplateArgument(DefaultTInfo)) {
1046 Param->setInvalidDecl();
1047 return Param;
1048 }
1049
1050 Param->setDefaultArgument(
1051 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1052 }
1053
1054 return Param;
1055}
1056
1057/// Convert the parser's template argument list representation into our form.
1060 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1061 TemplateId.RAngleLoc);
1062 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1063 TemplateId.NumArgs);
1064 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1065 return TemplateArgs;
1066}
1067
1069
1070 TemplateName TN = TypeConstr->Template.get();
1071 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1072
1073 // C++2a [temp.param]p4:
1074 // [...] The concept designated by a type-constraint shall be a type
1075 // concept ([temp.concept]).
1076 if (!CD->isTypeConcept()) {
1077 Diag(TypeConstr->TemplateNameLoc,
1078 diag::err_type_constraint_non_type_concept);
1079 return true;
1080 }
1081
1082 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1083
1084 if (!WereArgsSpecified &&
1086 Diag(TypeConstr->TemplateNameLoc,
1087 diag::err_type_constraint_missing_arguments)
1088 << CD;
1089 return true;
1090 }
1091 return false;
1092}
1093
1095 TemplateIdAnnotation *TypeConstr,
1096 TemplateTypeParmDecl *ConstrainedParameter,
1097 SourceLocation EllipsisLoc) {
1098 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1099 false);
1100}
1101
1103 TemplateIdAnnotation *TypeConstr,
1104 TemplateTypeParmDecl *ConstrainedParameter,
1105 SourceLocation EllipsisLoc,
1106 bool AllowUnexpandedPack) {
1107
1108 if (CheckTypeConstraint(TypeConstr))
1109 return true;
1110
1111 TemplateName TN = TypeConstr->Template.get();
1112 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1114
1115 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1116 TypeConstr->TemplateNameLoc);
1117
1118 TemplateArgumentListInfo TemplateArgs;
1119 if (TypeConstr->LAngleLoc.isValid()) {
1120 TemplateArgs =
1121 makeTemplateArgumentListInfo(*this, *TypeConstr);
1122
1123 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1124 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1126 return true;
1127 }
1128 }
1129 }
1130 return AttachTypeConstraint(
1132 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1133 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1134 ConstrainedParameter, 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 SourceLocation EllipsisLoc) {
1192 // C++2a [temp.param]p4:
1193 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1194 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1195 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1197 *TemplateArgs) : nullptr;
1198
1199 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1200
1201 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1202 *this, NS, NameInfo, NamedConcept, FoundDecl,
1203 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1204 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1205 ParamAsArgument, ConstrainedParameter->getLocation(),
1206 [&](TemplateArgumentListInfo &ConstraintArgs) {
1207 if (TemplateArgs)
1208 for (const auto &ArgLoc : TemplateArgs->arguments())
1209 ConstraintArgs.addArgument(ArgLoc);
1210 },
1211 EllipsisLoc);
1212 if (ImmediatelyDeclaredConstraint.isInvalid())
1213 return true;
1214
1215 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1216 /*TemplateKWLoc=*/SourceLocation{},
1217 /*ConceptNameInfo=*/NameInfo,
1218 /*FoundDecl=*/FoundDecl,
1219 /*NamedConcept=*/NamedConcept,
1220 /*ArgsWritten=*/ArgsAsWritten);
1221 ConstrainedParameter->setTypeConstraint(CL,
1222 ImmediatelyDeclaredConstraint.get());
1223 return false;
1224}
1225
1227 NonTypeTemplateParmDecl *NewConstrainedParm,
1228 NonTypeTemplateParmDecl *OrigConstrainedParm,
1229 SourceLocation EllipsisLoc) {
1230 if (NewConstrainedParm->getType() != TL.getType() ||
1232 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1233 diag::err_unsupported_placeholder_constraint)
1234 << NewConstrainedParm->getTypeSourceInfo()
1235 ->getTypeLoc()
1236 .getSourceRange();
1237 return true;
1238 }
1239 // FIXME: Concepts: This should be the type of the placeholder, but this is
1240 // unclear in the wording right now.
1241 DeclRefExpr *Ref =
1242 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1243 VK_PRValue, OrigConstrainedParm->getLocation());
1244 if (!Ref)
1245 return true;
1246 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1248 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1250 OrigConstrainedParm->getLocation(),
1251 [&](TemplateArgumentListInfo &ConstraintArgs) {
1252 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1253 ConstraintArgs.addArgument(TL.getArgLoc(I));
1254 },
1255 EllipsisLoc);
1256 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1257 !ImmediatelyDeclaredConstraint.isUsable())
1258 return true;
1259
1260 NewConstrainedParm->setPlaceholderTypeConstraint(
1261 ImmediatelyDeclaredConstraint.get());
1262 return false;
1263}
1264
1267 if (TSI->getType()->isUndeducedType()) {
1268 // C++17 [temp.dep.expr]p3:
1269 // An id-expression is type-dependent if it contains
1270 // - an identifier associated by name lookup with a non-type
1271 // template-parameter declared with a type that contains a
1272 // placeholder type (7.1.7.4),
1274 }
1275
1277}
1278
1280 if (T->isDependentType())
1281 return false;
1282
1283 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1284 return true;
1285
1286 if (T->isStructuralType())
1287 return false;
1288
1289 // Structural types are required to be object types or lvalue references.
1290 if (T->isRValueReferenceType()) {
1291 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1292 return true;
1293 }
1294
1295 // Don't mention structural types in our diagnostic prior to C++20. Also,
1296 // there's not much more we can say about non-scalar non-class types --
1297 // because we can't see functions or arrays here, those can only be language
1298 // extensions.
1299 if (!getLangOpts().CPlusPlus20 ||
1300 (!T->isScalarType() && !T->isRecordType())) {
1301 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1302 return true;
1303 }
1304
1305 // Structural types are required to be literal types.
1306 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1307 return true;
1308
1309 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1310
1311 // Drill down into the reason why the class is non-structural.
1312 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1313 // All members are required to be public and non-mutable, and can't be of
1314 // rvalue reference type. Check these conditions first to prefer a "local"
1315 // reason over a more distant one.
1316 for (const FieldDecl *FD : RD->fields()) {
1317 if (FD->getAccess() != AS_public) {
1318 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1319 return true;
1320 }
1321 if (FD->isMutable()) {
1322 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1323 return true;
1324 }
1325 if (FD->getType()->isRValueReferenceType()) {
1326 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1327 << T;
1328 return true;
1329 }
1330 }
1331
1332 // All bases are required to be public.
1333 for (const auto &BaseSpec : RD->bases()) {
1334 if (BaseSpec.getAccessSpecifier() != AS_public) {
1335 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1336 << T << 1;
1337 return true;
1338 }
1339 }
1340
1341 // All subobjects are required to be of structural types.
1342 SourceLocation SubLoc;
1343 QualType SubType;
1344 int Kind = -1;
1345
1346 for (const FieldDecl *FD : RD->fields()) {
1347 QualType T = Context.getBaseElementType(FD->getType());
1348 if (!T->isStructuralType()) {
1349 SubLoc = FD->getLocation();
1350 SubType = T;
1351 Kind = 0;
1352 break;
1353 }
1354 }
1355
1356 if (Kind == -1) {
1357 for (const auto &BaseSpec : RD->bases()) {
1358 QualType T = BaseSpec.getType();
1359 if (!T->isStructuralType()) {
1360 SubLoc = BaseSpec.getBaseTypeLoc();
1361 SubType = T;
1362 Kind = 1;
1363 break;
1364 }
1365 }
1366 }
1367
1368 assert(Kind != -1 && "couldn't find reason why type is not structural");
1369 Diag(SubLoc, diag::note_not_structural_subobject)
1370 << T << Kind << SubType;
1371 T = SubType;
1372 RD = T->getAsCXXRecordDecl();
1373 }
1374
1375 return true;
1376}
1377
1380 // We don't allow variably-modified types as the type of non-type template
1381 // parameters.
1382 if (T->isVariablyModifiedType()) {
1383 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1384 << T;
1385 return QualType();
1386 }
1387
1388 // C++ [temp.param]p4:
1389 //
1390 // A non-type template-parameter shall have one of the following
1391 // (optionally cv-qualified) types:
1392 //
1393 // -- integral or enumeration type,
1395 // -- pointer to object or pointer to function,
1396 T->isPointerType() ||
1397 // -- lvalue reference to object or lvalue reference to function,
1399 // -- pointer to member,
1401 // -- std::nullptr_t, or
1402 T->isNullPtrType() ||
1403 // -- a type that contains a placeholder type.
1404 T->isUndeducedType()) {
1405 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1406 // are ignored when determining its type.
1407 return T.getUnqualifiedType();
1408 }
1409
1410 // C++ [temp.param]p8:
1411 //
1412 // A non-type template-parameter of type "array of T" or
1413 // "function returning T" is adjusted to be of type "pointer to
1414 // T" or "pointer to function returning T", respectively.
1415 if (T->isArrayType() || T->isFunctionType())
1416 return Context.getDecayedType(T);
1417
1418 // If T is a dependent type, we can't do the check now, so we
1419 // assume that it is well-formed. Note that stripping off the
1420 // qualifiers here is not really correct if T turns out to be
1421 // an array type, but we'll recompute the type everywhere it's
1422 // used during instantiation, so that should be OK. (Using the
1423 // qualified type is equally wrong.)
1424 if (T->isDependentType())
1425 return T.getUnqualifiedType();
1426
1427 // C++20 [temp.param]p6:
1428 // -- a structural type
1430 return QualType();
1431
1432 if (!getLangOpts().CPlusPlus20) {
1433 // FIXME: Consider allowing structural types as an extension in C++17. (In
1434 // earlier language modes, the template argument evaluation rules are too
1435 // inflexible.)
1436 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1437 return QualType();
1438 }
1439
1440 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1441 return T.getUnqualifiedType();
1442}
1443
1445 unsigned Depth,
1446 unsigned Position,
1447 SourceLocation EqualLoc,
1448 Expr *Default) {
1450
1451 // Check that we have valid decl-specifiers specified.
1452 auto CheckValidDeclSpecifiers = [this, &D] {
1453 // C++ [temp.param]
1454 // p1
1455 // template-parameter:
1456 // ...
1457 // parameter-declaration
1458 // p2
1459 // ... A storage class shall not be specified in a template-parameter
1460 // declaration.
1461 // [dcl.typedef]p1:
1462 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1463 // of a parameter-declaration
1464 const DeclSpec &DS = D.getDeclSpec();
1465 auto EmitDiag = [this](SourceLocation Loc) {
1466 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1468 };
1470 EmitDiag(DS.getStorageClassSpecLoc());
1471
1473 EmitDiag(DS.getThreadStorageClassSpecLoc());
1474
1475 // [dcl.inline]p1:
1476 // The inline specifier can be applied only to the declaration or
1477 // definition of a variable or function.
1478
1479 if (DS.isInlineSpecified())
1480 EmitDiag(DS.getInlineSpecLoc());
1481
1482 // [dcl.constexpr]p1:
1483 // The constexpr specifier shall be applied only to the definition of a
1484 // variable or variable template or the declaration of a function or
1485 // function template.
1486
1487 if (DS.hasConstexprSpecifier())
1488 EmitDiag(DS.getConstexprSpecLoc());
1489
1490 // [dcl.fct.spec]p1:
1491 // Function-specifiers can be used only in function declarations.
1492
1493 if (DS.isVirtualSpecified())
1494 EmitDiag(DS.getVirtualSpecLoc());
1495
1496 if (DS.hasExplicitSpecifier())
1497 EmitDiag(DS.getExplicitSpecLoc());
1498
1499 if (DS.isNoreturnSpecified())
1500 EmitDiag(DS.getNoreturnSpecLoc());
1501 };
1502
1503 CheckValidDeclSpecifiers();
1504
1505 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1506 if (isa<AutoType>(T))
1507 Diag(D.getIdentifierLoc(),
1508 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1509 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1510
1511 assert(S->isTemplateParamScope() &&
1512 "Non-type template parameter not in template parameter scope!");
1513 bool Invalid = false;
1514
1515 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1516 if (T.isNull()) {
1517 T = Context.IntTy; // Recover with an 'int' type.
1518 Invalid = true;
1519 }
1520
1522
1523 const IdentifierInfo *ParamName = D.getIdentifier();
1524 bool IsParameterPack = D.hasEllipsis();
1527 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1528 TInfo);
1529 Param->setAccess(AS_public);
1530
1532 if (TL.isConstrained())
1533 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1534 Invalid = true;
1535
1536 if (Invalid)
1537 Param->setInvalidDecl();
1538
1539 if (Param->isParameterPack())
1540 if (auto *LSI = getEnclosingLambda())
1541 LSI->LocalPacks.push_back(Param);
1542
1543 if (ParamName) {
1544 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1545 ParamName);
1546
1547 // Add the template parameter into the current scope.
1548 S->AddDecl(Param);
1549 IdResolver.AddDecl(Param);
1550 }
1551
1552 // C++0x [temp.param]p9:
1553 // A default template-argument may be specified for any kind of
1554 // template-parameter that is not a template parameter pack.
1555 if (Default && IsParameterPack) {
1556 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1557 Default = nullptr;
1558 }
1559
1560 // Check the well-formedness of the default template argument, if provided.
1561 if (Default) {
1562 // Check for unexpanded parameter packs.
1564 return Param;
1565
1566 Param->setDefaultArgument(
1568 QualType(), SourceLocation()));
1569 }
1570
1571 return Param;
1572}
1573
1575 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1576 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1577 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1579 assert(S->isTemplateParamScope() &&
1580 "Template template parameter not in template parameter scope!");
1581
1582 // Construct the parameter object.
1583 bool IsParameterPack = EllipsisLoc.isValid();
1586 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1587 Name, Typename, Params);
1588 Param->setAccess(AS_public);
1589
1590 if (Param->isParameterPack())
1591 if (auto *LSI = getEnclosingLambda())
1592 LSI->LocalPacks.push_back(Param);
1593
1594 // If the template template parameter has a name, then link the identifier
1595 // into the scope and lookup mechanisms.
1596 if (Name) {
1597 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1598
1599 S->AddDecl(Param);
1600 IdResolver.AddDecl(Param);
1601 }
1602
1603 if (Params->size() == 0) {
1604 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1605 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1606 Param->setInvalidDecl();
1607 }
1608
1609 // C++0x [temp.param]p9:
1610 // A default template-argument may be specified for any kind of
1611 // template-parameter that is not a template parameter pack.
1612 if (IsParameterPack && !Default.isInvalid()) {
1613 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1615 }
1616
1617 if (!Default.isInvalid()) {
1618 // Check only that we have a template template argument. We don't want to
1619 // try to check well-formedness now, because our template template parameter
1620 // might have dependent types in its template parameters, which we wouldn't
1621 // be able to match now.
1622 //
1623 // If none of the template template parameter's template arguments mention
1624 // other template parameters, we could actually perform more checking here.
1625 // However, it isn't worth doing.
1627 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1628 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1629 << DefaultArg.getSourceRange();
1630 return Param;
1631 }
1632
1633 // Check for unexpanded parameter packs.
1635 DefaultArg.getArgument().getAsTemplate(),
1637 return Param;
1638
1639 Param->setDefaultArgument(Context, DefaultArg);
1640 }
1641
1642 return Param;
1643}
1644
1645namespace {
1646class ConstraintRefersToContainingTemplateChecker
1647 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1648 bool Result = false;
1649 const FunctionDecl *Friend = nullptr;
1650 unsigned TemplateDepth = 0;
1651
1652 // Check a record-decl that we've seen to see if it is a lexical parent of the
1653 // Friend, likely because it was referred to without its template arguments.
1654 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1655 CheckingRD = CheckingRD->getMostRecentDecl();
1656 if (!CheckingRD->isTemplated())
1657 return;
1658
1659 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1660 DC && !DC->isFileContext(); DC = DC->getParent())
1661 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1662 if (CheckingRD == RD->getMostRecentDecl())
1663 Result = true;
1664 }
1665
1666 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1667 assert(D->getDepth() <= TemplateDepth &&
1668 "Nothing should reference a value below the actual template depth, "
1669 "depth is likely wrong");
1670 if (D->getDepth() != TemplateDepth)
1671 Result = true;
1672
1673 // Necessary because the type of the NTTP might be what refers to the parent
1674 // constriant.
1675 TransformType(D->getType());
1676 }
1677
1678public:
1680
1681 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1682 const FunctionDecl *Friend,
1683 unsigned TemplateDepth)
1684 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1685 bool getResult() const { return Result; }
1686
1687 // This should be the only template parm type that we have to deal with.
1688 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1689 // FunctionParmPackExpr are all partially substituted, which cannot happen
1690 // with concepts at this point in translation.
1691 using inherited::TransformTemplateTypeParmType;
1692 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1693 TemplateTypeParmTypeLoc TL, bool) {
1694 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1695 "Nothing should reference a value below the actual template depth, "
1696 "depth is likely wrong");
1697 if (TL.getDecl()->getDepth() != TemplateDepth)
1698 Result = true;
1699 return inherited::TransformTemplateTypeParmType(
1700 TLB, TL,
1701 /*SuppressObjCLifetime=*/false);
1702 }
1703
1704 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1705 if (!D)
1706 return D;
1707 // FIXME : This is possibly an incomplete list, but it is unclear what other
1708 // Decl kinds could be used to refer to the template parameters. This is a
1709 // best guess so far based on examples currently available, but the
1710 // unreachable should catch future instances/cases.
1711 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1712 TransformType(TD->getUnderlyingType());
1713 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1714 CheckNonTypeTemplateParmDecl(NTTPD);
1715 else if (auto *VD = dyn_cast<ValueDecl>(D))
1716 TransformType(VD->getType());
1717 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1718 TransformTemplateParameterList(TD->getTemplateParameters());
1719 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1720 CheckIfContainingRecord(RD);
1721 else if (isa<NamedDecl>(D)) {
1722 // No direct types to visit here I believe.
1723 } else
1724 llvm_unreachable("Don't know how to handle this declaration type yet");
1725 return D;
1726 }
1727};
1728} // namespace
1729
1731 const FunctionDecl *Friend, unsigned TemplateDepth,
1732 const Expr *Constraint) {
1733 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1734 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1735 TemplateDepth);
1736 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1737 return Checker.getResult();
1738}
1739
1742 SourceLocation ExportLoc,
1743 SourceLocation TemplateLoc,
1744 SourceLocation LAngleLoc,
1745 ArrayRef<NamedDecl *> Params,
1746 SourceLocation RAngleLoc,
1747 Expr *RequiresClause) {
1748 if (ExportLoc.isValid())
1749 Diag(ExportLoc, diag::warn_template_export_unsupported);
1750
1751 for (NamedDecl *P : Params)
1753
1755 Context, TemplateLoc, LAngleLoc,
1756 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1757}
1758
1760 const CXXScopeSpec &SS) {
1761 if (SS.isSet())
1762 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1763}
1764
1765// Returns the template parameter list with all default template argument
1766// information.
1768 // Make sure we get the template parameter list from the most
1769 // recent declaration, since that is the only one that is guaranteed to
1770 // have all the default template argument information.
1771 Decl *D = TD->getMostRecentDecl();
1772 // C++11 N3337 [temp.param]p12:
1773 // A default template argument shall not be specified in a friend class
1774 // template declaration.
1775 //
1776 // Skip past friend *declarations* because they are not supposed to contain
1777 // default template arguments. Moreover, these declarations may introduce
1778 // template parameters living in different template depths than the
1779 // corresponding template parameters in TD, causing unmatched constraint
1780 // substitution.
1781 //
1782 // FIXME: Diagnose such cases within a class template:
1783 // template <class T>
1784 // struct S {
1785 // template <class = void> friend struct C;
1786 // };
1787 // template struct S<int>;
1789 D->getPreviousDecl())
1790 D = D->getPreviousDecl();
1791 return cast<TemplateDecl>(D)->getTemplateParameters();
1792}
1793
1795 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1796 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1797 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1798 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1799 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1800 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1801 assert(TemplateParams && TemplateParams->size() > 0 &&
1802 "No template parameters");
1803 assert(TUK != TagUseKind::Reference &&
1804 "Can only declare or define class templates");
1805 bool Invalid = false;
1806
1807 // Check that we can declare a template here.
1808 if (CheckTemplateDeclScope(S, TemplateParams))
1809 return true;
1810
1812 assert(Kind != TagTypeKind::Enum &&
1813 "can't build template of enumerated type");
1814
1815 // There is no such thing as an unnamed class template.
1816 if (!Name) {
1817 Diag(KWLoc, diag::err_template_unnamed_class);
1818 return true;
1819 }
1820
1821 // Find any previous declaration with this name. For a friend with no
1822 // scope explicitly specified, we only look for tag declarations (per
1823 // C++11 [basic.lookup.elab]p2).
1824 DeclContext *SemanticContext;
1825 LookupResult Previous(*this, Name, NameLoc,
1826 (SS.isEmpty() && TUK == TagUseKind::Friend)
1830 if (SS.isNotEmpty() && !SS.isInvalid()) {
1831 SemanticContext = computeDeclContext(SS, true);
1832 if (!SemanticContext) {
1833 // FIXME: Horrible, horrible hack! We can't currently represent this
1834 // in the AST, and historically we have just ignored such friend
1835 // class templates, so don't complain here.
1836 Diag(NameLoc, TUK == TagUseKind::Friend
1837 ? diag::warn_template_qualified_friend_ignored
1838 : diag::err_template_qualified_declarator_no_match)
1839 << SS.getScopeRep() << SS.getRange();
1840 return TUK != TagUseKind::Friend;
1841 }
1842
1843 if (RequireCompleteDeclContext(SS, SemanticContext))
1844 return true;
1845
1846 // If we're adding a template to a dependent context, we may need to
1847 // rebuilding some of the types used within the template parameter list,
1848 // now that we know what the current instantiation is.
1849 if (SemanticContext->isDependentContext()) {
1850 ContextRAII SavedContext(*this, SemanticContext);
1852 Invalid = true;
1853 }
1854
1855 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1856 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1857 /*TemplateId-*/ nullptr,
1858 /*IsMemberSpecialization*/ false);
1859
1860 LookupQualifiedName(Previous, SemanticContext);
1861 } else {
1862 SemanticContext = CurContext;
1863
1864 // C++14 [class.mem]p14:
1865 // If T is the name of a class, then each of the following shall have a
1866 // name different from T:
1867 // -- every member template of class T
1868 if (TUK != TagUseKind::Friend &&
1869 DiagnoseClassNameShadow(SemanticContext,
1870 DeclarationNameInfo(Name, NameLoc)))
1871 return true;
1872
1873 LookupName(Previous, S);
1874 }
1875
1876 if (Previous.isAmbiguous())
1877 return true;
1878
1879 NamedDecl *PrevDecl = nullptr;
1880 if (Previous.begin() != Previous.end())
1881 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1882
1883 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1884 // Maybe we will complain about the shadowed template parameter.
1885 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1886 // Just pretend that we didn't see the previous declaration.
1887 PrevDecl = nullptr;
1888 }
1889
1890 // If there is a previous declaration with the same name, check
1891 // whether this is a valid redeclaration.
1892 ClassTemplateDecl *PrevClassTemplate =
1893 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1894
1895 // We may have found the injected-class-name of a class template,
1896 // class template partial specialization, or class template specialization.
1897 // In these cases, grab the template that is being defined or specialized.
1898 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1899 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1900 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1901 PrevClassTemplate
1902 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1903 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1904 PrevClassTemplate
1905 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1906 ->getSpecializedTemplate();
1907 }
1908 }
1909
1910 if (TUK == TagUseKind::Friend) {
1911 // C++ [namespace.memdef]p3:
1912 // [...] When looking for a prior declaration of a class or a function
1913 // declared as a friend, and when the name of the friend class or
1914 // function is neither a qualified name nor a template-id, scopes outside
1915 // the innermost enclosing namespace scope are not considered.
1916 if (!SS.isSet()) {
1917 DeclContext *OutermostContext = CurContext;
1918 while (!OutermostContext->isFileContext())
1919 OutermostContext = OutermostContext->getLookupParent();
1920
1921 if (PrevDecl &&
1922 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1923 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1924 SemanticContext = PrevDecl->getDeclContext();
1925 } else {
1926 // Declarations in outer scopes don't matter. However, the outermost
1927 // context we computed is the semantic context for our new
1928 // declaration.
1929 PrevDecl = PrevClassTemplate = nullptr;
1930 SemanticContext = OutermostContext;
1931
1932 // Check that the chosen semantic context doesn't already contain a
1933 // declaration of this name as a non-tag type.
1935 DeclContext *LookupContext = SemanticContext;
1936 while (LookupContext->isTransparentContext())
1937 LookupContext = LookupContext->getLookupParent();
1938 LookupQualifiedName(Previous, LookupContext);
1939
1940 if (Previous.isAmbiguous())
1941 return true;
1942
1943 if (Previous.begin() != Previous.end())
1944 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1945 }
1946 }
1947 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1948 SemanticContext, S, SS.isValid()))
1949 PrevDecl = PrevClassTemplate = nullptr;
1950
1951 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1952 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1953 if (SS.isEmpty() &&
1954 !(PrevClassTemplate &&
1955 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1956 SemanticContext->getRedeclContext()))) {
1957 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1958 Diag(Shadow->getTargetDecl()->getLocation(),
1959 diag::note_using_decl_target);
1960 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1961 // Recover by ignoring the old declaration.
1962 PrevDecl = PrevClassTemplate = nullptr;
1963 }
1964 }
1965
1966 if (PrevClassTemplate) {
1967 // Ensure that the template parameter lists are compatible. Skip this check
1968 // for a friend in a dependent context: the template parameter list itself
1969 // could be dependent.
1970 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1972 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1973 : CurContext,
1974 CurContext, KWLoc),
1975 TemplateParams, PrevClassTemplate,
1976 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1978 return true;
1979
1980 // C++ [temp.class]p4:
1981 // In a redeclaration, partial specialization, explicit
1982 // specialization or explicit instantiation of a class template,
1983 // the class-key shall agree in kind with the original class
1984 // template declaration (7.1.5.3).
1985 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1987 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
1988 Diag(KWLoc, diag::err_use_with_wrong_tag)
1989 << Name
1990 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1991 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1992 Kind = PrevRecordDecl->getTagKind();
1993 }
1994
1995 // Check for redefinition of this class template.
1996 if (TUK == TagUseKind::Definition) {
1997 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1998 // If we have a prior definition that is not visible, treat this as
1999 // simply making that previous definition visible.
2000 NamedDecl *Hidden = nullptr;
2001 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2002 SkipBody->ShouldSkip = true;
2003 SkipBody->Previous = Def;
2004 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2005 assert(Tmpl && "original definition of a class template is not a "
2006 "class template?");
2009 } else {
2010 Diag(NameLoc, diag::err_redefinition) << Name;
2011 Diag(Def->getLocation(), diag::note_previous_definition);
2012 // FIXME: Would it make sense to try to "forget" the previous
2013 // definition, as part of error recovery?
2014 return true;
2015 }
2016 }
2017 }
2018 } else if (PrevDecl) {
2019 // C++ [temp]p5:
2020 // A class template shall not have the same name as any other
2021 // template, class, function, object, enumeration, enumerator,
2022 // namespace, or type in the same scope (3.3), except as specified
2023 // in (14.5.4).
2024 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2025 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2026 return true;
2027 }
2028
2029 // Check the template parameter list of this declaration, possibly
2030 // merging in the template parameter list from the previous class
2031 // template declaration. Skip this check for a friend in a dependent
2032 // context, because the template parameter list might be dependent.
2033 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2035 TemplateParams,
2036 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2037 : nullptr,
2038 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2039 SemanticContext->isDependentContext())
2043 SkipBody))
2044 Invalid = true;
2045
2046 if (SS.isSet()) {
2047 // If the name of the template was qualified, we must be defining the
2048 // template out-of-line.
2049 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2050 Diag(NameLoc, TUK == TagUseKind::Friend
2051 ? diag::err_friend_decl_does_not_match
2052 : diag::err_member_decl_does_not_match)
2053 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2054 Invalid = true;
2055 }
2056 }
2057
2058 // If this is a templated friend in a dependent context we should not put it
2059 // on the redecl chain. In some cases, the templated friend can be the most
2060 // recent declaration tricking the template instantiator to make substitutions
2061 // there.
2062 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2063 bool ShouldAddRedecl =
2065
2066 CXXRecordDecl *NewClass =
2067 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2068 PrevClassTemplate && ShouldAddRedecl ?
2069 PrevClassTemplate->getTemplatedDecl() : nullptr,
2070 /*DelayTypeCreation=*/true);
2071 SetNestedNameSpecifier(*this, NewClass, SS);
2072 if (NumOuterTemplateParamLists > 0)
2074 Context,
2075 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2076
2077 // Add alignment attributes if necessary; these attributes are checked when
2078 // the ASTContext lays out the structure.
2079 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2082 }
2083
2084 ClassTemplateDecl *NewTemplate
2085 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2086 DeclarationName(Name), TemplateParams,
2087 NewClass);
2088
2089 if (ShouldAddRedecl)
2090 NewTemplate->setPreviousDecl(PrevClassTemplate);
2091
2092 NewClass->setDescribedClassTemplate(NewTemplate);
2093
2094 if (ModulePrivateLoc.isValid())
2095 NewTemplate->setModulePrivate();
2096
2097 // Build the type for the class template declaration now.
2099 T = Context.getInjectedClassNameType(NewClass, T);
2100 assert(T->isDependentType() && "Class template type is not dependent?");
2101 (void)T;
2102
2103 // If we are providing an explicit specialization of a member that is a
2104 // class template, make a note of that.
2105 if (PrevClassTemplate &&
2106 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2107 PrevClassTemplate->setMemberSpecialization();
2108
2109 // Set the access specifier.
2110 if (!Invalid && TUK != TagUseKind::Friend &&
2111 NewTemplate->getDeclContext()->isRecord())
2112 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2113
2114 // Set the lexical context of these templates
2116 NewTemplate->setLexicalDeclContext(CurContext);
2117
2118 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2119 NewClass->startDefinition();
2120
2121 ProcessDeclAttributeList(S, NewClass, Attr);
2122 ProcessAPINotes(NewClass);
2123
2124 if (PrevClassTemplate)
2125 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2126
2130
2131 if (TUK != TagUseKind::Friend) {
2132 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2133 Scope *Outer = S;
2134 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2135 Outer = Outer->getParent();
2136 PushOnScopeChains(NewTemplate, Outer);
2137 } else {
2138 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2139 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2140 NewClass->setAccess(PrevClassTemplate->getAccess());
2141 }
2142
2143 NewTemplate->setObjectOfFriendDecl();
2144
2145 // Friend templates are visible in fairly strange ways.
2147 DeclContext *DC = SemanticContext->getRedeclContext();
2148 DC->makeDeclVisibleInContext(NewTemplate);
2149 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2150 PushOnScopeChains(NewTemplate, EnclosingScope,
2151 /* AddToContext = */ false);
2152 }
2153
2155 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2156 Friend->setAccess(AS_public);
2158 }
2159
2160 if (PrevClassTemplate)
2161 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2162
2163 if (Invalid) {
2164 NewTemplate->setInvalidDecl();
2165 NewClass->setInvalidDecl();
2166 }
2167
2168 ActOnDocumentableDecl(NewTemplate);
2169
2170 if (SkipBody && SkipBody->ShouldSkip)
2171 return SkipBody->Previous;
2172
2173 return NewTemplate;
2174}
2175
2176/// Diagnose the presence of a default template argument on a
2177/// template parameter, which is ill-formed in certain contexts.
2178///
2179/// \returns true if the default template argument should be dropped.
2182 SourceLocation ParamLoc,
2183 SourceRange DefArgRange) {
2184 switch (TPC) {
2188 return false;
2189
2192 // C++ [temp.param]p9:
2193 // A default template-argument shall not be specified in a
2194 // function template declaration or a function template
2195 // definition [...]
2196 // If a friend function template declaration specifies a default
2197 // template-argument, that declaration shall be a definition and shall be
2198 // the only declaration of the function template in the translation unit.
2199 // (C++98/03 doesn't have this wording; see DR226).
2200 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2201 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2202 : diag::ext_template_parameter_default_in_function_template)
2203 << DefArgRange;
2204 return false;
2205
2207 // C++0x [temp.param]p9:
2208 // A default template-argument shall not be specified in the
2209 // template-parameter-lists of the definition of a member of a
2210 // class template that appears outside of the member's class.
2211 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2212 << DefArgRange;
2213 return true;
2214
2217 // C++ [temp.param]p9:
2218 // A default template-argument shall not be specified in a
2219 // friend template declaration.
2220 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2221 << DefArgRange;
2222 return true;
2223
2224 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2225 // for friend function templates if there is only a single
2226 // declaration (and it is a definition). Strange!
2227 }
2228
2229 llvm_unreachable("Invalid TemplateParamListContext!");
2230}
2231
2232/// Check for unexpanded parameter packs within the template parameters
2233/// of a template template parameter, recursively.
2236 // A template template parameter which is a parameter pack is also a pack
2237 // expansion.
2238 if (TTP->isParameterPack())
2239 return false;
2240
2242 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2243 NamedDecl *P = Params->getParam(I);
2244 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2245 if (!TTP->isParameterPack())
2246 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2247 if (TC->hasExplicitTemplateArgs())
2248 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2251 return true;
2252 continue;
2253 }
2254
2255 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2256 if (!NTTP->isParameterPack() &&
2257 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2258 NTTP->getTypeSourceInfo(),
2260 return true;
2261
2262 continue;
2263 }
2264
2265 if (TemplateTemplateParmDecl *InnerTTP
2266 = dyn_cast<TemplateTemplateParmDecl>(P))
2267 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2268 return true;
2269 }
2270
2271 return false;
2272}
2273
2275 TemplateParameterList *OldParams,
2277 SkipBodyInfo *SkipBody) {
2278 bool Invalid = false;
2279
2280 // C++ [temp.param]p10:
2281 // The set of default template-arguments available for use with a
2282 // template declaration or definition is obtained by merging the
2283 // default arguments from the definition (if in scope) and all
2284 // declarations in scope in the same way default function
2285 // arguments are (8.3.6).
2286 bool SawDefaultArgument = false;
2287 SourceLocation PreviousDefaultArgLoc;
2288
2289 // Dummy initialization to avoid warnings.
2290 TemplateParameterList::iterator OldParam = NewParams->end();
2291 if (OldParams)
2292 OldParam = OldParams->begin();
2293
2294 bool RemoveDefaultArguments = false;
2295 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2296 NewParamEnd = NewParams->end();
2297 NewParam != NewParamEnd; ++NewParam) {
2298 // Whether we've seen a duplicate default argument in the same translation
2299 // unit.
2300 bool RedundantDefaultArg = false;
2301 // Whether we've found inconsis inconsitent default arguments in different
2302 // translation unit.
2303 bool InconsistentDefaultArg = false;
2304 // The name of the module which contains the inconsistent default argument.
2305 std::string PrevModuleName;
2306
2307 SourceLocation OldDefaultLoc;
2308 SourceLocation NewDefaultLoc;
2309
2310 // Variable used to diagnose missing default arguments
2311 bool MissingDefaultArg = false;
2312
2313 // Variable used to diagnose non-final parameter packs
2314 bool SawParameterPack = false;
2315
2316 if (TemplateTypeParmDecl *NewTypeParm
2317 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2318 // Check the presence of a default argument here.
2319 if (NewTypeParm->hasDefaultArgument() &&
2321 *this, TPC, NewTypeParm->getLocation(),
2322 NewTypeParm->getDefaultArgument().getSourceRange()))
2323 NewTypeParm->removeDefaultArgument();
2324
2325 // Merge default arguments for template type parameters.
2326 TemplateTypeParmDecl *OldTypeParm
2327 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2328 if (NewTypeParm->isParameterPack()) {
2329 assert(!NewTypeParm->hasDefaultArgument() &&
2330 "Parameter packs can't have a default argument!");
2331 SawParameterPack = true;
2332 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2333 NewTypeParm->hasDefaultArgument() &&
2334 (!SkipBody || !SkipBody->ShouldSkip)) {
2335 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2336 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2337 SawDefaultArgument = true;
2338
2339 if (!OldTypeParm->getOwningModule())
2340 RedundantDefaultArg = true;
2341 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2342 NewTypeParm)) {
2343 InconsistentDefaultArg = true;
2344 PrevModuleName =
2346 }
2347 PreviousDefaultArgLoc = NewDefaultLoc;
2348 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2349 // Merge the default argument from the old declaration to the
2350 // new declaration.
2351 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2352 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2353 } else if (NewTypeParm->hasDefaultArgument()) {
2354 SawDefaultArgument = true;
2355 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2356 } else if (SawDefaultArgument)
2357 MissingDefaultArg = true;
2358 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2359 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2360 // Check for unexpanded parameter packs.
2361 if (!NewNonTypeParm->isParameterPack() &&
2362 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2363 NewNonTypeParm->getTypeSourceInfo(),
2365 Invalid = true;
2366 continue;
2367 }
2368
2369 // Check the presence of a default argument here.
2370 if (NewNonTypeParm->hasDefaultArgument() &&
2372 *this, TPC, NewNonTypeParm->getLocation(),
2373 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2374 NewNonTypeParm->removeDefaultArgument();
2375 }
2376
2377 // Merge default arguments for non-type template parameters
2378 NonTypeTemplateParmDecl *OldNonTypeParm
2379 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2380 if (NewNonTypeParm->isParameterPack()) {
2381 assert(!NewNonTypeParm->hasDefaultArgument() &&
2382 "Parameter packs can't have a default argument!");
2383 if (!NewNonTypeParm->isPackExpansion())
2384 SawParameterPack = true;
2385 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2386 NewNonTypeParm->hasDefaultArgument() &&
2387 (!SkipBody || !SkipBody->ShouldSkip)) {
2388 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2389 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2390 SawDefaultArgument = true;
2391 if (!OldNonTypeParm->getOwningModule())
2392 RedundantDefaultArg = true;
2393 else if (!getASTContext().isSameDefaultTemplateArgument(
2394 OldNonTypeParm, NewNonTypeParm)) {
2395 InconsistentDefaultArg = true;
2396 PrevModuleName =
2397 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2398 }
2399 PreviousDefaultArgLoc = NewDefaultLoc;
2400 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2401 // Merge the default argument from the old declaration to the
2402 // new declaration.
2403 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2404 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405 } else if (NewNonTypeParm->hasDefaultArgument()) {
2406 SawDefaultArgument = true;
2407 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2408 } else if (SawDefaultArgument)
2409 MissingDefaultArg = true;
2410 } else {
2411 TemplateTemplateParmDecl *NewTemplateParm
2412 = cast<TemplateTemplateParmDecl>(*NewParam);
2413
2414 // Check for unexpanded parameter packs, recursively.
2415 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2416 Invalid = true;
2417 continue;
2418 }
2419
2420 // Check the presence of a default argument here.
2421 if (NewTemplateParm->hasDefaultArgument() &&
2423 NewTemplateParm->getLocation(),
2424 NewTemplateParm->getDefaultArgument().getSourceRange()))
2425 NewTemplateParm->removeDefaultArgument();
2426
2427 // Merge default arguments for template template parameters
2428 TemplateTemplateParmDecl *OldTemplateParm
2429 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2430 if (NewTemplateParm->isParameterPack()) {
2431 assert(!NewTemplateParm->hasDefaultArgument() &&
2432 "Parameter packs can't have a default argument!");
2433 if (!NewTemplateParm->isPackExpansion())
2434 SawParameterPack = true;
2435 } else if (OldTemplateParm &&
2436 hasVisibleDefaultArgument(OldTemplateParm) &&
2437 NewTemplateParm->hasDefaultArgument() &&
2438 (!SkipBody || !SkipBody->ShouldSkip)) {
2439 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2440 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2441 SawDefaultArgument = true;
2442 if (!OldTemplateParm->getOwningModule())
2443 RedundantDefaultArg = true;
2444 else if (!getASTContext().isSameDefaultTemplateArgument(
2445 OldTemplateParm, NewTemplateParm)) {
2446 InconsistentDefaultArg = true;
2447 PrevModuleName =
2448 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2449 }
2450 PreviousDefaultArgLoc = NewDefaultLoc;
2451 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2452 // Merge the default argument from the old declaration to the
2453 // new declaration.
2454 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2455 PreviousDefaultArgLoc
2456 = OldTemplateParm->getDefaultArgument().getLocation();
2457 } else if (NewTemplateParm->hasDefaultArgument()) {
2458 SawDefaultArgument = true;
2459 PreviousDefaultArgLoc
2460 = NewTemplateParm->getDefaultArgument().getLocation();
2461 } else if (SawDefaultArgument)
2462 MissingDefaultArg = true;
2463 }
2464
2465 // C++11 [temp.param]p11:
2466 // If a template parameter of a primary class template or alias template
2467 // is a template parameter pack, it shall be the last template parameter.
2468 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2469 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2470 TPC == TPC_TypeAliasTemplate)) {
2471 Diag((*NewParam)->getLocation(),
2472 diag::err_template_param_pack_must_be_last_template_parameter);
2473 Invalid = true;
2474 }
2475
2476 // [basic.def.odr]/13:
2477 // There can be more than one definition of a
2478 // ...
2479 // default template argument
2480 // ...
2481 // in a program provided that each definition appears in a different
2482 // translation unit and the definitions satisfy the [same-meaning
2483 // criteria of the ODR].
2484 //
2485 // Simply, the design of modules allows the definition of template default
2486 // argument to be repeated across translation unit. Note that the ODR is
2487 // checked elsewhere. But it is still not allowed to repeat template default
2488 // argument in the same translation unit.
2489 if (RedundantDefaultArg) {
2490 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2491 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2492 Invalid = true;
2493 } else if (InconsistentDefaultArg) {
2494 // We could only diagnose about the case that the OldParam is imported.
2495 // The case NewParam is imported should be handled in ASTReader.
2496 Diag(NewDefaultLoc,
2497 diag::err_template_param_default_arg_inconsistent_redefinition);
2498 Diag(OldDefaultLoc,
2499 diag::note_template_param_prev_default_arg_in_other_module)
2500 << PrevModuleName;
2501 Invalid = true;
2502 } else if (MissingDefaultArg &&
2503 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2504 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2505 // C++ 23[temp.param]p14:
2506 // If a template-parameter of a class template, variable template, or
2507 // alias template has a default template argument, each subsequent
2508 // template-parameter shall either have a default template argument
2509 // supplied or be a template parameter pack.
2510 Diag((*NewParam)->getLocation(),
2511 diag::err_template_param_default_arg_missing);
2512 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2513 Invalid = true;
2514 RemoveDefaultArguments = true;
2515 }
2516
2517 // If we have an old template parameter list that we're merging
2518 // in, move on to the next parameter.
2519 if (OldParams)
2520 ++OldParam;
2521 }
2522
2523 // We were missing some default arguments at the end of the list, so remove
2524 // all of the default arguments.
2525 if (RemoveDefaultArguments) {
2526 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2527 NewParamEnd = NewParams->end();
2528 NewParam != NewParamEnd; ++NewParam) {
2529 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2530 TTP->removeDefaultArgument();
2531 else if (NonTypeTemplateParmDecl *NTTP
2532 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2533 NTTP->removeDefaultArgument();
2534 else
2535 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2536 }
2537 }
2538
2539 return Invalid;
2540}
2541
2542namespace {
2543
2544/// A class which looks for a use of a certain level of template
2545/// parameter.
2546struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2548
2549 unsigned Depth;
2550
2551 // Whether we're looking for a use of a template parameter that makes the
2552 // overall construct type-dependent / a dependent type. This is strictly
2553 // best-effort for now; we may fail to match at all for a dependent type
2554 // in some cases if this is set.
2555 bool IgnoreNonTypeDependent;
2556
2557 bool Match;
2558 SourceLocation MatchLoc;
2559
2560 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2561 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2562 Match(false) {}
2563
2564 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2565 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2566 NamedDecl *ND = Params->getParam(0);
2567 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2568 Depth = PD->getDepth();
2569 } else if (NonTypeTemplateParmDecl *PD =
2570 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2571 Depth = PD->getDepth();
2572 } else {
2573 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2574 }
2575 }
2576
2577 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2578 if (ParmDepth >= Depth) {
2579 Match = true;
2580 MatchLoc = Loc;
2581 return true;
2582 }
2583 return false;
2584 }
2585
2586 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2587 // Prune out non-type-dependent expressions if requested. This can
2588 // sometimes result in us failing to find a template parameter reference
2589 // (if a value-dependent expression creates a dependent type), but this
2590 // mode is best-effort only.
2591 if (auto *E = dyn_cast_or_null<Expr>(S))
2592 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2593 return true;
2594 return super::TraverseStmt(S, Q);
2595 }
2596
2597 bool TraverseTypeLoc(TypeLoc TL) {
2598 if (IgnoreNonTypeDependent && !TL.isNull() &&
2599 !TL.getType()->isDependentType())
2600 return true;
2601 return super::TraverseTypeLoc(TL);
2602 }
2603
2604 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2605 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2606 }
2607
2608 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2609 // For a best-effort search, keep looking until we find a location.
2610 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2611 }
2612
2613 bool TraverseTemplateName(TemplateName N) {
2614 if (TemplateTemplateParmDecl *PD =
2615 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2616 if (Matches(PD->getDepth()))
2617 return false;
2618 return super::TraverseTemplateName(N);
2619 }
2620
2621 bool VisitDeclRefExpr(DeclRefExpr *E) {
2622 if (NonTypeTemplateParmDecl *PD =
2623 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2624 if (Matches(PD->getDepth(), E->getExprLoc()))
2625 return false;
2626 return super::VisitDeclRefExpr(E);
2627 }
2628
2629 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2630 return TraverseType(T->getReplacementType());
2631 }
2632
2633 bool
2634 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2635 return TraverseTemplateArgument(T->getArgumentPack());
2636 }
2637
2638 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2639 return TraverseType(T->getInjectedSpecializationType());
2640 }
2641};
2642} // end anonymous namespace
2643
2644/// Determines whether a given type depends on the given parameter
2645/// list.
2646static bool
2648 if (!Params->size())
2649 return false;
2650
2651 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2652 Checker.TraverseType(T);
2653 return Checker.Match;
2654}
2655
2656// Find the source range corresponding to the named type in the given
2657// nested-name-specifier, if any.
2659 QualType T,
2660 const CXXScopeSpec &SS) {
2662 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2663 if (const Type *CurType = NNS->getAsType()) {
2664 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2665 return NNSLoc.getTypeLoc().getSourceRange();
2666 } else
2667 break;
2668
2669 NNSLoc = NNSLoc.getPrefix();
2670 }
2671
2672 return SourceRange();
2673}
2674
2676 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2677 TemplateIdAnnotation *TemplateId,
2678 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2679 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2680 IsMemberSpecialization = false;
2681 Invalid = false;
2682
2683 // The sequence of nested types to which we will match up the template
2684 // parameter lists. We first build this list by starting with the type named
2685 // by the nested-name-specifier and walking out until we run out of types.
2686 SmallVector<QualType, 4> NestedTypes;
2687 QualType T;
2688 if (SS.getScopeRep()) {
2690 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2692 else
2693 T = QualType(SS.getScopeRep()->getAsType(), 0);
2694 }
2695
2696 // If we found an explicit specialization that prevents us from needing
2697 // 'template<>' headers, this will be set to the location of that
2698 // explicit specialization.
2699 SourceLocation ExplicitSpecLoc;
2700
2701 while (!T.isNull()) {
2702 NestedTypes.push_back(T);
2703
2704 // Retrieve the parent of a record type.
2706 // If this type is an explicit specialization, we're done.
2708 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2709 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2710 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2711 ExplicitSpecLoc = Spec->getLocation();
2712 break;
2713 }
2714 } else if (Record->getTemplateSpecializationKind()
2716 ExplicitSpecLoc = Record->getLocation();
2717 break;
2718 }
2719
2720 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2722 else
2723 T = QualType();
2724 continue;
2725 }
2726
2727 if (const TemplateSpecializationType *TST
2729 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2730 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2732 else
2733 T = QualType();
2734 continue;
2735 }
2736 }
2737
2738 // Look one step prior in a dependent template specialization type.
2739 if (const DependentTemplateSpecializationType *DependentTST
2741 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2742 T = QualType(NNS->getAsType(), 0);
2743 else
2744 T = QualType();
2745 continue;
2746 }
2747
2748 // Look one step prior in a dependent name type.
2749 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2750 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2751 T = QualType(NNS->getAsType(), 0);
2752 else
2753 T = QualType();
2754 continue;
2755 }
2756
2757 // Retrieve the parent of an enumeration type.
2758 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2759 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2760 // check here.
2761 EnumDecl *Enum = EnumT->getDecl();
2762
2763 // Get to the parent type.
2764 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2766 else
2767 T = QualType();
2768 continue;
2769 }
2770
2771 T = QualType();
2772 }
2773 // Reverse the nested types list, since we want to traverse from the outermost
2774 // to the innermost while checking template-parameter-lists.
2775 std::reverse(NestedTypes.begin(), NestedTypes.end());
2776
2777 // C++0x [temp.expl.spec]p17:
2778 // A member or a member template may be nested within many
2779 // enclosing class templates. In an explicit specialization for
2780 // such a member, the member declaration shall be preceded by a
2781 // template<> for each enclosing class template that is
2782 // explicitly specialized.
2783 bool SawNonEmptyTemplateParameterList = false;
2784
2785 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2786 if (SawNonEmptyTemplateParameterList) {
2787 if (!SuppressDiagnostic)
2788 Diag(DeclLoc, diag::err_specialize_member_of_template)
2789 << !Recovery << Range;
2790 Invalid = true;
2791 IsMemberSpecialization = false;
2792 return true;
2793 }
2794
2795 return false;
2796 };
2797
2798 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2799 // Check that we can have an explicit specialization here.
2800 if (CheckExplicitSpecialization(Range, true))
2801 return true;
2802
2803 // We don't have a template header, but we should.
2804 SourceLocation ExpectedTemplateLoc;
2805 if (!ParamLists.empty())
2806 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2807 else
2808 ExpectedTemplateLoc = DeclStartLoc;
2809
2810 if (!SuppressDiagnostic)
2811 Diag(DeclLoc, diag::err_template_spec_needs_header)
2812 << Range
2813 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2814 return false;
2815 };
2816
2817 unsigned ParamIdx = 0;
2818 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2819 ++TypeIdx) {
2820 T = NestedTypes[TypeIdx];
2821
2822 // Whether we expect a 'template<>' header.
2823 bool NeedEmptyTemplateHeader = false;
2824
2825 // Whether we expect a template header with parameters.
2826 bool NeedNonemptyTemplateHeader = false;
2827
2828 // For a dependent type, the set of template parameters that we
2829 // expect to see.
2830 TemplateParameterList *ExpectedTemplateParams = nullptr;
2831
2832 // C++0x [temp.expl.spec]p15:
2833 // A member or a member template may be nested within many enclosing
2834 // class templates. In an explicit specialization for such a member, the
2835 // member declaration shall be preceded by a template<> for each
2836 // enclosing class template that is explicitly specialized.
2839 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2840 ExpectedTemplateParams = Partial->getTemplateParameters();
2841 NeedNonemptyTemplateHeader = true;
2842 } else if (Record->isDependentType()) {
2843 if (Record->getDescribedClassTemplate()) {
2844 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2845 ->getTemplateParameters();
2846 NeedNonemptyTemplateHeader = true;
2847 }
2848 } else if (ClassTemplateSpecializationDecl *Spec
2849 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2850 // C++0x [temp.expl.spec]p4:
2851 // Members of an explicitly specialized class template are defined
2852 // in the same manner as members of normal classes, and not using
2853 // the template<> syntax.
2854 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2855 NeedEmptyTemplateHeader = true;
2856 else
2857 continue;
2858 } else if (Record->getTemplateSpecializationKind()) {
2859 if (Record->getTemplateSpecializationKind()
2861 TypeIdx == NumTypes - 1)
2862 IsMemberSpecialization = true;
2863
2864 continue;
2865 }
2866 } else if (const TemplateSpecializationType *TST
2868 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2869 ExpectedTemplateParams = Template->getTemplateParameters();
2870 NeedNonemptyTemplateHeader = true;
2871 }
2873 // FIXME: We actually could/should check the template arguments here
2874 // against the corresponding template parameter list.
2875 NeedNonemptyTemplateHeader = false;
2876 }
2877
2878 // C++ [temp.expl.spec]p16:
2879 // In an explicit specialization declaration for a member of a class
2880 // template or a member template that appears in namespace scope, the
2881 // member template and some of its enclosing class templates may remain
2882 // unspecialized, except that the declaration shall not explicitly
2883 // specialize a class member template if its enclosing class templates
2884 // are not explicitly specialized as well.
2885 if (ParamIdx < ParamLists.size()) {
2886 if (ParamLists[ParamIdx]->size() == 0) {
2887 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2888 false))
2889 return nullptr;
2890 } else
2891 SawNonEmptyTemplateParameterList = true;
2892 }
2893
2894 if (NeedEmptyTemplateHeader) {
2895 // If we're on the last of the types, and we need a 'template<>' header
2896 // here, then it's a member specialization.
2897 if (TypeIdx == NumTypes - 1)
2898 IsMemberSpecialization = true;
2899
2900 if (ParamIdx < ParamLists.size()) {
2901 if (ParamLists[ParamIdx]->size() > 0) {
2902 // The header has template parameters when it shouldn't. Complain.
2903 if (!SuppressDiagnostic)
2904 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2905 diag::err_template_param_list_matches_nontemplate)
2906 << T
2907 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2908 ParamLists[ParamIdx]->getRAngleLoc())
2910 Invalid = true;
2911 return nullptr;
2912 }
2913
2914 // Consume this template header.
2915 ++ParamIdx;
2916 continue;
2917 }
2918
2919 if (!IsFriend)
2920 if (DiagnoseMissingExplicitSpecialization(
2922 return nullptr;
2923
2924 continue;
2925 }
2926
2927 if (NeedNonemptyTemplateHeader) {
2928 // In friend declarations we can have template-ids which don't
2929 // depend on the corresponding template parameter lists. But
2930 // assume that empty parameter lists are supposed to match this
2931 // template-id.
2932 if (IsFriend && T->isDependentType()) {
2933 if (ParamIdx < ParamLists.size() &&
2935 ExpectedTemplateParams = nullptr;
2936 else
2937 continue;
2938 }
2939
2940 if (ParamIdx < ParamLists.size()) {
2941 // Check the template parameter list, if we can.
2942 if (ExpectedTemplateParams &&
2944 ExpectedTemplateParams,
2945 !SuppressDiagnostic, TPL_TemplateMatch))
2946 Invalid = true;
2947
2948 if (!Invalid &&
2949 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2951 Invalid = true;
2952
2953 ++ParamIdx;
2954 continue;
2955 }
2956
2957 if (!SuppressDiagnostic)
2958 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2959 << T
2961 Invalid = true;
2962 continue;
2963 }
2964 }
2965
2966 // If there were at least as many template-ids as there were template
2967 // parameter lists, then there are no template parameter lists remaining for
2968 // the declaration itself.
2969 if (ParamIdx >= ParamLists.size()) {
2970 if (TemplateId && !IsFriend) {
2971 // We don't have a template header for the declaration itself, but we
2972 // should.
2973 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2974 TemplateId->RAngleLoc));
2975
2976 // Fabricate an empty template parameter list for the invented header.
2978 SourceLocation(), std::nullopt,
2979 SourceLocation(), nullptr);
2980 }
2981
2982 return nullptr;
2983 }
2984
2985 // If there were too many template parameter lists, complain about that now.
2986 if (ParamIdx < ParamLists.size() - 1) {
2987 bool HasAnyExplicitSpecHeader = false;
2988 bool AllExplicitSpecHeaders = true;
2989 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2990 if (ParamLists[I]->size() == 0)
2991 HasAnyExplicitSpecHeader = true;
2992 else
2993 AllExplicitSpecHeaders = false;
2994 }
2995
2996 if (!SuppressDiagnostic)
2997 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2998 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
2999 : diag::err_template_spec_extra_headers)
3000 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3001 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3002
3003 // If there was a specialization somewhere, such that 'template<>' is
3004 // not required, and there were any 'template<>' headers, note where the
3005 // specialization occurred.
3006 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3007 !SuppressDiagnostic)
3008 Diag(ExplicitSpecLoc,
3009 diag::note_explicit_template_spec_does_not_need_header)
3010 << NestedTypes.back();
3011
3012 // We have a template parameter list with no corresponding scope, which
3013 // means that the resulting template declaration can't be instantiated
3014 // properly (we'll end up with dependent nodes when we shouldn't).
3015 if (!AllExplicitSpecHeaders)
3016 Invalid = true;
3017 }
3018
3019 // C++ [temp.expl.spec]p16:
3020 // In an explicit specialization declaration for a member of a class
3021 // template or a member template that ap- pears in namespace scope, the
3022 // member template and some of its enclosing class templates may remain
3023 // unspecialized, except that the declaration shall not explicitly
3024 // specialize a class member template if its en- closing class templates
3025 // are not explicitly specialized as well.
3026 if (ParamLists.back()->size() == 0 &&
3027 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3028 false))
3029 return nullptr;
3030
3031 // Return the last template parameter list, which corresponds to the
3032 // entity being declared.
3033 return ParamLists.back();
3034}
3035
3037 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3038 Diag(Template->getLocation(), diag::note_template_declared_here)
3039 << (isa<FunctionTemplateDecl>(Template)
3040 ? 0
3041 : isa<ClassTemplateDecl>(Template)
3042 ? 1
3043 : isa<VarTemplateDecl>(Template)
3044 ? 2
3045 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3046 << Template->getDeclName();
3047 return;
3048 }
3049
3050 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3051 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3052 IEnd = OST->end();
3053 I != IEnd; ++I)
3054 Diag((*I)->getLocation(), diag::note_template_declared_here)
3055 << 0 << (*I)->getDeclName();
3056
3057 return;
3058 }
3059}
3060
3061static QualType
3064 SourceLocation TemplateLoc,
3065 TemplateArgumentListInfo &TemplateArgs) {
3066 ASTContext &Context = SemaRef.getASTContext();
3067
3068 switch (BTD->getBuiltinTemplateKind()) {
3069 case BTK__make_integer_seq: {
3070 // Specializations of __make_integer_seq<S, T, N> are treated like
3071 // S<T, 0, ..., N-1>.
3072
3073 QualType OrigType = Converted[1].getAsType();
3074 // C++14 [inteseq.intseq]p1:
3075 // T shall be an integer type.
3076 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3077 SemaRef.Diag(TemplateArgs[1].getLocation(),
3078 diag::err_integer_sequence_integral_element_type);
3079 return QualType();
3080 }
3081
3082 TemplateArgument NumArgsArg = Converted[2];
3083 if (NumArgsArg.isDependent())
3085 Converted);
3086
3087 TemplateArgumentListInfo SyntheticTemplateArgs;
3088 // The type argument, wrapped in substitution sugar, gets reused as the
3089 // first template argument in the synthetic template argument list.
3090 SyntheticTemplateArgs.addArgument(
3093 OrigType, TemplateArgs[1].getLocation())));
3094
3095 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3096 // Expand N into 0 ... N-1.
3097 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3098 I < NumArgs; ++I) {
3099 TemplateArgument TA(Context, I, OrigType);
3100 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3101 TA, OrigType, TemplateArgs[2].getLocation()));
3102 }
3103 } else {
3104 // C++14 [inteseq.make]p1:
3105 // If N is negative the program is ill-formed.
3106 SemaRef.Diag(TemplateArgs[2].getLocation(),
3107 diag::err_integer_sequence_negative_length);
3108 return QualType();
3109 }
3110
3111 // The first template argument will be reused as the template decl that
3112 // our synthetic template arguments will be applied to.
3113 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3114 TemplateLoc, SyntheticTemplateArgs);
3115 }
3116
3118 // Specializations of
3119 // __type_pack_element<Index, T_1, ..., T_N>
3120 // are treated like T_Index.
3121 assert(Converted.size() == 2 &&
3122 "__type_pack_element should be given an index and a parameter pack");
3123
3124 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3125 if (IndexArg.isDependent() || Ts.isDependent())
3127 Converted);
3128
3129 llvm::APSInt Index = IndexArg.getAsIntegral();
3130 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3131 "type std::size_t, and hence be non-negative");
3132 // If the Index is out of bounds, the program is ill-formed.
3133 if (Index >= Ts.pack_size()) {
3134 SemaRef.Diag(TemplateArgs[0].getLocation(),
3135 diag::err_type_pack_element_out_of_bounds);
3136 return QualType();
3137 }
3138
3139 // We simply return the type at index `Index`.
3140 int64_t N = Index.getExtValue();
3141 return Ts.getPackAsArray()[N].getAsType();
3142 }
3143 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3144}
3145
3146/// Determine whether this alias template is "enable_if_t".
3147/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3149 return AliasTemplate->getName() == "enable_if_t" ||
3150 AliasTemplate->getName() == "__enable_if_t";
3151}
3152
3153/// Collect all of the separable terms in the given condition, which
3154/// might be a conjunction.
3155///
3156/// FIXME: The right answer is to convert the logical expression into
3157/// disjunctive normal form, so we can find the first failed term
3158/// within each possible clause.
3159static void collectConjunctionTerms(Expr *Clause,
3160 SmallVectorImpl<Expr *> &Terms) {
3161 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3162 if (BinOp->getOpcode() == BO_LAnd) {
3163 collectConjunctionTerms(BinOp->getLHS(), Terms);
3164 collectConjunctionTerms(BinOp->getRHS(), Terms);
3165 return;
3166 }
3167 }
3168
3169 Terms.push_back(Clause);
3170}
3171
3172// The ranges-v3 library uses an odd pattern of a top-level "||" with
3173// a left-hand side that is value-dependent but never true. Identify
3174// the idiom and ignore that term.
3176 // Top-level '||'.
3177 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3178 if (!BinOp) return Cond;
3179
3180 if (BinOp->getOpcode() != BO_LOr) return Cond;
3181
3182 // With an inner '==' that has a literal on the right-hand side.
3183 Expr *LHS = BinOp->getLHS();
3184 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3185 if (!InnerBinOp) return Cond;
3186
3187 if (InnerBinOp->getOpcode() != BO_EQ ||
3188 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3189 return Cond;
3190
3191 // If the inner binary operation came from a macro expansion named
3192 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3193 // of the '||', which is the real, user-provided condition.
3194 SourceLocation Loc = InnerBinOp->getExprLoc();
3195 if (!Loc.isMacroID()) return Cond;
3196
3197 StringRef MacroName = PP.getImmediateMacroName(Loc);
3198 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3199 return BinOp->getRHS();
3200
3201 return Cond;
3202}
3203
3204namespace {
3205
3206// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3207// within failing boolean expression, such as substituting template parameters
3208// for actual types.
3209class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3210public:
3211 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3212 : Policy(P) {}
3213
3214 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3215 const auto *DR = dyn_cast<DeclRefExpr>(E);
3216 if (DR && DR->getQualifier()) {
3217 // If this is a qualified name, expand the template arguments in nested
3218 // qualifiers.
3219 DR->getQualifier()->print(OS, Policy, true);
3220 // Then print the decl itself.
3221 const ValueDecl *VD = DR->getDecl();
3222 OS << VD->getName();
3223 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3224 // This is a template variable, print the expanded template arguments.
3226 OS, IV->getTemplateArgs().asArray(), Policy,
3227 IV->getSpecializedTemplate()->getTemplateParameters());
3228 }
3229 return true;
3230 }
3231 return false;
3232 }
3233
3234private:
3235 const PrintingPolicy Policy;
3236};
3237
3238} // end anonymous namespace
3239
3240std::pair<Expr *, std::string>
3242 Cond = lookThroughRangesV3Condition(PP, Cond);
3243
3244 // Separate out all of the terms in a conjunction.
3246 collectConjunctionTerms(Cond, Terms);
3247
3248 // Determine which term failed.
3249 Expr *FailedCond = nullptr;
3250 for (Expr *Term : Terms) {
3251 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3252
3253 // Literals are uninteresting.
3254 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3255 isa<IntegerLiteral>(TermAsWritten))
3256 continue;
3257
3258 // The initialization of the parameter from the argument is
3259 // a constant-evaluated context.
3262
3263 bool Succeeded;
3264 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3265 !Succeeded) {
3266 FailedCond = TermAsWritten;
3267 break;
3268 }
3269 }
3270 if (!FailedCond)
3271 FailedCond = Cond->IgnoreParenImpCasts();
3272
3273 std::string Description;
3274 {
3275 llvm::raw_string_ostream Out(Description);
3277 Policy.PrintCanonicalTypes = true;
3278 FailedBooleanConditionPrinterHelper Helper(Policy);
3279 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3280 }
3281 return { FailedCond, Description };
3282}
3283
3285 SourceLocation TemplateLoc,
3286 TemplateArgumentListInfo &TemplateArgs) {
3288 = Name.getUnderlying().getAsDependentTemplateName();
3289 if (DTN && DTN->isIdentifier())
3290 // When building a template-id where the template-name is dependent,
3291 // assume the template is a type template. Either our assumption is
3292 // correct, or the code is ill-formed and will be diagnosed when the
3293 // dependent name is substituted.
3296 TemplateArgs.arguments());
3297
3298 if (Name.getAsAssumedTemplateName() &&
3299 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3300 return QualType();
3301
3302 TemplateDecl *Template = Name.getAsTemplateDecl();
3303 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3304 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3305 // We might have a substituted template template parameter pack. If so,
3306 // build a template specialization type for it.
3307 if (Name.getAsSubstTemplateTemplateParmPack())
3309 TemplateArgs.arguments());
3310
3311 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3312 << Name;
3314 return QualType();
3315 }
3316
3317 // Check that the template argument list is well-formed for this
3318 // template.
3319 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3320 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3321 SugaredConverted, CanonicalConverted,
3322 /*UpdateArgsWithConversions=*/true))
3323 return QualType();
3324
3325 QualType CanonType;
3326
3328 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3329
3330 // Find the canonical type for this type alias template specialization.
3331 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3332 if (Pattern->isInvalidDecl())
3333 return QualType();
3334
3335 // Only substitute for the innermost template argument list.
3336 MultiLevelTemplateArgumentList TemplateArgLists;
3337 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3338 /*Final=*/false);
3339 TemplateArgLists.addOuterRetainedLevels(
3340 AliasTemplate->getTemplateParameters()->getDepth());
3341
3344 *this, /*PointOfInstantiation=*/TemplateLoc,
3345 /*Entity=*/AliasTemplate,
3346 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3347
3348 // Diagnose uses of this alias.
3349 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3350
3351 if (Inst.isInvalid())
3352 return QualType();
3353
3354 std::optional<ContextRAII> SavedContext;
3355 if (!AliasTemplate->getDeclContext()->isFileContext())
3356 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3357
3358 CanonType =
3359 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3360 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3361 if (CanonType.isNull()) {
3362 // If this was enable_if and we failed to find the nested type
3363 // within enable_if in a SFINAE context, dig out the specific
3364 // enable_if condition that failed and present that instead.
3366 if (auto DeductionInfo = isSFINAEContext()) {
3367 if (*DeductionInfo &&
3368 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3369 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3370 diag::err_typename_nested_not_found_enable_if &&
3371 TemplateArgs[0].getArgument().getKind()
3373 Expr *FailedCond;
3374 std::string FailedDescription;
3375 std::tie(FailedCond, FailedDescription) =
3376 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3377
3378 // Remove the old SFINAE diagnostic.
3379 PartialDiagnosticAt OldDiag =
3381 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3382
3383 // Add a new SFINAE diagnostic specifying which condition
3384 // failed.
3385 (*DeductionInfo)->addSFINAEDiagnostic(
3386 OldDiag.first,
3387 PDiag(diag::err_typename_nested_not_found_requirement)
3388 << FailedDescription
3389 << FailedCond->getSourceRange());
3390 }
3391 }
3392 }
3393
3394 return QualType();
3395 }
3396 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3397 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3398 TemplateLoc, TemplateArgs);
3399 } else if (Name.isDependent() ||
3401 TemplateArgs, CanonicalConverted)) {
3402 // This class template specialization is a dependent
3403 // type. Therefore, its canonical type is another class template
3404 // specialization type that contains all of the converted
3405 // arguments in canonical form. This ensures that, e.g., A<T> and
3406 // A<T, T> have identical types when A is declared as:
3407 //
3408 // template<typename T, typename U = T> struct A;
3410 Name, CanonicalConverted);
3411
3412 // This might work out to be a current instantiation, in which
3413 // case the canonical type needs to be the InjectedClassNameType.
3414 //
3415 // TODO: in theory this could be a simple hashtable lookup; most
3416 // changes to CurContext don't change the set of current
3417 // instantiations.
3418 if (isa<ClassTemplateDecl>(Template)) {
3419 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3420 // If we get out to a namespace, we're done.
3421 if (Ctx->isFileContext()) break;
3422
3423 // If this isn't a record, keep looking.
3424 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3425 if (!Record) continue;
3426
3427 // Look for one of the two cases with InjectedClassNameTypes
3428 // and check whether it's the same template.
3429 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3430 !Record->getDescribedClassTemplate())
3431 continue;
3432
3433 // Fetch the injected class name type and check whether its
3434 // injected type is equal to the type we just built.
3436 QualType Injected = cast<InjectedClassNameType>(ICNT)
3437 ->getInjectedSpecializationType();
3438
3439 if (CanonType != Injected->getCanonicalTypeInternal())
3440 continue;
3441
3442 // If so, the canonical type of this TST is the injected
3443 // class name type of the record we just found.
3444 assert(ICNT.isCanonical());
3445 CanonType = ICNT;
3446 break;
3447 }
3448 }
3449 } else if (ClassTemplateDecl *ClassTemplate =
3450 dyn_cast<ClassTemplateDecl>(Template)) {
3451 // Find the class template specialization declaration that
3452 // corresponds to these arguments.
3453 void *InsertPos = nullptr;
3455 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3456 if (!Decl) {
3457 // This is the first time we have referenced this class template
3458 // specialization. Create the canonical declaration and add it to
3459 // the set of specializations.
3461 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3462 ClassTemplate->getDeclContext(),
3463 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3464 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3465 nullptr);
3466 ClassTemplate->AddSpecialization(Decl, InsertPos);
3467 if (ClassTemplate->isOutOfLine())
3468 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3469 }
3470
3471 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3472 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3473 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3474 if (!Inst.isInvalid()) {
3475 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3476 CanonicalConverted,
3477 /*Final=*/false);
3478 InstantiateAttrsForDecl(TemplateArgLists,
3479 ClassTemplate->getTemplatedDecl(), Decl);
3480 }
3481 }
3482
3483 // Diagnose uses of this specialization.
3484 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3485
3486 CanonType = Context.getTypeDeclType(Decl);
3487 assert(isa<RecordType>(CanonType) &&
3488 "type of non-dependent specialization is not a RecordType");
3489 } else {
3490 llvm_unreachable("Unhandled template kind");
3491 }
3492
3493 // Build the fully-sugared type for this class template
3494 // specialization, which refers back to the class template
3495 // specialization we created or found.
3496 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3497 CanonType);
3498}
3499
3501 TemplateNameKind &TNK,
3502 SourceLocation NameLoc,
3503 IdentifierInfo *&II) {
3504 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3505
3506 TemplateName Name = ParsedName.get();
3507 auto *ATN = Name.getAsAssumedTemplateName();
3508 assert(ATN && "not an assumed template name");
3509 II = ATN->getDeclName().getAsIdentifierInfo();
3510
3511 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3512 // Resolved to a type template name.
3513 ParsedName = TemplateTy::make(Name);
3514 TNK = TNK_Type_template;
3515 }
3516}
3517
3519 SourceLocation NameLoc,
3520 bool Diagnose) {
3521 // We assumed this undeclared identifier to be an (ADL-only) function
3522 // template name, but it was used in a context where a type was required.
3523 // Try to typo-correct it now.
3524 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3525 assert(ATN && "not an assumed template name");
3526
3527 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3528 struct CandidateCallback : CorrectionCandidateCallback {
3529 bool ValidateCandidate(const TypoCorrection &TC) override {
3530 return TC.getCorrectionDecl() &&
3532 }
3533 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3534 return std::make_unique<CandidateCallback>(*this);
3535 }
3536 } FilterCCC;
3537
3538 TypoCorrection Corrected =
3539 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3540 FilterCCC, CTK_ErrorRecovery);
3541 if (Corrected && Corrected.getFoundDecl()) {
3542 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3543 << ATN->getDeclName());
3544 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3545 return false;
3546 }
3547
3548 if (Diagnose)
3549 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3550 return true;
3551}
3552
3554 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3555 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3556 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3557 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3558 bool IsCtorOrDtorName, bool IsClassName,
3559 ImplicitTypenameContext AllowImplicitTypename) {
3560 if (SS.isInvalid())
3561 return true;
3562
3563 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3564 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3565
3566 // C++ [temp.res]p3:
3567 // A qualified-id that refers to a type and in which the
3568 // nested-name-specifier depends on a template-parameter (14.6.2)
3569 // shall be prefixed by the keyword typename to indicate that the
3570 // qualified-id denotes a type, forming an
3571 // elaborated-type-specifier (7.1.5.3).
3572 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3573 // C++2a relaxes some of those restrictions in [temp.res]p5.
3574 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3576 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3577 else
3578 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3579 << SS.getScopeRep() << TemplateII->getName()
3580 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3581 } else
3582 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3583 << SS.getScopeRep() << TemplateII->getName();
3584
3585 // FIXME: This is not quite correct recovery as we don't transform SS
3586 // into the corresponding dependent form (and we don't diagnose missing
3587 // 'template' keywords within SS as a result).
3588 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3589 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3590 TemplateArgsIn, RAngleLoc);
3591 }
3592
3593 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3594 // it's not actually allowed to be used as a type in most cases. Because
3595 // we annotate it before we know whether it's valid, we have to check for
3596 // this case here.
3597 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3598 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3599 Diag(TemplateIILoc,
3600 TemplateKWLoc.isInvalid()
3601 ? diag::err_out_of_line_qualified_id_type_names_constructor
3602 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3603 << TemplateII << 0 /*injected-class-name used as template name*/
3604 << 1 /*if any keyword was present, it was 'template'*/;
3605 }
3606 }
3607
3608 TemplateName Template = TemplateD.get();
3609 if (Template.getAsAssumedTemplateName() &&
3610 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3611 return true;
3612
3613 // Translate the parser's template argument list in our AST format.
3614 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3615 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3616
3617 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3618 assert(SS.getScopeRep() == DTN->getQualifier());
3620 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3621 TemplateArgs.arguments());
3622 // Build type-source information.
3623 TypeLocBuilder TLB;
3628 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3629 SpecTL.setTemplateNameLoc(TemplateIILoc);
3630 SpecTL.setLAngleLoc(LAngleLoc);
3631 SpecTL.setRAngleLoc(RAngleLoc);
3632 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3633 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3635 }
3636
3637 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3638 if (SpecTy.isNull())
3639 return true;
3640
3641 // Build type-source information.
3642 TypeLocBuilder TLB;
3645 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3646 SpecTL.setTemplateNameLoc(TemplateIILoc);
3647 SpecTL.setLAngleLoc(LAngleLoc);
3648 SpecTL.setRAngleLoc(RAngleLoc);
3649 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3650 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3651
3652 // Create an elaborated-type-specifier containing the nested-name-specifier.
3653 QualType ElTy =
3655 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3656 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3658 if (!ElabTL.isEmpty())
3660 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3661}
3662
3664 TypeSpecifierType TagSpec,
3665 SourceLocation TagLoc,
3666 CXXScopeSpec &SS,
3667 SourceLocation TemplateKWLoc,
3668 TemplateTy TemplateD,
3669 SourceLocation TemplateLoc,
3670 SourceLocation LAngleLoc,
3671 ASTTemplateArgsPtr TemplateArgsIn,
3672 SourceLocation RAngleLoc) {
3673 if (SS.isInvalid())
3674 return TypeResult(true);
3675
3676 TemplateName Template = TemplateD.get();
3677
3678 // Translate the parser's template argument list in our AST format.
3679 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3680 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3681
3682 // Determine the tag kind
3684 ElaboratedTypeKeyword Keyword
3686
3687 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3688 assert(SS.getScopeRep() == DTN->getQualifier());
3690 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3691 TemplateArgs.arguments());
3692
3693 // Build type-source information.
3694 TypeLocBuilder TLB;
3697 SpecTL.setElaboratedKeywordLoc(TagLoc);
3699 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3700 SpecTL.setTemplateNameLoc(TemplateLoc);
3701 SpecTL.setLAngleLoc(LAngleLoc);
3702 SpecTL.setRAngleLoc(RAngleLoc);
3703 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3704 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3706 }
3707
3708 if (TypeAliasTemplateDecl *TAT =
3709 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3710 // C++0x [dcl.type.elab]p2:
3711 // If the identifier resolves to a typedef-name or the simple-template-id
3712 // resolves to an alias template specialization, the
3713 // elaborated-type-specifier is ill-formed.
3714 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3715 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3716 Diag(TAT->getLocation(), diag::note_declared_at);
3717 }
3718
3719 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3720 if (Result.isNull())
3721 return TypeResult(true);
3722
3723 // Check the tag kind
3724 if (const RecordType *RT = Result->getAs<RecordType>()) {
3725 RecordDecl *D = RT->getDecl();
3726
3727 IdentifierInfo *Id = D->getIdentifier();
3728 assert(Id && "templated class must have an identifier");
3729
3731 TagLoc, Id)) {
3732 Diag(TagLoc, diag::err_use_with_wrong_tag)
3733 << Result
3734 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3735 Diag(D->getLocation(), diag::note_previous_use);
3736 }
3737 }
3738
3739 // Provide source-location information for the template specialization.
3740 TypeLocBuilder TLB;
3743 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3744 SpecTL.setTemplateNameLoc(TemplateLoc);
3745 SpecTL.setLAngleLoc(LAngleLoc);
3746 SpecTL.setRAngleLoc(RAngleLoc);
3747 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3748 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3749
3750 // Construct an elaborated type containing the nested-name-specifier (if any)
3751 // and tag keyword.
3754 ElabTL.setElaboratedKeywordLoc(TagLoc);
3757}
3758
3759static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3760 NamedDecl *PrevDecl,
3763
3765
3767 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3768 switch (Arg.getKind()) {
3776 return false;
3777
3779 QualType Type = Arg.getAsType();
3780 const TemplateTypeParmType *TPT =
3782 return TPT && !Type.hasQualifiers() &&
3783 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3784 }
3785
3787 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3788 if (!DRE || !DRE->getDecl())
3789 return false;
3790 const NonTypeTemplateParmDecl *NTTP =
3791 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3792 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3793 }
3794
3796 const TemplateTemplateParmDecl *TTP =
3797 dyn_cast_or_null<TemplateTemplateParmDecl>(
3799 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3800 }
3801 llvm_unreachable("unexpected kind of template argument");
3802}
3803
3806 if (Params->size() != Args.size())
3807 return false;
3808
3809 unsigned Depth = Params->getDepth();
3810
3811 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3812 TemplateArgument Arg = Args[I];
3813
3814 // If the parameter is a pack expansion, the argument must be a pack
3815 // whose only element is a pack expansion.
3816 if (Params->getParam(I)->isParameterPack()) {
3817 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3818 !Arg.pack_begin()->isPackExpansion())
3819 return false;
3820 Arg = Arg.pack_begin()->getPackExpansionPattern();
3821 }
3822
3823 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3824 return false;
3825 }
3826
3827 return true;
3828}
3829
3830template<typename PartialSpecDecl>
3831static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3832 if (Partial->getDeclContext()->isDependentContext())
3833 return;
3834
3835 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3836 // for non-substitution-failure issues?
3837 TemplateDeductionInfo Info(Partial->getLocation());
3838 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3839 return;
3840
3841 auto *Template = Partial->getSpecializedTemplate();
3842 S.Diag(Partial->getLocation(),
3843 diag::ext_partial_spec_not_more_specialized_than_primary)
3844 << isa<VarTemplateDecl>(Template);
3845
3846 if (Info.hasSFINAEDiagnostic()) {
3850 SmallString<128> SFINAEArgString;
3851 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3852 S.Diag(Diag.first,
3853 diag::note_partial_spec_not_more_specialized_than_primary)
3854 << SFINAEArgString;
3855 }
3856
3857 S.NoteTemplateLocation(*Template);
3858 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3859 Template->getAssociatedConstraints(TemplateAC);
3860 Partial->getAssociatedConstraints(PartialAC);
3861 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3862 TemplateAC);
3863}
3864
3865static void
3867 const llvm::SmallBitVector &DeducibleParams) {
3868 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3869 if (!DeducibleParams[I]) {
3870 NamedDecl *Param = TemplateParams->getParam(I);
3871 if (Param->getDeclName())
3872 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3873 << Param->getDeclName();
3874 else
3875 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3876 << "(anonymous)";
3877 }
3878 }
3879}
3880
3881
3882template<typename PartialSpecDecl>
3884 PartialSpecDecl *Partial) {
3885 // C++1z [temp.class.spec]p8: (DR1495)
3886 // - The specialization shall be more specialized than the primary
3887 // template (14.5.5.2).
3889
3890 // C++ [temp.class.spec]p8: (DR1315)
3891 // - Each template-parameter shall appear at least once in the
3892 // template-id outside a non-deduced context.
3893 // C++1z [temp.class.spec.match]p3 (P0127R2)
3894 // If the template arguments of a partial specialization cannot be
3895 // deduced because of the structure of its template-parameter-list
3896 // and the template-id, the program is ill-formed.
3897 auto *TemplateParams = Partial->getTemplateParameters();
3898 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3899 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3900 TemplateParams->getDepth(), DeducibleParams);
3901
3902 if (!DeducibleParams.all()) {
3903 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3904 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3905 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3906 << (NumNonDeducible > 1)
3907 << SourceRange(Partial->getLocation(),
3908 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3909 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3910 }
3911}
3912
3915 checkTemplatePartialSpecialization(*this, Partial);
3916}
3917
3920 checkTemplatePartialSpecialization(*this, Partial);
3921}
3922
3924 // C++1z [temp.param]p11:
3925 // A template parameter of a deduction guide template that does not have a
3926 // default-argument shall be deducible from the parameter-type-list of the
3927 // deduction guide template.
3928 auto *TemplateParams = TD->getTemplateParameters();
3929 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3930 MarkDeducedTemplateParameters(TD, DeducibleParams);
3931 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3932 // A parameter pack is deducible (to an empty pack).
3933 auto *Param = TemplateParams->getParam(I);
3934 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3935 DeducibleParams[I] = true;
3936 }
3937
3938 if (!DeducibleParams.all()) {
3939 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3940 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3941 << (NumNonDeducible > 1);
3942 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3943 }
3944}
3945
3948 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
3950 // D must be variable template id.
3951 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3952 "Variable template specialization is declared with a template id.");
3953
3954 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3955 TemplateArgumentListInfo TemplateArgs =
3956 makeTemplateArgumentListInfo(*this, *TemplateId);
3957 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3958 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3959 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3960
3961 TemplateName Name = TemplateId->Template.get();
3962
3963 // The template-id must name a variable template.
3965 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3966 if (!VarTemplate) {
3967 NamedDecl *FnTemplate;
3968 if (auto *OTS = Name.getAsOverloadedTemplate())
3969 FnTemplate = *OTS->begin();
3970 else
3971 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3972 if (FnTemplate)
3973 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3974 << FnTemplate->getDeclName();
3975 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3977 }
3978
3979 // Check for unexpanded parameter packs in any of the template arguments.
3980 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3981 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3985 return true;
3986
3987 // Check that the template argument list is well-formed for this
3988 // template.
3989 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3990 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3991 false, SugaredConverted, CanonicalConverted,
3992 /*UpdateArgsWithConversions=*/true))
3993 return true;
3994
3995 // Find the variable template (partial) specialization declaration that
3996 // corresponds to these arguments.
3999 TemplateArgs.size(),
4000 CanonicalConverted))
4001 return true;
4002
4003 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4004 // also do them during instantiation.
4005 if (!Name.isDependent() &&
4007 TemplateArgs, CanonicalConverted)) {
4008 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4009 << VarTemplate->getDeclName();
4011 }
4012
4013 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4014 CanonicalConverted) &&
4015 (!Context.getLangOpts().CPlusPlus20 ||
4016 !TemplateParams->hasAssociatedConstraints())) {
4017 // C++ [temp.class.spec]p9b3:
4018 //
4019 // -- The argument list of the specialization shall not be identical
4020 // to the implicit argument list of the primary template.
4021 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4022 << /*variable template*/ 1
4023 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4024 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4025 // FIXME: Recover from this by treating the declaration as a redeclaration
4026 // of the primary template.
4027 return true;
4028 }
4029 }
4030
4031 void *InsertPos = nullptr;
4032 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4033
4035 PrevDecl = VarTemplate->findPartialSpecialization(
4036 CanonicalConverted, TemplateParams, InsertPos);
4037 else
4038 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4039
4041
4042 // Check whether we can declare a variable template specialization in
4043 // the current scope.
4044 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4045 TemplateNameLoc,
4047 return true;
4048
4049 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4050 // Since the only prior variable template specialization with these
4051 // arguments was referenced but not declared, reuse that
4052 // declaration node as our own, updating its source location and
4053 // the list of outer template parameters to reflect our new declaration.
4054 Specialization = PrevDecl;
4055 Specialization->setLocation(TemplateNameLoc);
4056 PrevDecl = nullptr;
4057 } else if (IsPartialSpecialization) {
4058 // Create a new class template partial specialization declaration node.
4060 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4063 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4064 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4065 CanonicalConverted);
4066 Partial->setTemplateArgsAsWritten(TemplateArgs);
4067
4068 if (!PrevPartial)
4069 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4070 Specialization = Partial;
4071
4072 // If we are providing an explicit specialization of a member variable
4073 // template specialization, make a note of that.
4074 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4075 PrevPartial->setMemberSpecialization();
4076
4078 } else {
4079 // Create a new class template specialization declaration node for
4080 // this explicit specialization or friend declaration.
4082 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4083 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4084 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4085
4086 if (!PrevDecl)
4087 VarTemplate->AddSpecialization(Specialization, InsertPos);
4088 }
4089
4090 // C++ [temp.expl.spec]p6:
4091 // If a template, a member template or the member of a class template is
4092 // explicitly specialized then that specialization shall be declared
4093 // before the first use of that specialization that would cause an implicit
4094 // instantiation to take place, in every translation unit in which such a
4095 // use occurs; no diagnostic is required.
4096 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4097 bool Okay = false;
4098 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4099 // Is there any previous explicit specialization declaration?
4101 Okay = true;
4102 break;
4103 }
4104 }
4105
4106 if (!Okay) {
4107 SourceRange Range(TemplateNameLoc, RAngleLoc);
4108 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4109 << Name << Range;
4110
4111 Diag(PrevDecl->getPointOfInstantiation(),
4112 diag::note_instantiation_required_here)
4113 << (PrevDecl->getTemplateSpecializationKind() !=
4115 return true;
4116 }
4117 }
4118
4119 Specialization->setLexicalDeclContext(CurContext);
4120
4121 // Add the specialization into its lexical context, so that it can
4122 // be seen when iterating through the list of declarations in that
4123 // context. However, specializations are not found by name lookup.
4125
4126 // Note that this is an explicit specialization.
4127 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4128
4129 Previous.clear();
4130 if (PrevDecl)
4131 Previous.addDecl(PrevDecl);
4132 else if (Specialization->isStaticDataMember() &&
4133 Specialization->isOutOfLine())
4134 Specialization->setAccess(VarTemplate->getAccess());
4135
4136 return Specialization;
4137}
4138
4139namespace {
4140/// A partial specialization whose template arguments have matched
4141/// a given template-id.
4142struct PartialSpecMatchResult {
4145};
4146} // end anonymous namespace
4147
4150 SourceLocation TemplateNameLoc,
4151 const TemplateArgumentListInfo &TemplateArgs) {
4152 assert(Template && "A variable template id without template?");
4153
4154 // Check that the template argument list is well-formed for this template.
4155 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4157 Template, TemplateNameLoc,
4158 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4159 SugaredConverted, CanonicalConverted,
4160 /*UpdateArgsWithConversions=*/true))
4161 return true;
4162
4163 // Produce a placeholder value if the specialization is dependent.
4164 if (Template->getDeclContext()->isDependentContext() ||
4166 TemplateArgs, CanonicalConverted))
4167 return DeclResult();
4168
4169 // Find the variable template specialization declaration that
4170 // corresponds to these arguments.
4171 void *InsertPos = nullptr;
4173 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4174 checkSpecializationReachability(TemplateNameLoc, Spec);
4175 // If we already have a variable template specialization, return it.
4176 return Spec;
4177 }
4178
4179 // This is the first time we have referenced this variable template
4180 // specialization. Create the canonical declaration and add it to
4181 // the set of specializations, based on the closest partial specialization
4182 // that it represents. That is,
4183 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4184 const TemplateArgumentList *PartialSpecArgs = nullptr;
4185 bool AmbiguousPartialSpec = false;
4186 typedef PartialSpecMatchResult MatchResult;
4188 SourceLocation PointOfInstantiation = TemplateNameLoc;
4189 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4190 /*ForTakingAddress=*/false);
4191
4192 // 1. Attempt to find the closest partial specialization that this
4193 // specializes, if any.
4194 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4195 // Perhaps better after unification of DeduceTemplateArguments() and
4196 // getMoreSpecializedPartialSpecialization().
4198 Template->getPartialSpecializations(PartialSpecs);
4199
4200 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4201 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4202 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4203
4205 DeduceTemplateArguments(Partial, CanonicalConverted, Info);
4207 // Store the failed-deduction information for use in diagnostics, later.
4208 // TODO: Actually use the failed-deduction info?
4209 FailedCandidates.addCandidate().set(
4210 DeclAccessPair::make(Template, AS_public), Partial,
4212 (void)Result;
4213 } else {
4214 Matched.push_back(PartialSpecMatchResult());
4215 Matched.back().Partial = Partial;
4216 Matched.back().Args = Info.takeCanonical();
4217 }
4218 }
4219
4220 if (Matched.size() >= 1) {
4221 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4222 if (Matched.size() == 1) {
4223 // -- If exactly one matching specialization is found, the
4224 // instantiation is generated from that specialization.
4225 // We don't need to do anything for this.
4226 } else {
4227 // -- If more than one matching specialization is found, the
4228 // partial order rules (14.5.4.2) are used to determine
4229 // whether one of the specializations is more specialized
4230 // than the others. If none of the specializations is more
4231 // specialized than all of the other matching
4232 // specializations, then the use of the variable template is
4233 // ambiguous and the program is ill-formed.
4235 PEnd = Matched.end();
4236 P != PEnd; ++P) {
4237 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4238 PointOfInstantiation) ==
4239 P->Partial)
4240 Best = P;
4241 }
4242
4243 // Determine if the best partial specialization is more specialized than
4244 // the others.
4245 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4246 PEnd = Matched.end();
4247 P != PEnd; ++P) {
4249 P->Partial, Best->Partial,
4250 PointOfInstantiation) != Best->Partial) {
4251 AmbiguousPartialSpec = true;
4252 break;
4253 }
4254 }
4255 }
4256
4257 // Instantiate using the best variable template partial specialization.
4258 InstantiationPattern = Best->Partial;
4259 PartialSpecArgs = Best->Args;
4260 } else {
4261 // -- If no match is found, the instantiation is generated
4262 // from the primary template.
4263 // InstantiationPattern = Template->getTemplatedDecl();
4264 }
4265
4266 // 2. Create the canonical declaration.
4267 // Note that we do not instantiate a definition until we see an odr-use
4268 // in DoMarkVarDeclReferenced().
4269 // FIXME: LateAttrs et al.?
4271 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4272 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4273 if (!Decl)
4274 return true;
4275
4276 if (AmbiguousPartialSpec) {
4277 // Partial ordering did not produce a clear winner. Complain.
4279 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4280 << Decl;
4281
4282 // Print the matching partial specializations.
4283 for (MatchResult P : Matched)
4284 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4285 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4286 *P.Args);
4287 return true;
4288 }
4289
4291 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4292 Decl->setInstantiationOf(D, PartialSpecArgs);
4293
4294 checkSpecializationReachability(TemplateNameLoc, Decl);
4295
4296 assert(Decl && "No variable template specialization?");
4297 return Decl;
4298}
4299
4301 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4302 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4303 const TemplateArgumentListInfo *TemplateArgs) {
4304
4305 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4306 *TemplateArgs);
4307 if (Decl.isInvalid())
4308 return ExprError();
4309
4310 if (!Decl.get())
4311 return ExprResult();
4312
4313 VarDecl *Var = cast<VarDecl>(Decl.get());
4316 NameInfo.getLoc());
4317
4318 // Build an ordinary singleton decl ref.
4319 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4320}
4321
4324 Diag(Loc, diag::err_template_missing_args)
4325 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4326 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4327 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4328 }
4329}
4330
4332 bool TemplateKeyword,
4333 TemplateDecl *TD,
4336 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4338}
4339
4342 SourceLocation TemplateKWLoc,
4343 const DeclarationNameInfo &ConceptNameInfo,
4344 NamedDecl *FoundDecl,
4345 ConceptDecl *NamedConcept,
4346 const TemplateArgumentListInfo *TemplateArgs) {
4347 assert(NamedConcept && "A concept template id without a template?");
4348
4349 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4351 NamedConcept, ConceptNameInfo.getLoc(),
4352 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4353 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4354 /*UpdateArgsWithConversions=*/false))
4355 return ExprError();
4356
4357 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4358
4360 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4361 CanonicalConverted);
4362 ConstraintSatisfaction Satisfaction;
4363 bool AreArgsDependent =
4365 *TemplateArgs, CanonicalConverted);
4366 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4367 /*Final=*/false);
4369
4372
4373 if (!AreArgsDependent &&
4375 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4376 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4377 TemplateArgs->getRAngleLoc()),
4378 Satisfaction))
4379 return ExprError();
4380 auto *CL = ConceptReference::Create(
4381 Context,
4383 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4386 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4387}
4388
4390 SourceLocation TemplateKWLoc,
4391 LookupResult &R,
4392 bool RequiresADL,
4393 const TemplateArgumentListInfo *TemplateArgs) {
4394 // FIXME: Can we do any checking at this point? I guess we could check the
4395 // template arguments that we have against the template name, if the template
4396 // name refers to a single template. That's not a terribly common case,
4397 // though.
4398 // foo<int> could identify a single function unambiguously
4399 // This approach does NOT work, since f<int>(1);
4400 // gets resolved prior to resorting to overload resolution
4401 // i.e., template<class T> void f(double);
4402 // vs template<class T, class U> void f(U);
4403
4404 // These should be filtered out by our callers.
4405 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4406
4407 // Non-function templates require a template argument list.
4408 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4409 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4411 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4412 return ExprError();
4413 }
4414 }
4415 bool KnownDependent = false;
4416 // In C++1y, check variable template ids.
4417 if (R.getAsSingle<VarTemplateDecl>()) {
4420 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4421 if (Res.isInvalid() || Res.isUsable())
4422 return Res;
4423 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4424 KnownDependent = true;
4425 }
4426
4427 if (R.getAsSingle<ConceptDecl>()) {
4428 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4430 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4431 }
4432
4433 // We don't want lookup warnings at this point.
4435
4438 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4439 R.begin(), R.end(), KnownDependent);
4440
4441 // Model the templates with UnresolvedTemplateTy. The expression should then
4442 // either be transformed in an instantiation or be diagnosed in
4443 // CheckPlaceholderExpr.
4444 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4447
4448 return ULE;
4449}
4450
4452 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4453 const DeclarationNameInfo &NameInfo,
4454 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4455 assert(TemplateArgs || TemplateKWLoc.isValid());
4456
4457 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4458 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4459 /*EnteringContext=*/false, TemplateKWLoc))
4460 return ExprError();
4461
4462 if (R.isAmbiguous())
4463 return ExprError();
4464
4466 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4467
4468 if (R.empty()) {
4470 Diag(NameInfo.getLoc(), diag::err_no_member)
4471 << NameInfo.getName() << DC << SS.getRange();
4472 return ExprError();
4473 }
4474
4475 // If necessary, build an implicit class member access.
4476 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4477 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4478 /*S=*/nullptr);
4479
4480 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4481}
4482
4484 CXXScopeSpec &SS,
4485 SourceLocation TemplateKWLoc,
4486 const UnqualifiedId &Name,
4487 ParsedType ObjectType,
4488 bool EnteringContext,
4490 bool AllowInjectedClassName) {
4491 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4492 Diag(TemplateKWLoc,
4494 diag::warn_cxx98_compat_template_outside_of_template :
4495 diag::ext_template_outside_of_template)
4496 << FixItHint::CreateRemoval(TemplateKWLoc);
4497
4498 if (SS.isInvalid())
4499 return TNK_Non_template;
4500
4501 // Figure out where isTemplateName is going to look.
4502 DeclContext *LookupCtx = nullptr;
4503 if (SS.isNotEmpty())
4504 LookupCtx = computeDeclContext(SS, EnteringContext);
4505 else if (ObjectType)
4506 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4507
4508 // C++0x [temp.names]p5:
4509 // If a name prefixed by the keyword template is not the name of
4510 // a template, the program is ill-formed. [Note: the keyword
4511 // template may not be applied to non-template members of class
4512 // templates. -end note ] [ Note: as is the case with the
4513 // typename prefix, the template prefix is allowed in cases
4514 // where it is not strictly necessary; i.e., when the
4515 // nested-name-specifier or the expression on the left of the ->
4516 // or . is not dependent on a template-parameter, or the use
4517 // does not appear in the scope of a template. -end note]
4518 //
4519 // Note: C++03 was more strict here, because it banned the use of
4520 // the "template" keyword prior to a template-name that was not a
4521 // dependent name. C++ DR468 relaxed this requirement (the
4522 // "template" keyword is now permitted). We follow the C++0x
4523 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4524 bool MemberOfUnknownSpecialization;
4525 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4526 ObjectType, EnteringContext, Result,
4527 MemberOfUnknownSpecialization);
4528 if (TNK != TNK_Non_template) {
4529 // We resolved this to a (non-dependent) template name. Return it.
4530 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4531 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4532 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4533 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4534 // C++14 [class.qual]p2:
4535 // In a lookup in which function names are not ignored and the
4536 // nested-name-specifier nominates a class C, if the name specified
4537 // [...] is the injected-class-name of C, [...] the name is instead
4538 // considered to name the constructor
4539 //
4540 // We don't get here if naming the constructor would be valid, so we
4541 // just reject immediately and recover by treating the
4542 // injected-class-name as naming the template.
4543 Diag(Name.getBeginLoc(),
4544 diag::ext_out_of_line_qualified_id_type_names_constructor)
4545 << Name.Identifier
4546 << 0 /*injected-class-name used as template name*/
4547 << TemplateKWLoc.isValid();
4548 }
4549 return TNK;
4550 }
4551
4552 if (!MemberOfUnknownSpecialization) {
4553 // Didn't find a template name, and the lookup wasn't dependent.
4554 // Do the lookup again to determine if this is a "nothing found" case or
4555 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4556 // need to do this.
4558 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4560 // Tell LookupTemplateName that we require a template so that it diagnoses
4561 // cases where it finds a non-template.
4562 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4563 ? RequiredTemplateKind(TemplateKWLoc)
4565 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4566 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4567 !R.isAmbiguous()) {
4568 if (LookupCtx)
4569 Diag(Name.getBeginLoc(), diag::err_no_member)
4570 << DNI.getName() << LookupCtx << SS.getRange();
4571 else
4572 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4573 << DNI.getName() << SS.getRange();
4574 }
4575 return TNK_Non_template;
4576 }
4577
4578 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4579
4580 switch (Name.getKind()) {
4583 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4585
4588 Qualifier, Name.OperatorFunctionId.Operator));
4589 return TNK_Function_template;
4590
4592 // This is a kind of template name, but can never occur in a dependent
4593 // scope (literal operators can only be declared at namespace scope).
4594 break;
4595
4596 default:
4597 break;
4598 }
4599
4600 // This name cannot possibly name a dependent template. Diagnose this now
4601 // rather than building a dependent template name that can never be valid.
4602 Diag(Name.getBeginLoc(),
4603 diag::err_template_kw_refers_to_dependent_non_template)
4604 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4605 << TemplateKWLoc.isValid() << TemplateKWLoc;
4606 return TNK_Non_template;
4607}
4608
4611 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4612 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4613 const TemplateArgument &Arg = AL.getArgument();
4614 QualType ArgType;
4615 TypeSourceInfo *TSI = nullptr;
4616
4617 // Check template type parameter.
4618 switch(Arg.getKind()) {
4620 // C++ [temp.arg.type]p1:
4621 // A template-argument for a template-parameter which is a
4622 // type shall be a type-id.
4623 ArgType = Arg.getAsType();
4624 TSI = AL.getTypeSourceInfo();
4625 break;
4628 // We have a template type parameter but the template argument
4629 // is a template without any arguments.
4630 SourceRange SR = AL.getSourceRange();
4633 return true;
4634 }
4636 // We have a template type parameter but the template argument is an
4637 // expression; see if maybe it is missing the "typename" keyword.
4638 CXXScopeSpec SS;
4639 DeclarationNameInfo NameInfo;
4640
4641 if (DependentScopeDeclRefExpr *ArgExpr =
4642 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4643 SS.Adopt(ArgExpr->getQualifierLoc());
4644 NameInfo = ArgExpr->getNameInfo();
4645 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4646 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4647 if (ArgExpr->isImplicitAccess()) {
4648 SS.Adopt(ArgExpr->getQualifierLoc());
4649 NameInfo = ArgExpr->getMemberNameInfo();
4650 }
4651 }
4652
4653 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4654 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4655 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4656
4657 if (Result.getAsSingle<TypeDecl>() ||
4658 Result.wasNotFoundInCurrentInstantiation()) {
4659 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4660 // Suggest that the user add 'typename' before the NNS.
4662 Diag(Loc, getLangOpts().MSVCCompat
4663 ? diag::ext_ms_template_type_arg_missing_typename
4664 : diag::err_template_arg_must_be_type_suggest)
4665 << FixItHint::CreateInsertion(Loc, "typename ");
4667
4668 // Recover by synthesizing a type using the location information that we
4669 // already have.
4671 SS.getScopeRep(), II);
4672 TypeLocBuilder TLB;
4674 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4676 TL.setNameLoc(NameInfo.getLoc());
4677 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4678
4679 // Overwrite our input TemplateArgumentLoc so that we can recover
4680 // properly.
4683
4684 break;
4685 }
4686 }
4687 // fallthrough
4688 [[fallthrough]];
4689 }
4690 default: {
4691 // We allow instantiateing a template with template argument packs when
4692 // building deduction guides.
4693 if (Arg.getKind() == TemplateArgument::Pack &&
4694 CodeSynthesisContexts.back().Kind ==
4696 SugaredConverted.push_back(Arg);
4697 CanonicalConverted.push_back(Arg);
4698 return false;
4699 }
4700 // We have a template type parameter but the template argument
4701 // is not a type.
4702 SourceRange SR = AL.getSourceRange();
4703 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4705
4706 return true;
4707 }
4708 }
4709
4710 if (CheckTemplateArgument(TSI))
4711 return true;
4712
4713 // Objective-C ARC:
4714 // If an explicitly-specified template argument type is a lifetime type
4715 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4716 if (getLangOpts().ObjCAutoRefCount &&
4717 ArgType->isObjCLifetimeType() &&
4718 !ArgType.getObjCLifetime()) {
4719 Qualifiers Qs;
4721 ArgType = Context.getQualifiedType(ArgType, Qs);
4722 }
4723
4724 SugaredConverted.push_back(TemplateArgument(ArgType));
4725 CanonicalConverted.push_back(
4727 return false;
4728}
4729
4730/// Substitute template arguments into the default template argument for
4731/// the given template type parameter.
4732///
4733/// \param SemaRef the semantic analysis object for which we are performing
4734/// the substitution.
4735///
4736/// \param Template the template that we are synthesizing template arguments
4737/// for.
4738///
4739/// \param TemplateLoc the location of the template name that started the
4740/// template-id we are checking.
4741///
4742/// \param RAngleLoc the location of the right angle bracket ('>') that
4743/// terminates the template-id.
4744///
4745/// \param Param the template template parameter whose default we are
4746/// substituting into.
4747///
4748/// \param Converted the list of template arguments provided for template
4749/// parameters that precede \p Param in the template parameter list.
4750///
4751/// \param Output the resulting substituted template argument.
4752///
4753/// \returns true if an error occurred.
4755 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4756 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4757 ArrayRef<TemplateArgument> SugaredConverted,
4758 ArrayRef<TemplateArgument> CanonicalConverted,
4759 TemplateArgumentLoc &Output) {
4760 Output = Param->getDefaultArgument();
4761
4762 // If the argument type is dependent, instantiate it now based
4763 // on the previously-computed template arguments.
4764 if (Output.getArgument().isInstantiationDependent()) {
4765 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4766 SugaredConverted,
4767 SourceRange(TemplateLoc, RAngleLoc));
4768 if (Inst.isInvalid())
4769 return true;
4770
4771 // Only substitute for the innermost template argument list.
4772 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4773 /*Final=*/true);
4774 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4775 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4776
4777 bool ForLambdaCallOperator = false;
4778 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4779 ForLambdaCallOperator = Rec->isLambda();
4780 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4781 !ForLambdaCallOperator);
4782
4783 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4784 Param->getDefaultArgumentLoc(),
4785 Param->getDeclName()))
4786 return true;
4787 }
4788
4789 return false;
4790}
4791
4792/// Substitute template arguments into the default template argument for
4793/// the given non-type template parameter.
4794///
4795/// \param SemaRef the semantic analysis object for which we are performing
4796/// the substitution.
4797///
4798/// \param Template the template that we are synthesizing template arguments
4799/// for.
4800///
4801/// \param TemplateLoc the location of the template name that started the
4802/// template-id we are checking.
4803///
4804/// \param RAngleLoc the location of the right angle bracket ('>') that
4805/// terminates the template-id.
4806///
4807/// \param Param the non-type template parameter whose default we are
4808/// substituting into.
4809///
4810/// \param Converted the list of template arguments provided for template
4811/// parameters that precede \p Param in the template parameter list.
4812///
4813/// \returns the substituted template argument, or NULL if an error occurred.
4815 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4816 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
4817 ArrayRef<TemplateArgument> SugaredConverted,
4818 ArrayRef<TemplateArgument> CanonicalConverted,
4819 TemplateArgumentLoc &Output) {
4820 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4821 SugaredConverted,
4822 SourceRange(TemplateLoc, RAngleLoc));
4823 if (Inst.isInvalid())
4824 return true;
4825
4826 // Only substitute for the innermost template argument list.
4827 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4828 /*Final=*/true);
4829 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4830 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4831
4832 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4833 EnterExpressionEvaluationContext ConstantEvaluated(
4835 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
4836 TemplateArgLists, Output);
4837}
4838
4839/// Substitute template arguments into the default template argument for
4840/// the given template template parameter.
4841///
4842/// \param SemaRef the semantic analysis object for which we are performing
4843/// the substitution.
4844///
4845/// \param Template the template that we are synthesizing template arguments
4846/// for.
4847///
4848/// \param TemplateLoc the location of the template name that started the
4849/// template-id we are checking.
4850///
4851/// \param RAngleLoc the location of the right angle bracket ('>') that
4852/// terminates the template-id.
4853///
4854/// \param Param the template template parameter whose default we are
4855/// substituting into.
4856///
4857/// \param Converted the list of template arguments provided for template
4858/// parameters that precede \p Param in the template parameter list.
4859///
4860/// \param QualifierLoc Will be set to the nested-name-specifier (with
4861/// source-location information) that precedes the template name.
4862///
4863/// \returns the substituted template argument, or NULL if an error occurred.
4865 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4866 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
4867 ArrayRef<TemplateArgument> SugaredConverted,
4868 ArrayRef<TemplateArgument> CanonicalConverted,
4869 NestedNameSpecifierLoc &QualifierLoc) {
4871 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
4872 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
4873 if (Inst.isInvalid())
4874 return TemplateName();
4875
4876 // Only substitute for the innermost template argument list.
4877 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4878 /*Final=*/true);
4879 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4880 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4881
4882 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4883 // Substitute into the nested-name-specifier first,
4884 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4885 if (QualifierLoc) {
4886 QualifierLoc =
4887 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4888 if (!QualifierLoc)
4889 return TemplateName();
4890 }
4891
4892 return SemaRef.SubstTemplateName(
4893 QualifierLoc,
4896 TemplateArgLists);
4897}
4898
4900 TemplateDecl *Template, SourceLocation TemplateLoc,
4901 SourceLocation RAngleLoc, Decl *Param,
4902 ArrayRef<TemplateArgument> SugaredConverted,
4903 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
4904 HasDefaultArg = false;
4905
4906 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4907 if (!hasReachableDefaultArgument(TypeParm))
4908 return TemplateArgumentLoc();
4909
4910 HasDefaultArg = true;
4911 TemplateArgumentLoc Output;
4912 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4913 TypeParm, SugaredConverted,
4914 CanonicalConverted, Output))
4915 return TemplateArgumentLoc();
4916 return Output;
4917 }
4918
4919 if (NonTypeTemplateParmDecl *NonTypeParm
4920 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4921 if (!hasReachableDefaultArgument(NonTypeParm))
4922 return TemplateArgumentLoc();
4923
4924 HasDefaultArg = true;
4925 TemplateArgumentLoc Output;
4926 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4927 NonTypeParm, SugaredConverted,
4928 CanonicalConverted, Output))
4929 return TemplateArgumentLoc();
4930 return Output;
4931 }
4932
4933 TemplateTemplateParmDecl *TempTempParm
4934 = cast<TemplateTemplateParmDecl>(Param);
4935 if (!hasReachableDefaultArgument(TempTempParm))
4936 return TemplateArgumentLoc();
4937
4938 HasDefaultArg = true;
4939 NestedNameSpecifierLoc QualifierLoc;
4941 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
4942 CanonicalConverted, QualifierLoc);
4943 if (TName.isNull())
4944 return TemplateArgumentLoc();
4945
4946 return TemplateArgumentLoc(
4947 Context, TemplateArgument(TName),
4949 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4950}
4951
4952/// Convert a template-argument that we parsed as a type into a template, if
4953/// possible. C++ permits injected-class-names to perform dual service as
4954/// template template arguments and as template type arguments.
4957 // Extract and step over any surrounding nested-name-specifier.
4958 NestedNameSpecifierLoc QualLoc;
4959 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4960 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
4961 return TemplateArgumentLoc();
4962
4963 QualLoc = ETLoc.getQualifierLoc();
4964 TLoc = ETLoc.getNamedTypeLoc();
4965 }
4966 // If this type was written as an injected-class-name, it can be used as a
4967 // template template argument.
4968 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4969 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
4970 QualLoc, InjLoc.getNameLoc());
4971
4972 // If this type was written as an injected-class-name, it may have been
4973 // converted to a RecordType during instantiation. If the RecordType is
4974 // *not* wrapped in a TemplateSpecializationType and denotes a class
4975 // template specialization, it must have come from an injected-class-name.
4976 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4977 if (auto *CTSD =
4978 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4979 return TemplateArgumentLoc(Context,
4980 TemplateName(CTSD->getSpecializedTemplate()),
4981 QualLoc, RecLoc.getNameLoc());
4982
4983 return TemplateArgumentLoc();
4984}
4985
4987 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
4988 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
4989 unsigned ArgumentPackIndex,
4990 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4991 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
4993 // Check template type parameters.
4994 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4995 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
4996 CanonicalConverted);
4997
4998 // Check non-type template parameters.
4999 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5000 // Do substitution on the type of the non-type template parameter
5001 // with the template arguments we've seen thus far. But if the
5002 // template has a dependent context then we cannot substitute yet.
5003 QualType NTTPType = NTTP->getType();
5004 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5005 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5006
5007 if (NTTPType->isInstantiationDependentType() &&
5008 !isa<TemplateTemplateParmDecl>(Template) &&
5009 !Template->getDeclContext()->isDependentContext()) {
5010 // Do substitution on the type of the non-type template parameter.
5011 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5012 SugaredConverted,
5013 SourceRange(TemplateLoc, RAngleLoc));
5014 if (Inst.isInvalid())
5015 return true;
5016
5017 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5018 /*Final=*/true);
5019 // If the parameter is a pack expansion, expand this slice of the pack.
5020 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5022 ArgumentPackIndex);
5023 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5024 NTTP->getDeclName());
5025 } else {
5026 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5027 NTTP->getDeclName());
5028 }
5029
5030 // If that worked, check the non-type template parameter type
5031 // for validity.
5032 if (!NTTPType.isNull())
5033 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5034 NTTP->getLocation());
5035 if (NTTPType.isNull())
5036 return true;
5037 }
5038
5039 switch (Arg.getArgument().getKind()) {
5041 llvm_unreachable("Should never see a NULL template argument here");
5042
5044 Expr *E = Arg.getArgument().getAsExpr();
5045 TemplateArgument SugaredResult, CanonicalResult;
5046 unsigned CurSFINAEErrors = NumSFINAEErrors;
5047 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5048 CanonicalResult, CTAK);
5049 if (Res.isInvalid())
5050 return true;
5051 // If the current template argument causes an error, give up now.
5052 if (CurSFINAEErrors < NumSFINAEErrors)
5053 return true;
5054
5055 // If the resulting expression is new, then use it in place of the
5056 // old expression in the template argument.
5057 if (Res.get() != E) {
5058 TemplateArgument TA(Res.get());
5059 Arg = TemplateArgumentLoc(TA, Res.get());
5060 }
5061
5062 SugaredConverted.push_back(SugaredResult);
5063 CanonicalConverted.push_back(CanonicalResult);
5064 break;
5065 }
5066
5071 // We've already checked this template argument, so just copy
5072 // it to the list of converted arguments.
5073 SugaredConverted.push_back(Arg.getArgument());
5074 CanonicalConverted.push_back(
5076 break;
5077
5080 // We were given a template template argument. It may not be ill-formed;
5081 // see below.
5082 if (DependentTemplateName *DTN
5085 // We have a template argument such as \c T::template X, which we
5086 // parsed as a template template argument. However, since we now
5087 // know that we need a non-type template argument, convert this
5088 // template name into an expression.
5089
5090 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5091 Arg.getTemplateNameLoc());
5092
5093 CXXScopeSpec SS;
5095 // FIXME: the template-template arg was a DependentTemplateName,
5096 // so it was provided with a template keyword. However, its source
5097 // location is not stored in the template argument structure.
5098 SourceLocation TemplateKWLoc;
5100 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5101 nullptr);
5102
5103 // If we parsed the template argument as a pack expansion, create a
5104 // pack expansion expression.
5107 if (E.isInvalid())
5108 return true;
5109 }
5110
5111 TemplateArgument SugaredResult, CanonicalResult;
5112 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5113 CanonicalResult, CTAK_Specified);
5114 if (E.isInvalid())
5115 return true;
5116
5117 SugaredConverted.push_back(SugaredResult);
5118 CanonicalConverted.push_back(CanonicalResult);
5119 break;
5120 }
5121
5122 // We have a template argument that actually does refer to a class
5123 // template, alias template, or template template parameter, and
5124 // therefore cannot be a non-type template argument.
5125 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5126 << Arg.getSourceRange();
5128
5129 return true;
5130
5132 // We have a non-type template parameter but the template
5133 // argument is a type.
5134
5135 // C++ [temp.arg]p2:
5136 // In a template-argument, an ambiguity between a type-id and
5137 // an expression is resolved to a type-id, regardless of the
5138 // form of the corresponding template-parameter.
5139 //
5140 // We warn specifically about this case, since it can be rather
5141 // confusing for users.
5142 QualType T = Arg.getArgument().getAsType();
5143 SourceRange SR = Arg.getSourceRange();
5144 if (T->isFunctionType())
5145 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5146 else
5147 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5149 return true;
5150 }
5151
5153 llvm_unreachable("Caller must expand template argument packs");
5154 }
5155
5156 return false;
5157 }
5158
5159
5160 // Check template template parameters.
5161 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5162
5163 TemplateParameterList *Params = TempParm->getTemplateParameters();
5164 if (TempParm->isExpandedParameterPack())
5165 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5166
5167 // Substitute into the template parameter list of the template
5168 // template parameter, since previously-supplied template arguments
5169 // may appear within the template template parameter.
5170 //
5171 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5172 {
5173 // Set up a template instantiation context.
5175 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5176 SugaredConverted,
5177 SourceRange(TemplateLoc, RAngleLoc));
5178 if (Inst.isInvalid())
5179 return true;
5180
5181 Params =
5184 Template, SugaredConverted, /*Final=*/true),
5185 /*EvaluateConstraints=*/false);
5186 if (!Params)
5187 return true;
5188 }
5189
5190 // C++1z [temp.local]p1: (DR1004)
5191 // When [the injected-class-name] is used [...] as a template-argument for
5192 // a template template-parameter [...] it refers to the class template
5193 // itself.
5197 if (!ConvertedArg.getArgument().isNull())
5198 Arg = ConvertedArg;
5199 }
5200
5201 switch (Arg.getArgument().getKind()) {
5203 llvm_unreachable("Should never see a NULL template argument here");
5204
5207 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5208 /*IsDeduced=*/CTAK != CTAK_Specified))
5209 return true;
5210
5211 SugaredConverted.push_back(Arg.getArgument());
5212 CanonicalConverted.push_back(
5214 break;
5215
5218 // We have a template template parameter but the template
5219 // argument does not refer to a template.
5220 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5221 << getLangOpts().CPlusPlus11;
5222 return true;
5223
5228 llvm_unreachable("non-type argument with template template parameter");
5229
5231 llvm_unreachable("Caller must expand template argument packs");
5232 }
5233
5234 return false;
5235}
5236
5237/// Diagnose a missing template argument.
5238template<typename TemplateParmDecl>
5240 TemplateDecl *TD,
5241 const TemplateParmDecl *D,
5243 // Dig out the most recent declaration of the template parameter; there may be
5244 // declarations of the template that are more recent than TD.
5245 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5246 ->getTemplateParameters()
5247 ->getParam(D->getIndex()));
5248
5249 // If there's a default argument that's not reachable, diagnose that we're
5250 // missing a module import.
5252 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5253 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5254 D->getDefaultArgumentLoc(), Modules,
5256 /*Recover*/true);
5257 return true;
5258 }
5259
5260 // FIXME: If there's a more recent default argument that *is* visible,
5261 // diagnose that it was declared too late.
5262
5264
5265 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5266 << /*not enough args*/0
5268 << TD;
5269 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5270 return true;
5271}
5272
5273/// Check that the given template argument list is well-formed
5274/// for specializing the given template.
5276 TemplateDecl *Template, SourceLocation TemplateLoc,
5277 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5278 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5279 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5280 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5281 bool PartialOrderingTTP) {
5282
5284 *ConstraintsNotSatisfied = false;
5285
5286 // Make a copy of the template arguments for processing. Only make the
5287 // changes at the end when successful in matching the arguments to the
5288 // template.
5289 TemplateArgumentListInfo NewArgs = TemplateArgs;
5290
5292
5293 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5294
5295 // C++ [temp.arg]p1:
5296 // [...] The type and form of each template-argument specified in
5297 // a template-id shall match the type and form specified for the
5298 // corresponding parameter declared by the template in its
5299 // template-parameter-list.
5300 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5301 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5302 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5303 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5304 LocalInstantiationScope InstScope(*this, true);
5305 for (TemplateParameterList::iterator Param = Params->begin(),
5306 ParamEnd = Params->end();
5307 Param != ParamEnd; /* increment in loop */) {
5308 // If we have an expanded parameter pack, make sure we don't have too
5309 // many arguments.
5310 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5311 if (*Expansions == SugaredArgumentPack.size()) {
5312 // We're done with this parameter pack. Pack up its arguments and add
5313 // them to the list.
5314 SugaredConverted.push_back(
5315 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5316 SugaredArgumentPack.clear();
5317
5318 CanonicalConverted.push_back(
5319 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5320 CanonicalArgumentPack.clear();
5321
5322 // This argument is assigned to the next parameter.
5323 ++Param;
5324 continue;
5325 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5326 // Not enough arguments for this parameter pack.
5327 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5328 << /*not enough args*/0
5330 << Template;
5331 NoteTemplateLocation(*Template, Params->getSourceRange());
5332 return true;
5333 }
5334 }
5335
5336 if (ArgIdx < NumArgs) {
5337 // Check the template argument we were given.
5338 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5339 RAngleLoc, SugaredArgumentPack.size(),
5340 SugaredConverted, CanonicalConverted,
5342 return true;
5343
5344 CanonicalConverted.back().setIsDefaulted(
5346 Context, NewArgs[ArgIdx].getArgument(), *Param,
5347 CanonicalConverted, Params->getDepth()));
5348
5349 bool PackExpansionIntoNonPack =
5350 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5351 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5352 // CWG1430: Don't diagnose this pack expansion when partial
5353 // ordering template template parameters. Some uses of the template could
5354 // be valid, and invalid uses will be diagnosed later during
5355 // instantiation.
5356 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5357 (isa<TypeAliasTemplateDecl>(Template) ||
5358 isa<ConceptDecl>(Template))) {
5359 // CWG1430: we have a pack expansion as an argument to an
5360 // alias template, and it's not part of a parameter pack. This
5361 // can't be canonicalized, so reject it now.
5362 // As for concepts - we cannot normalize constraints where this
5363 // situation exists.
5364 Diag(NewArgs[ArgIdx].getLocation(),
5365 diag::err_template_expansion_into_fixed_list)
5366 << (isa<ConceptDecl>(Template) ? 1 : 0)
5367 << NewArgs[ArgIdx].getSourceRange();
5369 return true;
5370 }
5371
5372 // We're now done with this argument.
5373 ++ArgIdx;
5374
5375 if ((*Param)->isTemplateParameterPack()) {
5376 // The template parameter was a template parameter pack, so take the
5377 // deduced argument and place it on the argument pack. Note that we
5378 // stay on the same template parameter so that we can deduce more
5379 // arguments.
5380 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5381 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5382 } else {
5383 // Move to the next template parameter.
5384 ++Param;
5385 }
5386
5387 // If we just saw a pack expansion into a non-pack, then directly convert
5388 // the remaining arguments, because we don't know what parameters they'll
5389 // match up with.
5390 if (PackExpansionIntoNonPack) {
5391 if (!SugaredArgumentPack.empty()) {
5392 // If we were part way through filling in an expanded parameter pack,
5393 // fall back to just producing individual arguments.
5394 SugaredConverted.insert(SugaredConverted.end(),
5395 SugaredArgumentPack.begin(),
5396 SugaredArgumentPack.end());
5397 SugaredArgumentPack.clear();
5398
5399 CanonicalConverted.insert(CanonicalConverted.end(),
5400 CanonicalArgumentPack.begin(),
5401 CanonicalArgumentPack.end());
5402 CanonicalArgumentPack.clear();
5403 }
5404
5405 while (ArgIdx < NumArgs) {
5406 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5407 SugaredConverted.push_back(Arg);
5408 CanonicalConverted.push_back(
5410 ++ArgIdx;
5411 }
5412
5413 return false;
5414 }
5415
5416 continue;
5417 }
5418
5419 // If we're checking a partial template argument list, we're done.
5420 if (PartialTemplateArgs) {
5421 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5422 SugaredConverted.push_back(
5423 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5424 CanonicalConverted.push_back(
5425 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5426 }
5427 return false;
5428 }
5429
5430 // If we have a template parameter pack with no more corresponding
5431 // arguments, just break out now and we'll fill in the argument pack below.
5432 if ((*Param)->isTemplateParameterPack()) {
5433 assert(!getExpandedPackSize(*Param) &&
5434 "Should have dealt with this already");
5435
5436 // A non-expanded parameter pack before the end of the parameter list
5437 // only occurs for an ill-formed template parameter list, unless we've
5438 // got a partial argument list for a function template, so just bail out.
5439 if (Param + 1 != ParamEnd) {
5440 assert(
5441 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5442 "Concept templates must have parameter packs at the end.");
5443 return true;
5444 }
5445
5446 SugaredConverted.push_back(
5447 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5448 SugaredArgumentPack.clear();
5449
5450 CanonicalConverted.push_back(
5451 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5452 CanonicalArgumentPack.clear();
5453
5454 ++Param;
5455 continue;
5456 }
5457
5458 // Check whether we have a default argument.
5460
5461 // Retrieve the default template argument from the template
5462 // parameter. For each kind of template parameter, we substitute the
5463 // template arguments provided thus far and any "outer" template arguments
5464 // (when the template parameter was part of a nested template) into
5465 // the default argument.
5466 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5468 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5469 NewArgs);
5470
5471 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5472 TTP, SugaredConverted,
5473 CanonicalConverted, Arg))
5474 return true;
5475 } else if (NonTypeTemplateParmDecl *NTTP
5476 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5477 if (!hasReachableDefaultArgument(NTTP))
5478 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5479 NewArgs);
5480
5481 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5482 NTTP, SugaredConverted,
5483 CanonicalConverted, Arg))
5484 return true;
5485 } else {
5486 TemplateTemplateParmDecl *TempParm
5487 = cast<TemplateTemplateParmDecl>(*Param);
5488
5489 if (!hasReachableDefaultArgument(TempParm))
5490 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5491 NewArgs);
5492
5493 NestedNameSpecifierLoc QualifierLoc;
5495 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
5496 CanonicalConverted, QualifierLoc);
5497 if (Name.isNull())
5498 return true;
5499
5500 Arg = TemplateArgumentLoc(
5501 Context, TemplateArgument(Name), QualifierLoc,
5503 }
5504
5505 // Introduce an instantiation record that describes where we are using
5506 // the default template argument. We're not actually instantiating a
5507 // template here, we just create this object to put a note into the
5508 // context stack.
5509 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5510 SugaredConverted,
5511 SourceRange(TemplateLoc, RAngleLoc));
5512 if (Inst.isInvalid())
5513 return true;
5514
5515 // Check the default template argument.
5516 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5517 SugaredConverted, CanonicalConverted,
5519 return true;
5520
5521 CanonicalConverted.back().setIsDefaulted(true);
5522
5523 // Core issue 150 (assumed resolution): if this is a template template
5524 // parameter, keep track of the default template arguments from the
5525 // template definition.
5526 if (isTemplateTemplateParameter)
5527 NewArgs.addArgument(Arg);
5528
5529 // Move to the next template parameter and argument.
5530 ++Param;
5531 ++ArgIdx;
5532 }
5533
5534 // If we're performing a partial argument substitution, allow any trailing
5535 // pack expansions; they might be empty. This can happen even if
5536 // PartialTemplateArgs is false (the list of arguments is complete but
5537 // still dependent).
5538 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5540 while (ArgIdx < NumArgs &&
5541 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5542 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5543 SugaredConverted.push_back(Arg);
5544 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5545 }
5546 }
5547
5548 // If we have any leftover arguments, then there were too many arguments.
5549 // Complain and fail.
5550 if (ArgIdx < NumArgs) {
5551 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5552 << /*too many args*/1
5554 << Template
5555 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5556 NoteTemplateLocation(*Template, Params->getSourceRange());
5557 return true;
5558 }
5559
5560 // No problems found with the new argument list, propagate changes back
5561 // to caller.
5562 if (UpdateArgsWithConversions)
5563 TemplateArgs = std::move(NewArgs);
5564
5565 if (!PartialTemplateArgs) {
5566 // Setup the context/ThisScope for the case where we are needing to
5567 // re-instantiate constraints outside of normal instantiation.
5568 DeclContext *NewContext = Template->getDeclContext();
5569
5570 // If this template is in a template, make sure we extract the templated
5571 // decl.
5572 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5573 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5574 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5575
5576 Qualifiers ThisQuals;
5577 if (const auto *Method =
5578 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5579 ThisQuals = Method->getMethodQualifiers();
5580
5581 ContextRAII Context(*this, NewContext);
5582 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5583
5585 Template, NewContext, /*Final=*/false, CanonicalConverted,
5586 /*RelativeToPrimary=*/true,
5587 /*Pattern=*/nullptr,
5588 /*ForConceptInstantiation=*/true);
5590 Template, MLTAL,
5591 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5594 return true;
5595 }
5596 }
5597
5598 return false;
5599}
5600
5601namespace {
5602 class UnnamedLocalNoLinkageFinder
5603 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5604 {
5605 Sema &S;
5606 SourceRange SR;
5607
5609
5610 public:
5611 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5612
5613 bool Visit(QualType T) {
5614 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5615 }
5616
5617#define TYPE(Class, Parent) \
5618 bool Visit##Class##Type(const Class##Type *);
5619#define ABSTRACT_TYPE(Class, Parent) \
5620 bool Visit##Class##Type(const Class##Type *) { return false; }
5621#define NON_CANONICAL_TYPE(Class, Parent) \
5622 bool Visit##Class##Type(const Class##Type *) { return false; }
5623#include "clang/AST/TypeNodes.inc"
5624
5625 bool VisitTagDecl(const TagDecl *Tag);
5626 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5627 };
5628} // end anonymous namespace
5629
5630bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5631 return false;
5632}
5633
5634bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5635 return Visit(T->getElementType());
5636}
5637
5638bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5639 return Visit(T->getPointeeType());
5640}
5641
5642bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5643 const BlockPointerType* T) {
5644 return Visit(T->getPointeeType());
5645}
5646
5647bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5648 const LValueReferenceType* T) {
5649 return Visit(T->getPointeeType());
5650}
5651
5652bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5653 const RValueReferenceType* T) {
5654 return Visit(T->getPointeeType());
5655}
5656
5657bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5658 const MemberPointerType* T) {
5659 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5660}
5661
5662bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5663 const ConstantArrayType* T) {
5664 return Visit(T->getElementType());
5665}
5666
5667bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5668 const IncompleteArrayType* T) {
5669 return Visit(T->getElementType());
5670}
5671
5672bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5673 const VariableArrayType* T) {
5674 return Visit(T->getElementType());
5675}
5676
5677bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5678 const DependentSizedArrayType* T) {
5679 return Visit(T->getElementType());
5680}
5681
5682bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5684 return Visit(T->getElementType());
5685}
5686
5687bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5688 const DependentSizedMatrixType *T) {
5689 return Visit(T->getElementType());
5690}
5691
5692bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5694 return Visit(T->getPointeeType());
5695}
5696
5697bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5698 return Visit(T->getElementType());
5699}
5700
5701bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5702 const DependentVectorType *T) {
5703 return Visit(T->getElementType());
5704}
5705
5706bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5707 return Visit(T->getElementType());
5708}
5709
5710bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5711 const ConstantMatrixType *T) {
5712 return Visit(T->getElementType());
5713}
5714
5715bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5716 const FunctionProtoType* T) {
5717 for (const auto &A : T->param_types()) {
5718 if (Visit(A))
5719 return true;
5720 }
5721
5722 return Visit(T->getReturnType());
5723}
5724
5725bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5726 const FunctionNoProtoType* T) {
5727 return Visit(T->getReturnType());
5728}
5729
5730bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5731 const UnresolvedUsingType*) {
5732 return false;
5733}
5734
5735bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5736 return false;
5737}
5738
5739bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5740 return Visit(T->getUnmodifiedType());
5741}
5742
5743bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5744 return false;
5745}
5746
5747bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5748 const PackIndexingType *) {
5749 return false;
5750}
5751
5752bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5753 const UnaryTransformType*) {
5754 return false;
5755}
5756
5757bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5758 return Visit(T->getDeducedType());
5759}
5760
5761bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5763 return Visit(T->getDeducedType());
5764}
5765
5766bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5767 return VisitTagDecl(T->getDecl());
5768}
5769
5770bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5771 return VisitTagDecl(T->getDecl());
5772}
5773
5774bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5775 const TemplateTypeParmType*) {
5776 return false;
5777}
5778
5779bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5781 return false;
5782}
5783
5784bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5786 return false;
5787}
5788
5789bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5790 const InjectedClassNameType* T) {
5791 return VisitTagDecl(T->getDecl());
5792}
5793
5794bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5795 const DependentNameType* T) {
5796 return VisitNestedNameSpecifier(T->getQualifier());
5797}
5798
5799bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5801 if (auto *Q = T->getQualifier())
5802 return VisitNestedNameSpecifier(Q);
5803 return false;
5804}
5805
5806bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5807 const PackExpansionType* T) {
5808 return Visit(T->getPattern());
5809}
5810
5811bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5812 return false;
5813}
5814
5815bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5816 const ObjCInterfaceType *) {
5817 return false;
5818}
5819
5820bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5821 const ObjCObjectPointerType *) {
5822 return false;
5823}
5824
5825bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5826 return Visit(T->getValueType());
5827}
5828
5829bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5830 return false;
5831}
5832
5833bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
5834 return false;
5835}
5836
5837bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
5838 const ArrayParameterType *T) {
5839 return VisitConstantArrayType(T);
5840}
5841
5842bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
5843 const DependentBitIntType *T) {
5844 return false;
5845}
5846
5847bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5848 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5849 S.Diag(SR.getBegin(),
5850 S.getLangOpts().CPlusPlus11 ?
5851 diag::warn_cxx98_compat_template_arg_local_type :
5852 diag::ext_template_arg_local_type)
5853 << S.Context.getTypeDeclType(Tag) << SR;
5854 return true;
5855 }
5856
5857 if (!Tag->hasNameForLinkage()) {
5858 S.Diag(SR.getBegin(),
5859 S.getLangOpts().CPlusPlus11 ?
5860 diag::warn_cxx98_compat_template_arg_unnamed_type :
5861 diag::ext_template_arg_unnamed_type) << SR;
5862 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5863 return true;
5864 }
5865
5866 return false;
5867}
5868
5869bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5870 NestedNameSpecifier *NNS) {
5871 assert(NNS);
5872 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5873 return true;
5874
5875 switch (NNS->getKind()) {
5881 return false;
5882
5885 return Visit(QualType(NNS->getAsType(), 0));
5886 }
5887 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5888}
5889
5891 assert(ArgInfo && "invalid TypeSourceInfo");
5892 QualType Arg = ArgInfo->getType();
5893 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5894 QualType CanonArg = Context.getCanonicalType(Arg);
5895
5896 if (CanonArg->isVariablyModifiedType()) {
5897 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5899 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5900 }
5901
5902 // C++03 [temp.arg.type]p2:
5903 // A local type, a type with no linkage, an unnamed type or a type
5904 // compounded from any of these types shall not be used as a
5905 // template-argument for a template type-parameter.
5906 //
5907 // C++11 allows these, and even in C++03 we allow them as an extension with
5908 // a warning.
5909 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
5910 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5911 (void)Finder.Visit(CanonArg);
5912 }
5913
5914 return false;
5915}
5916
5920 NPV_Error
5922
5923/// Determine whether the given template argument is a null pointer
5924/// value of the appropriate type.
5927 QualType ParamType, Expr *Arg,
5928 Decl *Entity = nullptr) {
5929 if (Arg->isValueDependent() || Arg->isTypeDependent())
5930 return NPV_NotNullPointer;
5931
5932 // dllimport'd entities aren't constant but are available inside of template
5933 // arguments.
5934 if (Entity && Entity->hasAttr<DLLImportAttr>())
5935 return NPV_NotNullPointer;
5936
5937 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5938 llvm_unreachable(
5939 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5940
5941 if (!S.getLangOpts().CPlusPlus11)
5942 return NPV_NotNullPointer;
5943
5944 // Determine whether we have a constant expression.
5946 if (ArgRV.isInvalid())
5947 return NPV_Error;
5948 Arg = ArgRV.get();
5949
5950 Expr::EvalResult EvalResult;
5952 EvalResult.Diag = &Notes;
5953 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5954 EvalResult.HasSideEffects) {
5955 SourceLocation DiagLoc = Arg->getExprLoc();
5956
5957 // If our only note is the usual "invalid subexpression" note, just point
5958 // the caret at its location rather than producing an essentially
5959 // redundant note.
5960 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5961 diag::note_invalid_subexpr_in_const_expr) {
5962 DiagLoc = Notes[0].first;
5963 Notes.clear();
5964 }
5965
5966 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5967 << Arg->getType() << Arg->getSourceRange();
5968 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5969 S.Diag(Notes[I].first, Notes[I].second);
5970
5972 return NPV_Error;
5973 }
5974
5975 // C++11 [temp.arg.nontype]p1:
5976 // - an address constant expression of type std::nullptr_t
5977 if (Arg->getType()->isNullPtrType())
5978 return NPV_NullPointer;
5979
5980 // - a constant expression that evaluates to a null pointer value (4.10); or
5981 // - a constant expression that evaluates to a null member pointer value
5982 // (4.11); or
5983 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
5984 (EvalResult.Val.isMemberPointer() &&
5985 !EvalResult.Val.getMemberPointerDecl())) {
5986 // If our expression has an appropriate type, we've succeeded.
5987 bool ObjCLifetimeConversion;
5988 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5989 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5990 ObjCLifetimeConversion))
5991 return NPV_NullPointer;
5992
5993 // The types didn't match, but we know we got a null pointer; complain,
5994 // then recover as if the types were correct.
5995 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5996 << Arg->getType() << ParamType << Arg->getSourceRange();
5998 return NPV_NullPointer;
5999 }
6000
6001 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6002 // We found a pointer that isn't null, but doesn't refer to an object.
6003 // We could just return NPV_NotNullPointer, but we can print a better
6004 // message with the information we have here.
6005 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6006 << EvalResult.Val.getAsString(S.Context, ParamType);
6008 return NPV_Error;
6009 }
6010
6011 // If we don't have a null pointer value, but we do have a NULL pointer
6012 // constant, suggest a cast to the appropriate type.
6014 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6015 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6016 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6018 ")");
6020 return NPV_NullPointer;
6021 }
6022
6023 // FIXME: If we ever want to support general, address-constant expressions
6024 // as non-type template arguments, we should return the ExprResult here to
6025 // be interpreted by the caller.
6026 return NPV_NotNullPointer;
6027}
6028
6029/// Checks whether the given template argument is compatible with its
6030/// template parameter.
6032 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6033 Expr *Arg, QualType ArgType) {
6034 bool ObjCLifetimeConversion;
6035 if (ParamType->isPointerType() &&
6036 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6037 S.IsQualificationConversion(ArgType, ParamType, false,
6038 ObjCLifetimeConversion)) {
6039 // For pointer-to-object types, qualification conversions are
6040 // permitted.
6041 } else {
6042 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6043 if (!ParamRef->getPointeeType()->isFunctionType()) {
6044 // C++ [temp.arg.nontype]p5b3:
6045 // For a non-type template-parameter of type reference to
6046 // object, no conversions apply. The type referred to by the
6047 // reference may be more cv-qualified than the (otherwise
6048 // identical) type of the template- argument. The
6049 // template-parameter is bound directly to the
6050 // template-argument, which shall be an lvalue.
6051
6052 // FIXME: Other qualifiers?
6053 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6054 unsigned ArgQuals = ArgType.getCVRQualifiers();
6055
6056 if ((ParamQuals | ArgQuals) != ParamQuals) {
6057 S.Diag(Arg->getBeginLoc(),
6058 diag::err_template_arg_ref_bind_ignores_quals)
6059 << ParamType << Arg->getType() << Arg->getSourceRange();
6061 return true;
6062 }
6063 }
6064 }
6065
6066 // At this point, the template argument refers to an object or
6067 // function with external linkage. We now need to check whether the
6068 // argument and parameter types are compatible.
6069 if (!S.Context.hasSameUnqualifiedType(ArgType,
6070 ParamType.getNonReferenceType())) {
6071 // We can't perform this conversion or binding.
6072 if (ParamType->isReferenceType())
6073 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6074 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6075 else
6076 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6077 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6079 return true;
6080 }
6081 }
6082
6083 return false;
6084}
6085
6086/// Checks whether the given template argument is the address
6087/// of an object or function according to C++ [temp.arg.nontype]p1.
6089 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6090 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6091 bool Invalid = false;
6092 Expr *Arg = ArgIn;
6093 QualType ArgType = Arg->getType();
6094
6095 bool AddressTaken = false;
6096 SourceLocation AddrOpLoc;
6097 if (S.getLangOpts().MicrosoftExt) {
6098 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6099 // dereference and address-of operators.
6100 Arg = Arg->IgnoreParenCasts();
6101
6102 bool ExtWarnMSTemplateArg = false;
6103 UnaryOperatorKind FirstOpKind;
6104 SourceLocation FirstOpLoc;
6105 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6106 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6107 if (UnOpKind == UO_Deref)
6108 ExtWarnMSTemplateArg = true;
6109 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6110 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6111 if (!AddrOpLoc.isValid()) {
6112 FirstOpKind = UnOpKind;
6113 FirstOpLoc = UnOp->getOperatorLoc();
6114 }
6115 } else
6116 break;
6117 }
6118 if (FirstOpLoc.isValid()) {
6119 if (ExtWarnMSTemplateArg)
6120 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6121 << ArgIn->getSourceRange();
6122
6123 if (FirstOpKind == UO_AddrOf)
6124 AddressTaken = true;
6125 else if (Arg->getType()->isPointerType()) {
6126 // We cannot let pointers get dereferenced here, that is obviously not a
6127 // constant expression.
6128 assert(FirstOpKind == UO_Deref);
6129 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6130 << Arg->getSourceRange();
6131 }
6132 }
6133 } else {
6134 // See through any implicit casts we added to fix the type.
6135 Arg = Arg->IgnoreImpCasts();
6136
6137 // C++ [temp.arg.nontype]p1:
6138 //
6139 // A template-argument for a non-type, non-template
6140 // template-parameter shall be one of: [...]
6141 //
6142 // -- the address of an object or function with external
6143 // linkage, including function templates and function
6144 // template-ids but excluding non-static class members,
6145 // expressed as & id-expression where the & is optional if
6146 // the name refers to a function or array, or if the
6147 // corresponding template-parameter is a reference; or
6148
6149 // In C++98/03 mode, give an extension warning on any extra parentheses.
6150 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6151 bool ExtraParens = false;
6152 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6153 if (!Invalid && !ExtraParens) {
6154 S.Diag(Arg->getBeginLoc(),
6155 S.getLangOpts().CPlusPlus11
6156 ? diag::warn_cxx98_compat_template_arg_extra_parens
6157 : diag::ext_template_arg_extra_parens)
6158 << Arg->getSourceRange();
6159 ExtraParens = true;
6160 }
6161
6162 Arg = Parens->getSubExpr();
6163 }
6164
6165 while (SubstNonTypeTemplateParmExpr *subst =
6166 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6167 Arg = subst->getReplacement()->IgnoreImpCasts();
6168
6169 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6170 if (UnOp->getOpcode() == UO_AddrOf) {
6171 Arg = UnOp->getSubExpr();
6172 AddressTaken = true;
6173 AddrOpLoc = UnOp->getOperatorLoc();
6174 }
6175 }
6176
6177 while (SubstNonTypeTemplateParmExpr *subst =
6178 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6179 Arg = subst->getReplacement()->IgnoreImpCasts();
6180 }
6181
6182 ValueDecl *Entity = nullptr;
6183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6184 Entity = DRE->getDecl();
6185 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6186 Entity = CUE->getGuidDecl();
6187
6188 // If our parameter has pointer type, check for a null template value.
6189 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6190 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6191 Entity)) {
6192 case NPV_NullPointer:
6193 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6194 SugaredConverted = TemplateArgument(ParamType,
6195 /*isNullPtr=*/true);
6196 CanonicalConverted =
6198 /*isNullPtr=*/true);
6199 return false;
6200
6201 case NPV_Error:
6202 return true;
6203
6204 case NPV_NotNullPointer:
6205 break;
6206 }
6207 }
6208
6209 // Stop checking the precise nature of the argument if it is value dependent,
6210 // it should be checked when instantiated.
6211 if (Arg->isValueDependent()) {
6212 SugaredConverted = TemplateArgument(ArgIn);
6213 CanonicalConverted =
6214 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6215 return false;
6216 }
6217
6218 if (!Entity) {
6219 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6220 << Arg->getSourceRange();
6222 return true;
6223 }
6224
6225 // Cannot refer to non-static data members
6226 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6227 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6228 << Entity << Arg->getSourceRange();
6230 return true;
6231 }
6232
6233 // Cannot refer to non-static member functions
6234 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6235 if (!Method->isStatic()) {
6236 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6237 << Method << Arg->getSourceRange();
6239 return true;
6240 }
6241 }
6242
6243 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6244 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6245 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6246
6247 // A non-type template argument must refer to an object or function.
6248 if (!Func && !Var && !Guid) {
6249 // We found something, but we don't know specifically what it is.
6250 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6251 << Arg->getSourceRange();
6252 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6253 return true;
6254 }
6255
6256 // Address / reference template args must have external linkage in C++98.
6257 if (Entity->getFormalLinkage() == Linkage::Internal) {
6258 S.Diag(Arg->getBeginLoc(),
6259 S.getLangOpts().CPlusPlus11
6260 ? diag::warn_cxx98_compat_template_arg_object_internal
6261 : diag::ext_template_arg_object_internal)
6262 << !Func << Entity << Arg->getSourceRange();
6263 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6264 << !Func;
6265 } else if (!Entity->hasLinkage()) {
6266 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6267 << !Func << Entity << Arg->getSourceRange();
6268 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6269 << !Func;
6270 return true;
6271 }
6272
6273 if (Var) {
6274 // A value of reference type is not an object.
6275 if (Var->getType()->isReferenceType()) {
6276 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6277 << Var->getType() << Arg->getSourceRange();
6279 return true;
6280 }
6281
6282 // A template argument must have static storage duration.
6283 if (Var->getTLSKind()) {
6284 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6285 << Arg->getSourceRange();
6286 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6287 return true;
6288 }
6289 }
6290
6291 if (AddressTaken && ParamType->isReferenceType()) {
6292 // If we originally had an address-of operator, but the
6293 // parameter has reference type, complain and (if things look
6294 // like they will work) drop the address-of operator.
6295 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6296 ParamType.getNonReferenceType())) {
6297 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6298 << ParamType;
6300 return true;
6301 }
6302
6303 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6304 << ParamType
6305 << FixItHint::CreateRemoval(AddrOpLoc);
6307
6308 ArgType = Entity->getType();
6309 }
6310
6311 // If the template parameter has pointer type, either we must have taken the
6312 // address or the argument must decay to a pointer.
6313 if (!AddressTaken && ParamType->isPointerType()) {
6314 if (Func) {
6315 // Function-to-pointer decay.
6316 ArgType = S.Context.getPointerType(Func->getType());
6317 } else if (Entity->getType()->isArrayType()) {
6318 // Array-to-pointer decay.
6319 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6320 } else {
6321 // If the template parameter has pointer type but the address of
6322 // this object was not taken, complain and (possibly) recover by
6323 // taking the address of the entity.
6324 ArgType = S.Context.getPointerType(Entity->getType());
6325 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6326 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6327 << ParamType;
6329 return true;
6330 }
6331
6332 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6333 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6334
6336 }
6337 }
6338
6339 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6340 Arg, ArgType))
6341 return true;
6342
6343 // Create the template argument.
6344 SugaredConverted = TemplateArgument(Entity, ParamType);
6345 CanonicalConverted =
6346 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6347 S.Context.getCanonicalType(ParamType));
6348 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6349 return false;
6350}
6351
6352/// Checks whether the given template argument is a pointer to
6353/// member constant according to C++ [temp.arg.nontype]p1.
6354static bool
6356 QualType ParamType, Expr *&ResultArg,
6357 TemplateArgument &SugaredConverted,
6358 TemplateArgument &CanonicalConverted) {
6359 bool Invalid = false;
6360
6361 Expr *Arg = ResultArg;
6362 bool ObjCLifetimeConversion;
6363
6364 // C++ [temp.arg.nontype]p1:
6365 //
6366 // A template-argument for a non-type, non-template
6367 // template-parameter shall be one of: [...]
6368 //
6369 // -- a pointer to member expressed as described in 5.3.1.
6370 DeclRefExpr *DRE = nullptr;
6371
6372 // In C++98/03 mode, give an extension warning on any extra parentheses.
6373 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6374 bool ExtraParens = false;
6375 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6376 if (!Invalid && !ExtraParens) {
6377 S.Diag(Arg->getBeginLoc(),
6378 S.getLangOpts().CPlusPlus11
6379 ? diag::warn_cxx98_compat_template_arg_extra_parens
6380 : diag::ext_template_arg_extra_parens)
6381 << Arg->getSourceRange();
6382 ExtraParens = true;
6383 }
6384
6385 Arg = Parens->getSubExpr();
6386 }
6387
6388 while (SubstNonTypeTemplateParmExpr *subst =
6389 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6390 Arg = subst->getReplacement()->IgnoreImpCasts();
6391
6392 // A pointer-to-member constant written &Class::member.
6393 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6394 if (UnOp->getOpcode() == UO_AddrOf) {
6395 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6396 if (DRE && !DRE->getQualifier())
6397 DRE = nullptr;
6398 }
6399 }
6400 // A constant of pointer-to-member type.
6401 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6402 ValueDecl *VD = DRE->getDecl();
6403 if (VD->getType()->isMemberPointerType()) {
6404 if (isa<NonTypeTemplateParmDecl>(VD)) {
6405 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6406 SugaredConverted = TemplateArgument(Arg);
6407 CanonicalConverted =
6408 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6409 } else {
6410 SugaredConverted = TemplateArgument(VD, ParamType);
6411 CanonicalConverted =
6412 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6413 S.Context.getCanonicalType(ParamType));
6414 }
6415 return Invalid;
6416 }
6417 }
6418
6419 DRE = nullptr;
6420 }
6421
6422 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6423
6424 // Check for a null pointer value.
6425 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6426 Entity)) {
6427 case NPV_Error:
6428 return true;
6429 case NPV_NullPointer:
6430 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6431 SugaredConverted = TemplateArgument(ParamType,
6432 /*isNullPtr*/ true);
6433 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6434 /*isNullPtr*/ true);
6435 return false;
6436 case NPV_NotNullPointer:
6437 break;
6438 }
6439
6440 if (S.IsQualificationConversion(ResultArg->getType(),
6441 ParamType.getNonReferenceType(), false,
6442 ObjCLifetimeConversion)) {
6443 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6444 ResultArg->getValueKind())
6445 .get();
6446 } else if (!S.Context.hasSameUnqualifiedType(
6447 ResultArg->getType(), ParamType.getNonReferenceType())) {
6448 // We can't perform this conversion.
6449 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6450 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6452 return true;
6453 }
6454
6455 if (!DRE)
6456 return S.Diag(Arg->getBeginLoc(),
6457 diag::err_template_arg_not_pointer_to_member_form)
6458 << Arg->getSourceRange();
6459
6460 if (isa<FieldDecl>(DRE->getDecl()) ||
6461 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6462 isa<CXXMethodDecl>(DRE->getDecl())) {
6463 assert((isa<FieldDecl>(DRE->getDecl()) ||
6464 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6465 cast<CXXMethodDecl>(DRE->getDecl())
6466 ->isImplicitObjectMemberFunction()) &&
6467 "Only non-static member pointers can make it here");
6468
6469 // Okay: this is the address of a non-static member, and therefore
6470 // a member pointer constant.
6471 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6472 SugaredConverted = TemplateArgument(Arg);
6473 CanonicalConverted =
6474 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6475 } else {
6476 ValueDecl *D = DRE->getDecl();
6477 SugaredConverted = TemplateArgument(D, ParamType);
6478 CanonicalConverted =
6479 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6480 S.Context.getCanonicalType(ParamType));
6481 }
6482 return Invalid;
6483 }
6484
6485 // We found something else, but we don't know specifically what it is.
6486 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6487 << Arg->getSourceRange();
6488 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6489 return true;
6490}
6491
6493 QualType ParamType, Expr *Arg,
6494 TemplateArgument &SugaredConverted,
6495 TemplateArgument &CanonicalConverted,
6497 SourceLocation StartLoc = Arg->getBeginLoc();
6498
6499 // If the parameter type somehow involves auto, deduce the type now.
6500 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6501 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6502 // During template argument deduction, we allow 'decltype(auto)' to
6503 // match an arbitrary dependent argument.
6504 // FIXME: The language rules don't say what happens in this case.
6505 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6506 // expression is merely instantiation-dependent; is this enough?
6507 if (Arg->isTypeDependent()) {
6508 auto *AT = dyn_cast<AutoType>(DeducedT);
6509 if (AT && AT->isDecltypeAuto()) {
6510 SugaredConverted = TemplateArgument(Arg);
6511 CanonicalConverted = TemplateArgument(
6512 Context.getCanonicalTemplateArgument(SugaredConverted));
6513 return Arg;
6514 }
6515 }
6516
6517 // When checking a deduced template argument, deduce from its type even if
6518 // the type is dependent, in order to check the types of non-type template
6519 // arguments line up properly in partial ordering.
6520 Expr *DeductionArg = Arg;
6521 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6522 DeductionArg = PE->getPattern();
6523 TypeSourceInfo *TSI =
6524 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6525 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6526 InitializedEntity Entity =
6529 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6530 Expr *Inits[1] = {DeductionArg};
6531 ParamType =
6532 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6533 if (ParamType.isNull())
6534 return ExprError();
6535 } else {
6536 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6537 Param->getDepth() + 1);
6538 ParamType = QualType();
6540 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6541 /*DependentDeduction=*/true,
6542 // We do not check constraints right now because the
6543 // immediately-declared constraint of the auto type is
6544 // also an associated constraint, and will be checked
6545 // along with the other associated constraints after
6546 // checking the template argument list.
6547 /*IgnoreConstraints=*/true);
6549 if (ParamType.isNull())
6550 return ExprError();
6552 Diag(Arg->getExprLoc(),
6553 diag::err_non_type_template_parm_type_deduction_failure)
6554 << Param->getDeclName() << Param->getType() << Arg->getType()
6555 << Arg->getSourceRange();
6557 return ExprError();
6558 }
6559 }
6560 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6561 // an error. The error message normally references the parameter
6562 // declaration, but here we'll pass the argument location because that's
6563 // where the parameter type is deduced.
6564 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6565 if (ParamType.isNull()) {
6567 return ExprError();
6568 }
6569 }
6570
6571 // We should have already dropped all cv-qualifiers by now.
6572 assert(!ParamType.hasQualifiers() &&
6573 "non-type template parameter type cannot be qualified");
6574
6575 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6576 if (CTAK == CTAK_Deduced &&
6577 (ParamType->isReferenceType()
6579 Arg->getType())
6580 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6581 // FIXME: If either type is dependent, we skip the check. This isn't
6582 // correct, since during deduction we're supposed to have replaced each
6583 // template parameter with some unique (non-dependent) placeholder.
6584 // FIXME: If the argument type contains 'auto', we carry on and fail the
6585 // type check in order to force specific types to be more specialized than
6586 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6587 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6588 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6589 !Arg->getType()->getContainedDeducedType()) {
6590 SugaredConverted = TemplateArgument(Arg);
6591 CanonicalConverted = TemplateArgument(
6592 Context.getCanonicalTemplateArgument(SugaredConverted));
6593 return Arg;
6594 }
6595 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6596 // we should actually be checking the type of the template argument in P,
6597 // not the type of the template argument deduced from A, against the
6598 // template parameter type.
6599 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6600 << Arg->getType()
6601 << ParamType.getUnqualifiedType();
6603 return ExprError();
6604 }
6605
6606 // If either the parameter has a dependent type or the argument is
6607 // type-dependent, there's nothing we can check now.
6608 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6609 // Force the argument to the type of the parameter to maintain invariants.
6610 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6611 if (PE)
6612 Arg = PE->getPattern();
6614 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6615 ParamType->isLValueReferenceType() ? VK_LValue
6616 : ParamType->isRValueReferenceType() ? VK_XValue
6617 : VK_PRValue);
6618 if (E.isInvalid())
6619 return ExprError();
6620 if (PE) {
6621 // Recreate a pack expansion if we unwrapped one.
6622 E = new (Context)
6623 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6624 PE->getNumExpansions());
6625 }
6626 SugaredConverted = TemplateArgument(E.get());
6627 CanonicalConverted = TemplateArgument(
6628 Context.getCanonicalTemplateArgument(SugaredConverted));
6629 return E;
6630 }
6631
6632 QualType CanonParamType = Context.getCanonicalType(ParamType);
6633 // Avoid making a copy when initializing a template parameter of class type
6634 // from a template parameter object of the same type. This is going beyond
6635 // the standard, but is required for soundness: in
6636 // template<A a> struct X { X *p; X<a> *q; };
6637 // ... we need p and q to have the same type.
6638 //
6639 // Similarly, don't inject a call to a copy constructor when initializing
6640 // from a template parameter of the same type.
6641 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6642 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6643 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6644 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6645 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6646
6647 SugaredConverted = TemplateArgument(TPO, ParamType);
6648 CanonicalConverted =
6649 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6650 return Arg;
6651 }
6652 if (isa<NonTypeTemplateParmDecl>(ND)) {
6653 SugaredConverted = TemplateArgument(Arg);
6654 CanonicalConverted =
6655 Context.getCanonicalTemplateArgument(SugaredConverted);
6656 return Arg;
6657 }
6658 }
6659
6660 // The initialization of the parameter from the argument is
6661 // a constant-evaluated context.
6664
6665 bool IsConvertedConstantExpression = true;
6666 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6668 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6669 Expr *Inits[1] = {Arg};
6670 InitializedEntity Entity =
6672 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6673 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6674 if (Result.isInvalid() || !Result.get())
6675 return ExprError();
6677 if (Result.isInvalid() || !Result.get())
6678 return ExprError();
6679 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6680 /*DiscardedValue=*/false,
6681 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6682 .get();
6683 IsConvertedConstantExpression = false;
6684 }
6685
6686 if (getLangOpts().CPlusPlus17) {
6687 // C++17 [temp.arg.nontype]p1:
6688 // A template-argument for a non-type template parameter shall be
6689 // a converted constant expression of the type of the template-parameter.
6690 APValue Value;
6691 ExprResult ArgResult;
6692 if (IsConvertedConstantExpression) {
6693 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6694 CCEK_TemplateArg, Param);
6695 if (ArgResult.isInvalid())
6696 return ExprError();
6697 } else {
6698 ArgResult = Arg;
6699 }
6700
6701 // For a value-dependent argument, CheckConvertedConstantExpression is
6702 // permitted (and expected) to be unable to determine a value.
6703 if (ArgResult.get()->isValueDependent()) {
6704 SugaredConverted = TemplateArgument(ArgResult.get());
6705 CanonicalConverted =
6706 Context.getCanonicalTemplateArgument(SugaredConverted);
6707 return ArgResult;
6708 }
6709
6710 APValue PreNarrowingValue;
6712 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6713 false, PreNarrowingValue);
6714 if (ArgResult.isInvalid())
6715 return ExprError();
6716
6717 if (Value.isLValue()) {
6718 APValue::LValueBase Base = Value.getLValueBase();
6719 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6720 // For a non-type template-parameter of pointer or reference type,
6721 // the value of the constant expression shall not refer to
6722 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6723 ParamType->isNullPtrType());
6724 // -- a temporary object
6725 // -- a string literal
6726 // -- the result of a typeid expression, or
6727 // -- a predefined __func__ variable
6728 if (Base &&
6729 (!VD ||
6730 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6731 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6732 << Arg->getSourceRange();
6733 return ExprError();
6734 }
6735
6736 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6737 VD->getType()->isArrayType() &&
6738 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6739 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6740 SugaredConverted = TemplateArgument(VD, ParamType);
6741 CanonicalConverted = TemplateArgument(
6742 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6743 return ArgResult.get();
6744 }
6745
6746 // -- a subobject [until C++20]
6747 if (!getLangOpts().CPlusPlus20) {
6748 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6749 Value.isLValueOnePastTheEnd()) {
6750 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6751 << Value.getAsString(Context, ParamType);
6752 return ExprError();
6753 }
6754 assert((VD || !ParamType->isReferenceType()) &&
6755 "null reference should not be a constant expression");
6756 assert((!VD || !ParamType->isNullPtrType()) &&
6757 "non-null value of type nullptr_t?");
6758 }
6759 }
6760
6761 if (Value.isAddrLabelDiff())
6762 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6763
6764 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6765 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6766 return ArgResult.get();
6767 }
6768
6769 // C++ [temp.arg.nontype]p5:
6770 // The following conversions are performed on each expression used
6771 // as a non-type template-argument. If a non-type
6772 // template-argument cannot be converted to the type of the
6773 // corresponding template-parameter then the program is
6774 // ill-formed.
6775 if (ParamType->isIntegralOrEnumerationType()) {
6776 // C++11:
6777 // -- for a non-type template-parameter of integral or
6778 // enumeration type, conversions permitted in a converted
6779 // constant expression are applied.
6780 //
6781 // C++98:
6782 // -- for a non-type template-parameter of integral or
6783 // enumeration type, integral promotions (4.5) and integral
6784 // conversions (4.7) are applied.
6785
6786 if (getLangOpts().CPlusPlus11) {
6787 // C++ [temp.arg.nontype]p1:
6788 // A template-argument for a non-type, non-template template-parameter
6789 // shall be one of:
6790 //
6791 // -- for a non-type template-parameter of integral or enumeration
6792 // type, a converted constant expression of the type of the
6793 // template-parameter; or
6794 llvm::APSInt Value;
6795 ExprResult ArgResult =
6798 if (ArgResult.isInvalid())
6799 return ExprError();
6800
6801 // We can't check arbitrary value-dependent arguments.
6802 if (ArgResult.get()->isValueDependent()) {
6803 SugaredConverted = TemplateArgument(ArgResult.get());
6804 CanonicalConverted =
6805 Context.getCanonicalTemplateArgument(SugaredConverted);
6806 return ArgResult;
6807 }
6808
6809 // Widen the argument value to sizeof(parameter type). This is almost
6810 // always a no-op, except when the parameter type is bool. In
6811 // that case, this may extend the argument from 1 bit to 8 bits.
6812 QualType IntegerType = ParamType;
6813 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6814 IntegerType = Enum->getDecl()->getIntegerType();
6815 Value = Value.extOrTrunc(IntegerType->isBitIntType()
6816 ? Context.getIntWidth(IntegerType)
6817 : Context.getTypeSize(IntegerType));
6818
6819 SugaredConverted = TemplateArgument(Context, Value, ParamType);
6820 CanonicalConverted =
6822 return ArgResult;
6823 }
6824
6825 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6826 if (ArgResult.isInvalid())
6827 return ExprError();
6828 Arg = ArgResult.get();
6829
6830 QualType ArgType = Arg->getType();
6831
6832 // C++ [temp.arg.nontype]p1:
6833 // A template-argument for a non-type, non-template
6834 // template-parameter shall be one of:
6835 //
6836 // -- an integral constant-expression of integral or enumeration
6837 // type; or
6838 // -- the name of a non-type template-parameter; or
6839 llvm::APSInt Value;
6840 if (!ArgType->isIntegralOrEnumerationType()) {
6841 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6842 << ArgType << Arg->getSourceRange();
6844 return ExprError();
6845 } else if (!Arg->isValueDependent()) {
6846 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6847 QualType T;
6848
6849 public:
6850 TmplArgICEDiagnoser(QualType T) : T(T) { }
6851
6852 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
6853 SourceLocation Loc) override {
6854 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
6855 }
6856 } Diagnoser(ArgType);
6857
6858 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
6859 if (!Arg)
6860 return ExprError();
6861 }
6862
6863 // From here on out, all we care about is the unqualified form
6864 // of the argument type.
6865 ArgType = ArgType.getUnqualifiedType();
6866
6867 // Try to convert the argument to the parameter's type.
6868 if (Context.hasSameType(ParamType, ArgType)) {
6869 // Okay: no conversion necessary
6870 } else if (ParamType->isBooleanType()) {
6871 // This is an integral-to-boolean conversion.
6872 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6873 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6874 !ParamType->isEnumeralType()) {
6875 // This is an integral promotion or conversion.
6876 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6877 } else {
6878 // We can't perform this conversion.
6879 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6880 << Arg->getType() << ParamType << Arg->getSourceRange();
6882 return ExprError();
6883 }
6884
6885 // Add the value of this argument to the list of converted
6886 // arguments. We use the bitwidth and signedness of the template
6887 // parameter.
6888 if (Arg->isValueDependent()) {
6889 // The argument is value-dependent. Create a new
6890 // TemplateArgument with the converted expression.
6891 SugaredConverted = TemplateArgument(Arg);
6892 CanonicalConverted =
6893 Context.getCanonicalTemplateArgument(SugaredConverted);
6894 return Arg;
6895 }
6896
6897 QualType IntegerType = ParamType;
6898 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
6899 IntegerType = Enum->getDecl()->getIntegerType();
6900 }
6901
6902 if (ParamType->isBooleanType()) {
6903 // Value must be zero or one.
6904 Value = Value != 0;
6905 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6906 if (Value.getBitWidth() != AllowedBits)
6907 Value = Value.extOrTrunc(AllowedBits);
6908 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6909 } else {
6910 llvm::APSInt OldValue = Value;
6911
6912 // Coerce the template argument's value to the value it will have
6913 // based on the template parameter's type.
6914 unsigned AllowedBits = IntegerType->isBitIntType()
6915 ? Context.getIntWidth(IntegerType)
6916 : Context.getTypeSize(IntegerType);
6917 if (Value.getBitWidth() != AllowedBits)
6918 Value = Value.extOrTrunc(AllowedBits);
6919 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6920
6921 // Complain if an unsigned parameter received a negative value.
6922 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
6923 (OldValue.isSigned() && OldValue.isNegative())) {
6924 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6925 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6926 << Arg->getSourceRange();
6928 }
6929
6930 // Complain if we overflowed the template parameter's type.
6931 unsigned RequiredBits;
6932 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6933 RequiredBits = OldValue.getActiveBits();
6934 else if (OldValue.isUnsigned())
6935 RequiredBits = OldValue.getActiveBits() + 1;
6936 else
6937 RequiredBits = OldValue.getSignificantBits();
6938 if (RequiredBits > AllowedBits) {
6939 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6940 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6941 << Arg->getSourceRange();
6943 }
6944 }
6945
6946 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
6947 SugaredConverted = TemplateArgument(Context, Value, T);
6948 CanonicalConverted =
6950 return Arg;
6951 }
6952
6953 QualType ArgType = Arg->getType();
6954 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6955
6956 // Handle pointer-to-function, reference-to-function, and
6957 // pointer-to-member-function all in (roughly) the same way.
6958 if (// -- For a non-type template-parameter of type pointer to
6959 // function, only the function-to-pointer conversion (4.3) is
6960 // applied. If the template-argument represents a set of
6961 // overloaded functions (or a pointer to such), the matching
6962 // function is selected from the set (13.4).
6963 (ParamType->isPointerType() &&
6964 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6965 // -- For a non-type template-parameter of type reference to
6966 // function, no conversions apply. If the template-argument
6967 // represents a set of overloaded functions, the matching
6968 // function is selected from the set (13.4).
6969 (ParamType->isReferenceType() &&
6970 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6971 // -- For a non-type template-parameter of type pointer to
6972 // member function, no conversions apply. If the
6973 // template-argument represents a set of overloaded member
6974 // functions, the matching member function is selected from
6975 // the set (13.4).
6976 (ParamType->isMemberPointerType() &&
6977 ParamType->castAs<MemberPointerType>()->getPointeeType()
6978 ->isFunctionType())) {
6979
6980 if (Arg->getType() == Context.OverloadTy) {
6981 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6982 true,
6983 FoundResult)) {
6984 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6985 return ExprError();
6986
6987 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6988 if (Res.isInvalid())
6989 return ExprError();
6990 Arg = Res.get();
6991 ArgType = Arg->getType();
6992 } else
6993 return ExprError();
6994 }
6995
6996 if (!ParamType->isMemberPointerType()) {
6998 *this, Param, ParamType, Arg, SugaredConverted,
6999 CanonicalConverted))
7000 return ExprError();
7001 return Arg;
7002 }
7003
7005 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7006 return ExprError();
7007 return Arg;
7008 }
7009
7010 if (ParamType->isPointerType()) {
7011 // -- for a non-type template-parameter of type pointer to
7012 // object, qualification conversions (4.4) and the
7013 // array-to-pointer conversion (4.2) are applied.
7014 // C++0x also allows a value of std::nullptr_t.
7015 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7016 "Only object pointers allowed here");
7017
7019 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7020 return ExprError();
7021 return Arg;
7022 }
7023
7024 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7025 // -- For a non-type template-parameter of type reference to
7026 // object, no conversions apply. The type referred to by the
7027 // reference may be more cv-qualified than the (otherwise
7028 // identical) type of the template-argument. The
7029 // template-parameter is bound directly to the
7030 // template-argument, which must be an lvalue.
7031 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7032 "Only object references allowed here");
7033
7034 if (Arg->getType() == Context.OverloadTy) {
7036 ParamRefType->getPointeeType(),
7037 true,
7038 FoundResult)) {
7039 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7040 return ExprError();
7041 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7042 if (Res.isInvalid())
7043 return ExprError();
7044 Arg = Res.get();
7045 ArgType = Arg->getType();
7046 } else
7047 return ExprError();
7048 }
7049
7051 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7052 return ExprError();
7053 return Arg;
7054 }
7055
7056 // Deal with parameters of type std::nullptr_t.
7057 if (ParamType->isNullPtrType()) {
7058 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7059 SugaredConverted = TemplateArgument(Arg);
7060 CanonicalConverted =
7061 Context.getCanonicalTemplateArgument(SugaredConverted);
7062 return Arg;
7063 }
7064
7065 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7066 case NPV_NotNullPointer:
7067 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7068 << Arg->getType() << ParamType;
7070 return ExprError();
7071
7072 case NPV_Error:
7073 return ExprError();
7074
7075 case NPV_NullPointer:
7076 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7077 SugaredConverted = TemplateArgument(ParamType,
7078 /*isNullPtr=*/true);
7079 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7080 /*isNullPtr=*/true);
7081 return Arg;
7082 }
7083 }
7084
7085 // -- For a non-type template-parameter of type pointer to data
7086 // member, qualification conversions (4.4) are applied.
7087 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7088
7090 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7091 return ExprError();
7092 return Arg;
7093}
7094
7098
7100 TemplateParameterList *Params,
7102 bool IsDeduced) {
7104 TemplateDecl *Template = Name.getAsTemplateDecl();
7105 if (!Template) {
7106 // Any dependent template name is fine.
7107 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7108 return false;
7109 }
7110
7111 if (Template->isInvalidDecl())
7112 return true;
7113
7114 // C++0x [temp.arg.template]p1:
7115 // A template-argument for a template template-parameter shall be
7116 // the name of a class template or an alias template, expressed as an
7117 // id-expression. When the template-argument names a class template, only
7118 // primary class templates are considered when matching the
7119 // template template argument with the corresponding parameter;
7120 // partial specializations are not considered even if their
7121 // parameter lists match that of the template template parameter.
7122 //
7123 // Note that we also allow template template parameters here, which
7124 // will happen when we are dealing with, e.g., class template
7125 // partial specializations.
7126 if (!isa<ClassTemplateDecl>(Template) &&
7127 !isa<TemplateTemplateParmDecl>(Template) &&
7128 !isa<TypeAliasTemplateDecl>(Template) &&
7129 !isa<BuiltinTemplateDecl>(Template)) {
7130 assert(isa<FunctionTemplateDecl>(Template) &&
7131 "Only function templates are possible here");
7132 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7133 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7134 << Template;
7135 }
7136
7137 // C++1z [temp.arg.template]p3: (DR 150)
7138 // A template-argument matches a template template-parameter P when P
7139 // is at least as specialized as the template-argument A.
7140 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7141 // Quick check for the common case:
7142 // If P contains a parameter pack, then A [...] matches P if each of A's
7143 // template parameters matches the corresponding template parameter in
7144 // the template-parameter-list of P.
7146 Template->getTemplateParameters(), Params, false,
7148 // If the argument has no associated constraints, then the parameter is
7149 // definitely at least as specialized as the argument.
7150 // Otherwise - we need a more thorough check.
7151 !Template->hasAssociatedConstraints())
7152 return false;
7153
7155 Params, Template, Arg.getLocation(), IsDeduced)) {
7156 // P2113
7157 // C++20[temp.func.order]p2
7158 // [...] If both deductions succeed, the partial ordering selects the
7159 // more constrained template (if one exists) as determined below.
7160 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7161 Params->getAssociatedConstraints(ParamsAC);
7162 // C++2a[temp.arg.template]p3
7163 // [...] In this comparison, if P is unconstrained, the constraints on A
7164 // are not considered.
7165 if (ParamsAC.empty())
7166 return false;
7167
7168 Template->getAssociatedConstraints(TemplateAC);
7169
7170 bool IsParamAtLeastAsConstrained;
7171 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7172 IsParamAtLeastAsConstrained))
7173 return true;
7174 if (!IsParamAtLeastAsConstrained) {
7175 Diag(Arg.getLocation(),
7176 diag::err_template_template_parameter_not_at_least_as_constrained)
7177 << Template << Param << Arg.getSourceRange();
7178 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7179 Diag(Template->getLocation(), diag::note_entity_declared_at)
7180 << Template;
7181 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7182 TemplateAC);
7183 return true;
7184 }
7185 return false;
7186 }
7187 // FIXME: Produce better diagnostics for deduction failures.
7188 }
7189
7191 Params,
7192 true,
7194 Arg.getLocation());
7195}
7196
7198 unsigned HereDiagID,
7199 unsigned ExternalDiagID) {
7200 if (Decl.getLocation().isValid())
7201 return S.Diag(Decl.getLocation(), HereDiagID);
7202
7203 SmallString<128> Str;
7204 llvm::raw_svector_ostream Out(Str);
7206 PP.TerseOutput = 1;
7207 Decl.print(Out, PP);
7208 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7209}
7210
7212 std::optional<SourceRange> ParamRange) {
7214 noteLocation(*this, Decl, diag::note_template_decl_here,
7215 diag::note_template_decl_external);
7216 if (ParamRange && ParamRange->isValid()) {
7217 assert(Decl.getLocation().isValid() &&
7218 "Parameter range has location when Decl does not");
7219 DB << *ParamRange;
7220 }
7221}
7222
7224 noteLocation(*this, Decl, diag::note_template_param_here,
7225 diag::note_template_param_external);
7226}
7227
7229 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7231 // C++ [temp.param]p8:
7232 //
7233 // A non-type template-parameter of type "array of T" or
7234 // "function returning T" is adjusted to be of type "pointer to
7235 // T" or "pointer to function returning T", respectively.
7236 if (ParamType->isArrayType())
7237 ParamType = Context.getArrayDecayedType(ParamType);
7238 else if (ParamType->isFunctionType())
7239 ParamType = Context.getPointerType(ParamType);
7240
7241 // For a NULL non-type template argument, return nullptr casted to the
7242 // parameter's type.
7243 if (Arg.getKind() == TemplateArgument::NullPtr) {
7244 return ImpCastExprToType(
7246 ParamType,
7247 ParamType->getAs<MemberPointerType>()
7248 ? CK_NullToMemberPointer
7249 : CK_NullToPointer);
7250 }
7251 assert(Arg.getKind() == TemplateArgument::Declaration &&
7252 "Only declaration template arguments permitted here");
7253
7254 ValueDecl *VD = Arg.getAsDecl();
7255
7256 CXXScopeSpec SS;
7257 if (ParamType->isMemberPointerType()) {
7258 // If this is a pointer to member, we need to use a qualified name to
7259 // form a suitable pointer-to-member constant.
7260 assert(VD->getDeclContext()->isRecord() &&
7261 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7262 isa<IndirectFieldDecl>(VD)));
7263 QualType ClassType
7264 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7265 NestedNameSpecifier *Qualifier
7266 = NestedNameSpecifier::Create(Context, nullptr, false,
7267 ClassType.getTypePtr());
7268 SS.MakeTrivial(Context, Qualifier, Loc);
7269 }
7270
7272 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7273 if (RefExpr.isInvalid())
7274 return ExprError();
7275
7276 // For a pointer, the argument declaration is the pointee. Take its address.
7277 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7278 if (ParamType->isPointerType() && !ElemT.isNull() &&
7279 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7280 // Decay an array argument if we want a pointer to its first element.
7281 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7282 if (RefExpr.isInvalid())
7283 return ExprError();
7284 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7285 // For any other pointer, take the address (or form a pointer-to-member).
7286 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7287 if (RefExpr.isInvalid())
7288 return ExprError();
7289 } else if (ParamType->isRecordType()) {
7290 assert(isa<TemplateParamObjectDecl>(VD) &&
7291 "arg for class template param not a template parameter object");
7292 // No conversions apply in this case.
7293 return RefExpr;
7294 } else {
7295 assert(ParamType->isReferenceType() &&
7296 "unexpected type for decl template argument");
7297 if (NonTypeTemplateParmDecl *NTTP =
7298 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7299 QualType TemplateParamType = NTTP->getType();
7300 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7301 if (AT && AT->isDecltypeAuto()) {
7303 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7304 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7305 /*PackIndex=*/std::nullopt,
7306 /*RefParam=*/true);
7307 }
7308 }
7309 }
7310
7311 // At this point we should have the right value category.
7312 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7313 "value kind mismatch for non-type template argument");
7314
7315 // The type of the template parameter can differ from the type of the
7316 // argument in various ways; convert it now if necessary.
7317 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7318 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7319 CastKind CK;
7320 QualType Ignored;
7321 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7322 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7323 CK = CK_NoOp;
7324 } else if (ParamType->isVoidPointerType() &&
7325 RefExpr.get()->getType()->isPointerType()) {
7326 CK = CK_BitCast;
7327 } else {
7328 // FIXME: Pointers to members can need conversion derived-to-base or
7329 // base-to-derived conversions. We currently don't retain enough
7330 // information to convert properly (we need to track a cast path or
7331 // subobject number in the template argument).
7332 llvm_unreachable(
7333 "unexpected conversion required for non-type template argument");
7334 }
7335 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7336 RefExpr.get()->getValueKind());
7337 }
7338
7339 return RefExpr;
7340}
7341
7342/// Construct a new expression that refers to the given
7343/// integral template argument with the given source-location
7344/// information.
7345///
7346/// This routine takes care of the mapping from an integral template
7347/// argument (which may have any integral type) to the appropriate
7348/// literal value.
7350 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7351 assert(OrigT->isIntegralOrEnumerationType());
7352
7353 // If this is an enum type that we're instantiating, we need to use an integer
7354 // type the same size as the enumerator. We don't want to build an
7355 // IntegerLiteral with enum type. The integer type of an enum type can be of
7356 // any integral type with C++11 enum classes, make sure we create the right
7357 // type of literal for it.
7358 QualType T = OrigT;
7359 if (const EnumType *ET = OrigT->getAs<EnumType>())
7360 T = ET->getDecl()->getIntegerType();
7361
7362 Expr *E;
7363 if (T->isAnyCharacterType()) {
7365 if (T->isWideCharType())
7367 else if (T->isChar8Type() && S.getLangOpts().Char8)
7369 else if (T->isChar16Type())
7371 else if (T->isChar32Type())
7373 else
7375
7376 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7377 } else if (T->isBooleanType()) {
7378 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7379 } else {
7380 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7381 }
7382
7383 if (OrigT->isEnumeralType()) {
7384 // FIXME: This is a hack. We need a better way to handle substituted
7385 // non-type template parameters.
7386 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7387 nullptr, S.CurFPFeatureOverrides(),
7389 Loc, Loc);
7390 }
7391
7392 return E;
7393}
7394
7396 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7397 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7398 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7399 ILE->setType(T);
7400 return ILE;
7401 };
7402
7403 switch (Val.getKind()) {
7405 // This cannot occur in a template argument at all.
7406 case APValue::Array:
7407 case APValue::Struct:
7408 case APValue::Union:
7409 // These can only occur within a template parameter object, which is
7410 // represented as a TemplateArgument::Declaration.
7411 llvm_unreachable("unexpected template argument value");
7412
7413 case APValue::Int:
7415 Loc);
7416
7417 case APValue::Float:
7418 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7419 T, Loc);
7420
7423 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7424 Val.getFixedPoint().getScale());
7425
7426 case APValue::ComplexInt: {
7427 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7429 S, ElemT, Val.getComplexIntReal(), Loc),
7431 S, ElemT, Val.getComplexIntImag(), Loc)});
7432 }
7433
7434 case APValue::ComplexFloat: {
7435 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7436 return MakeInitList(
7438 ElemT, Loc),
7440 ElemT, Loc)});
7441 }
7442
7443 case APValue::Vector: {
7444 QualType ElemT = T->castAs<VectorType>()->getElementType();
7446 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7448 S, ElemT, Val.getVectorElt(I), Loc));
7449 return MakeInitList(Elts);
7450 }
7451
7452 case APValue::None:
7454 llvm_unreachable("Unexpected APValue kind.");
7455 case APValue::LValue:
7457 // There isn't necessarily a valid equivalent source-level syntax for
7458 // these; in particular, a naive lowering might violate access control.
7459 // So for now we lower to a ConstantExpr holding the value, wrapped around
7460 // an OpaqueValueExpr.
7461 // FIXME: We should have a better representation for this.
7463 if (T->isReferenceType()) {
7464 T = T->getPointeeType();
7465 VK = VK_LValue;
7466 }
7467 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7468 return ConstantExpr::Create(S.Context, OVE, Val);
7469 }
7470 llvm_unreachable("Unhandled APValue::ValueKind enum");
7471}
7472
7476 switch (Arg.getKind()) {
7482 llvm_unreachable("not a non-type template argument");
7483
7485 return Arg.getAsExpr();
7486
7491
7494 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7495
7498 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7499 }
7500 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7501}
7502
7503/// Match two template parameters within template parameter lists.
7505 Sema &S, NamedDecl *New,
7506 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7507 const NamedDecl *OldInstFrom, bool Complain,
7509 // Check the actual kind (type, non-type, template).
7510 if (Old->getKind() != New->getKind()) {
7511 if (Complain) {
7512 unsigned NextDiag = diag::err_template_param_different_kind;
7513 if (TemplateArgLoc.isValid()) {
7514 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7515 NextDiag = diag::note_template_param_different_kind;
7516 }
7517 S.Diag(New->getLocation(), NextDiag)
7518 << (Kind != Sema::TPL_TemplateMatch);
7519 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7520 << (Kind != Sema::TPL_TemplateMatch);
7521 }
7522
7523 return false;
7524 }
7525
7526 // Check that both are parameter packs or neither are parameter packs.
7527 // However, if we are matching a template template argument to a
7528 // template template parameter, the template template parameter can have
7529 // a parameter pack where the template template argument does not.
7530 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7532 Old->isTemplateParameterPack())) {
7533 if (Complain) {
7534 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7535 if (TemplateArgLoc.isValid()) {
7536 S.Diag(TemplateArgLoc,
7537 diag::err_template_arg_template_params_mismatch);
7538 NextDiag = diag::note_template_parameter_pack_non_pack;
7539 }
7540
7541 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7542 : isa<NonTypeTemplateParmDecl>(New)? 1
7543 : 2;
7544 S.Diag(New->getLocation(), NextDiag)
7545 << ParamKind << New->isParameterPack();
7546 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7547 << ParamKind << Old->isParameterPack();
7548 }
7549
7550 return false;
7551 }
7552
7553 // For non-type template parameters, check the type of the parameter.
7554 if (NonTypeTemplateParmDecl *OldNTTP
7555 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7556 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7557
7558 // If we are matching a template template argument to a template
7559 // template parameter and one of the non-type template parameter types
7560 // is dependent, then we must wait until template instantiation time
7561 // to actually compare the arguments.
7563 (!OldNTTP->getType()->isDependentType() &&
7564 !NewNTTP->getType()->isDependentType())) {
7565 // C++20 [temp.over.link]p6:
7566 // Two [non-type] template-parameters are equivalent [if] they have
7567 // equivalent types ignoring the use of type-constraints for
7568 // placeholder types
7569 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7570 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7571 if (!S.Context.hasSameType(OldType, NewType)) {
7572 if (Complain) {
7573 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7574 if (TemplateArgLoc.isValid()) {
7575 S.Diag(TemplateArgLoc,
7576 diag::err_template_arg_template_params_mismatch);
7577 NextDiag = diag::note_template_nontype_parm_different_type;
7578 }
7579 S.Diag(NewNTTP->getLocation(), NextDiag)
7580 << NewNTTP->getType()
7581 << (Kind != Sema::TPL_TemplateMatch);
7582 S.Diag(OldNTTP->getLocation(),
7583 diag::note_template_nontype_parm_prev_declaration)
7584 << OldNTTP->getType();
7585 }
7586
7587 return false;
7588 }
7589 }
7590 }
7591 // For template template parameters, check the template parameter types.
7592 // The template parameter lists of template template
7593 // parameters must agree.
7594 else if (TemplateTemplateParmDecl *OldTTP =
7595 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7596 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7598 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7599 OldTTP->getTemplateParameters(), Complain,
7602 : Kind),
7603 TemplateArgLoc))
7604 return false;
7605 }
7606
7609 !isa<TemplateTemplateParmDecl>(Old)) {
7610 const Expr *NewC = nullptr, *OldC = nullptr;
7611
7612 if (isa<TemplateTypeParmDecl>(New)) {
7613 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7614 NewC = TC->getImmediatelyDeclaredConstraint();
7615 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7616 OldC = TC->getImmediatelyDeclaredConstraint();
7617 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7618 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7619 ->getPlaceholderTypeConstraint())
7620 NewC = E;
7621 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7622 ->getPlaceholderTypeConstraint())
7623 OldC = E;
7624 } else
7625 llvm_unreachable("unexpected template parameter type");
7626
7627 auto Diagnose = [&] {
7628 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7629 diag::err_template_different_type_constraint);
7630 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7631 diag::note_template_prev_declaration) << /*declaration*/0;
7632 };
7633
7634 if (!NewC != !OldC) {
7635 if (Complain)
7636 Diagnose();
7637 return false;
7638 }
7639
7640 if (NewC) {
7641 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7642 NewC)) {
7643 if (Complain)
7644 Diagnose();
7645 return false;
7646 }
7647 }
7648 }
7649
7650 return true;
7651}
7652
7653/// Diagnose a known arity mismatch when comparing template argument
7654/// lists.
7655static
7660 SourceLocation TemplateArgLoc) {
7661 unsigned NextDiag = diag::err_template_param_list_different_arity;
7662 if (TemplateArgLoc.isValid()) {
7663 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7664 NextDiag = diag::note_template_param_list_different_arity;
7665 }
7666 S.Diag(New->getTemplateLoc(), NextDiag)
7667 << (New->size() > Old->size())
7668 << (Kind != Sema::TPL_TemplateMatch)
7669 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7670 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7671 << (Kind != Sema::TPL_TemplateMatch)
7672 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7673}
7674
7676 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7677 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7678 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7679 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7680 if (Complain)
7681 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7682 TemplateArgLoc);
7683
7684 return false;
7685 }
7686
7687 // C++0x [temp.arg.template]p3:
7688 // A template-argument matches a template template-parameter (call it P)
7689 // when each of the template parameters in the template-parameter-list of
7690 // the template-argument's corresponding class template or alias template
7691 // (call it A) matches the corresponding template parameter in the
7692 // template-parameter-list of P. [...]
7693 TemplateParameterList::iterator NewParm = New->begin();
7694 TemplateParameterList::iterator NewParmEnd = New->end();
7695 for (TemplateParameterList::iterator OldParm = Old->begin(),
7696 OldParmEnd = Old->end();
7697 OldParm != OldParmEnd; ++OldParm) {
7699 !(*OldParm)->isTemplateParameterPack()) {
7700 if (NewParm == NewParmEnd) {
7701 if (Complain)
7702 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7703 TemplateArgLoc);
7704
7705 return false;
7706 }
7707
7708 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7709 OldInstFrom, Complain, Kind,
7710 TemplateArgLoc))
7711 return false;
7712
7713 ++NewParm;
7714 continue;
7715 }
7716
7717 // C++0x [temp.arg.template]p3:
7718 // [...] When P's template- parameter-list contains a template parameter
7719 // pack (14.5.3), the template parameter pack will match zero or more
7720 // template parameters or template parameter packs in the
7721 // template-parameter-list of A with the same type and form as the
7722 // template parameter pack in P (ignoring whether those template
7723 // parameters are template parameter packs).
7724 for (; NewParm != NewParmEnd; ++NewParm) {
7725 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7726 OldInstFrom, Complain, Kind,
7727 TemplateArgLoc))
7728 return false;
7729 }
7730 }
7731
7732 // Make sure we exhausted all of the arguments.
7733 if (NewParm != NewParmEnd) {
7734 if (Complain)
7735 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7736 TemplateArgLoc);
7737
7738 return false;
7739 }
7740
7743 const Expr *NewRC = New->getRequiresClause();
7744 const Expr *OldRC = Old->getRequiresClause();
7745
7746 auto Diagnose = [&] {
7747 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7748 diag::err_template_different_requires_clause);
7749 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7750 diag::note_template_prev_declaration) << /*declaration*/0;
7751 };
7752
7753 if (!NewRC != !OldRC) {
7754 if (Complain)
7755 Diagnose();
7756 return false;
7757 }
7758
7759 if (NewRC) {
7760 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7761 NewRC)) {
7762 if (Complain)
7763 Diagnose();
7764 return false;
7765 }
7766 }
7767 }
7768
7769 return true;
7770}
7771
7772bool
7774 if (!S)
7775 return false;
7776
7777 // Find the nearest enclosing declaration scope.
7778 S = S->getDeclParent();
7779
7780 // C++ [temp.pre]p6: [P2096]
7781 // A template, explicit specialization, or partial specialization shall not
7782 // have C linkage.
7783 DeclContext *Ctx = S->getEntity();
7784 if (Ctx && Ctx->isExternCContext()) {
7785 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7786 << TemplateParams->getSourceRange();
7787 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7788 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7789 return true;
7790 }
7791 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
7792
7793 // C++ [temp]p2:
7794 // A template-declaration can appear only as a namespace scope or
7795 // class scope declaration.
7796 // C++ [temp.expl.spec]p3:
7797 // An explicit specialization may be declared in any scope in which the
7798 // corresponding primary template may be defined.
7799 // C++ [temp.class.spec]p6: [P2096]
7800 // A partial specialization may be declared in any scope in which the
7801 // corresponding primary template may be defined.
7802 if (Ctx) {
7803 if (Ctx->isFileContext())
7804 return false;
7805 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7806 // C++ [temp.mem]p2:
7807 // A local class shall not have member templates.
7808 if (RD->isLocalClass())
7809 return Diag(TemplateParams->getTemplateLoc(),
7810 diag::err_template_inside_local_class)
7811 << TemplateParams->getSourceRange();
7812 else
7813 return false;
7814 }
7815 }
7816
7817 return Diag(TemplateParams->getTemplateLoc(),
7818 diag::err_template_outside_namespace_or_class_scope)
7819 << TemplateParams->getSourceRange();
7820}
7821
7822/// Determine what kind of template specialization the given declaration
7823/// is.
7825 if (!D)
7826 return TSK_Undeclared;
7827
7828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7829 return Record->getTemplateSpecializationKind();
7830 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7831 return Function->getTemplateSpecializationKind();
7832 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7833 return Var->getTemplateSpecializationKind();
7834
7835 return TSK_Undeclared;
7836}
7837
7838/// Check whether a specialization is well-formed in the current
7839/// context.
7840///
7841/// This routine determines whether a template specialization can be declared
7842/// in the current context (C++ [temp.expl.spec]p2).
7843///
7844/// \param S the semantic analysis object for which this check is being
7845/// performed.
7846///
7847/// \param Specialized the entity being specialized or instantiated, which
7848/// may be a kind of template (class template, function template, etc.) or
7849/// a member of a class template (member function, static data member,
7850/// member class).
7851///
7852/// \param PrevDecl the previous declaration of this entity, if any.
7853///
7854/// \param Loc the location of the explicit specialization or instantiation of
7855/// this entity.
7856///
7857/// \param IsPartialSpecialization whether this is a partial specialization of
7858/// a class template.
7859///
7860/// \returns true if there was an error that we cannot recover from, false
7861/// otherwise.
7863 NamedDecl *Specialized,
7864 NamedDecl *PrevDecl,
7867 // Keep these "kind" numbers in sync with the %select statements in the
7868 // various diagnostics emitted by this routine.
7869 int EntityKind = 0;
7870 if (isa<ClassTemplateDecl>(Specialized))
7871 EntityKind = IsPartialSpecialization? 1 : 0;
7872 else if (isa<VarTemplateDecl>(Specialized))
7873 EntityKind = IsPartialSpecialization ? 3 : 2;
7874 else if (isa<FunctionTemplateDecl>(Specialized))
7875 EntityKind = 4;
7876 else if (isa<CXXMethodDecl>(Specialized))
7877 EntityKind = 5;
7878 else if (isa<VarDecl>(Specialized))
7879 EntityKind = 6;
7880 else if (isa<RecordDecl>(Specialized))
7881 EntityKind = 7;
7882 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7883 EntityKind = 8;
7884 else {
7885 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7886 << S.getLangOpts().CPlusPlus11;
7887 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7888 return true;
7889 }
7890
7891 // C++ [temp.expl.spec]p2:
7892 // An explicit specialization may be declared in any scope in which
7893 // the corresponding primary template may be defined.
7895 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7896 << Specialized;
7897 return true;
7898 }
7899
7900 // C++ [temp.class.spec]p6:
7901 // A class template partial specialization may be declared in any
7902 // scope in which the primary template may be defined.
7903 DeclContext *SpecializedContext =
7904 Specialized->getDeclContext()->getRedeclContext();
7906
7907 // Make sure that this redeclaration (or definition) occurs in the same
7908 // scope or an enclosing namespace.
7909 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7910 : DC->Equals(SpecializedContext))) {
7911 if (isa<TranslationUnitDecl>(SpecializedContext))
7912 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7913 << EntityKind << Specialized;
7914 else {
7915 auto *ND = cast<NamedDecl>(SpecializedContext);
7916 int Diag = diag::err_template_spec_redecl_out_of_scope;
7917 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7918 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7919 S.Diag(Loc, Diag) << EntityKind << Specialized
7920 << ND << isa<CXXRecordDecl>(ND);
7921 }
7922
7923 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7924
7925 // Don't allow specializing in the wrong class during error recovery.
7926 // Otherwise, things can go horribly wrong.
7927 if (DC->isRecord())
7928 return true;
7929 }
7930
7931 return false;
7932}
7933
7935 if (!E->isTypeDependent())
7936 return SourceLocation();
7937 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7938 Checker.TraverseStmt(E);
7939 if (Checker.MatchLoc.isInvalid())
7940 return E->getSourceRange();
7941 return Checker.MatchLoc;
7942}
7943
7944static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7945 if (!TL.getType()->isDependentType())
7946 return SourceLocation();
7947 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7948 Checker.TraverseTypeLoc(TL);
7949 if (Checker.MatchLoc.isInvalid())
7950 return TL.getSourceRange();
7951 return Checker.MatchLoc;
7952}
7953
7954/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7955/// that checks non-type template partial specialization arguments.
7957 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7958 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7959 for (unsigned I = 0; I != NumArgs; ++I) {
7960 if (Args[I].getKind() == TemplateArgument::Pack) {
7962 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7963 Args[I].pack_size(), IsDefaultArgument))
7964 return true;
7965
7966 continue;
7967 }
7968
7969 if (Args[I].getKind() != TemplateArgument::Expression)
7970 continue;
7971
7972 Expr *ArgExpr = Args[I].getAsExpr();
7973
7974 // We can have a pack expansion of any of the bullets below.
7975 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7976 ArgExpr = Expansion->getPattern();
7977
7978 // Strip off any implicit casts we added as part of type checking.
7979 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7980 ArgExpr = ICE->getSubExpr();
7981
7982 // C++ [temp.class.spec]p8:
7983 // A non-type argument is non-specialized if it is the name of a
7984 // non-type parameter. All other non-type arguments are
7985 // specialized.
7986 //
7987 // Below, we check the two conditions that only apply to
7988 // specialized non-type arguments, so skip any non-specialized
7989 // arguments.
7990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7991 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7992 continue;
7993
7994 // C++ [temp.class.spec]p9:
7995 // Within the argument list of a class template partial
7996 // specialization, the following restrictions apply:
7997 // -- A partially specialized non-type argument expression
7998 // shall not involve a template parameter of the partial
7999 // specialization except when the argument expression is a
8000 // simple identifier.
8001 // -- The type of a template parameter corresponding to a
8002 // specialized non-type argument shall not be dependent on a
8003 // parameter of the specialization.
8004 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8005 // We implement a compromise between the original rules and DR1315:
8006 // -- A specialized non-type template argument shall not be
8007 // type-dependent and the corresponding template parameter
8008 // shall have a non-dependent type.
8009 SourceRange ParamUseRange =
8010 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8011 if (ParamUseRange.isValid()) {
8012 if (IsDefaultArgument) {
8013 S.Diag(TemplateNameLoc,
8014 diag::err_dependent_non_type_arg_in_partial_spec);
8015 S.Diag(ParamUseRange.getBegin(),
8016 diag::note_dependent_non_type_default_arg_in_partial_spec)
8017 << ParamUseRange;
8018 } else {
8019 S.Diag(ParamUseRange.getBegin(),
8020 diag::err_dependent_non_type_arg_in_partial_spec)
8021 << ParamUseRange;
8022 }
8023 return true;
8024 }
8025
8026 ParamUseRange = findTemplateParameter(
8027 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8028 if (ParamUseRange.isValid()) {
8029 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8030 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8031 << Param->getType();
8033 return true;
8034 }
8035 }
8036
8037 return false;
8038}
8039
8041 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8042 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8043 // We have to be conservative when checking a template in a dependent
8044 // context.
8045 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8046 return false;
8047
8048 TemplateParameterList *TemplateParams =
8049 PrimaryTemplate->getTemplateParameters();
8050 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8052 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8053 if (!Param)
8054 continue;
8055
8056 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8057 Param, &TemplateArgs[I],
8058 1, I >= NumExplicit))
8059 return true;
8060 }
8061
8062 return false;
8063}
8064
8066 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8067 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8069 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8070 assert(TUK != TagUseKind::Reference && "References are not specializations");
8071
8072 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8073 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8074 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8075
8076 // Find the class template we're specializing
8077 TemplateName Name = TemplateId.Template.get();
8079 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8080
8081 if (!ClassTemplate) {
8082 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8083 << (Name.getAsTemplateDecl() &&
8084 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8085 return true;
8086 }
8087
8088 bool isMemberSpecialization = false;
8089 bool isPartialSpecialization = false;
8090
8091 if (SS.isSet()) {
8092 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8093 diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
8094 ClassTemplate->getDeclName(),
8095 TemplateNameLoc, &TemplateId,
8096 /*IsMemberSpecialization=*/false))
8097 return true;
8098 }
8099
8100 // Check the validity of the template headers that introduce this
8101 // template.
8102 // FIXME: We probably shouldn't complain about these headers for
8103 // friend declarations.
8104 bool Invalid = false;
8105 TemplateParameterList *TemplateParams =
8107 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8108 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8109 if (Invalid)
8110 return true;
8111
8112 // Check that we can declare a template specialization here.
8113 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8114 return true;
8115
8116 if (TemplateParams && TemplateParams->size() > 0) {
8117 isPartialSpecialization = true;
8118
8119 if (TUK == TagUseKind::Friend) {
8120 Diag(KWLoc, diag::err_partial_specialization_friend)
8121 << SourceRange(LAngleLoc, RAngleLoc);
8122 return true;
8123 }
8124
8125 // C++ [temp.class.spec]p10:
8126 // The template parameter list of a specialization shall not
8127 // contain default template argument values.
8128 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8129 Decl *Param = TemplateParams->getParam(I);
8130 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8131 if (TTP->hasDefaultArgument()) {
8132 Diag(TTP->getDefaultArgumentLoc(),
8133 diag::err_default_arg_in_partial_spec);
8134 TTP->removeDefaultArgument();
8135 }
8136 } else if (NonTypeTemplateParmDecl *NTTP
8137 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8138 if (NTTP->hasDefaultArgument()) {
8139 Diag(NTTP->getDefaultArgumentLoc(),
8140 diag::err_default_arg_in_partial_spec)
8141 << NTTP->getDefaultArgument().getSourceRange();
8142 NTTP->removeDefaultArgument();
8143 }
8144 } else {
8145 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8146 if (TTP->hasDefaultArgument()) {
8148 diag::err_default_arg_in_partial_spec)
8150 TTP->removeDefaultArgument();
8151 }
8152 }
8153 }
8154 } else if (TemplateParams) {
8155 if (TUK == TagUseKind::Friend)
8156 Diag(KWLoc, diag::err_template_spec_friend)
8158 SourceRange(TemplateParams->getTemplateLoc(),
8159 TemplateParams->getRAngleLoc()))
8160 << SourceRange(LAngleLoc, RAngleLoc);
8161 } else {
8162 assert(TUK == TagUseKind::Friend &&
8163 "should have a 'template<>' for this decl");
8164 }
8165
8166 // Check that the specialization uses the same tag kind as the
8167 // original template.
8169 assert(Kind != TagTypeKind::Enum &&
8170 "Invalid enum tag in class template spec!");
8171 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8172 TUK == TagUseKind::Definition, KWLoc,
8173 ClassTemplate->getIdentifier())) {
8174 Diag(KWLoc, diag::err_use_with_wrong_tag)
8175 << ClassTemplate
8177 ClassTemplate->getTemplatedDecl()->getKindName());
8178 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8179 diag::note_previous_use);
8180 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8181 }
8182
8183 // Translate the parser's template argument list in our AST format.
8184 TemplateArgumentListInfo TemplateArgs =
8185 makeTemplateArgumentListInfo(*this, TemplateId);
8186
8187 // Check for unexpanded parameter packs in any of the template arguments.
8188 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8189 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8190 isPartialSpecialization
8193 return true;
8194
8195 // Check that the template argument list is well-formed for this
8196 // template.
8197 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8198 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8199 false, SugaredConverted, CanonicalConverted,
8200 /*UpdateArgsWithConversions=*/true))
8201 return true;
8202
8203 // Find the class template (partial) specialization declaration that
8204 // corresponds to these arguments.
8205 if (isPartialSpecialization) {
8207 TemplateArgs.size(),
8208 CanonicalConverted))
8209 return true;
8210
8211 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8212 // also do it during instantiation.
8213 if (!Name.isDependent() &&
8215 TemplateArgs, CanonicalConverted)) {
8216 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8217 << ClassTemplate->getDeclName();
8218 isPartialSpecialization = false;
8219 Invalid = true;
8220 }
8221 }
8222
8223 void *InsertPos = nullptr;
8224 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8225
8226 if (isPartialSpecialization)
8227 PrevDecl = ClassTemplate->findPartialSpecialization(
8228 CanonicalConverted, TemplateParams, InsertPos);
8229 else
8230 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8231
8233
8234 // Check whether we can declare a class template specialization in
8235 // the current scope.
8236 if (TUK != TagUseKind::Friend &&
8238 TemplateNameLoc,
8239 isPartialSpecialization))
8240 return true;
8241
8242 // The canonical type
8243 QualType CanonType;
8244 if (isPartialSpecialization) {
8245 // Build the canonical type that describes the converted template
8246 // arguments of the class template partial specialization.
8247 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8248 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8249 CanonicalConverted);
8250
8251 if (Context.hasSameType(CanonType,
8252 ClassTemplate->getInjectedClassNameSpecialization()) &&
8253 (!Context.getLangOpts().CPlusPlus20 ||
8254 !TemplateParams->hasAssociatedConstraints())) {
8255 // C++ [temp.class.spec]p9b3:
8256 //
8257 // -- The argument list of the specialization shall not be identical
8258 // to the implicit argument list of the primary template.
8259 //
8260 // This rule has since been removed, because it's redundant given DR1495,
8261 // but we keep it because it produces better diagnostics and recovery.
8262 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8263 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8264 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8265 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8266 ClassTemplate->getIdentifier(),
8267 TemplateNameLoc,
8268 Attr,
8269 TemplateParams,
8270 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8271 /*FriendLoc*/SourceLocation(),
8272 TemplateParameterLists.size() - 1,
8273 TemplateParameterLists.data());
8274 }
8275
8276 // Create a new class template partial specialization declaration node.
8278 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8281 Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8282 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8283 CanonType, PrevPartial);
8284 Partial->setTemplateArgsAsWritten(TemplateArgs);
8285 SetNestedNameSpecifier(*this, Partial, SS);
8286 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8288 Context, TemplateParameterLists.drop_back(1));
8289 }
8290
8291 if (!PrevPartial)
8292 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8293 Specialization = Partial;
8294
8295 // If we are providing an explicit specialization of a member class
8296 // template specialization, make a note of that.
8297 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8298 PrevPartial->setMemberSpecialization();
8299
8301 } else {
8302 // Create a new class template specialization declaration node for
8303 // this explicit specialization or friend declaration.
8305 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8306 ClassTemplate, CanonicalConverted, PrevDecl);
8307 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8309 if (TemplateParameterLists.size() > 0) {
8310 Specialization->setTemplateParameterListsInfo(Context,
8311 TemplateParameterLists);
8312 }
8313
8314 if (!PrevDecl)
8315 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8316
8318 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8319 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8320 CanonicalConverted);
8321 } else {
8323 }
8324 }
8325
8326 // C++ [temp.expl.spec]p6:
8327 // If a template, a member template or the member of a class template is
8328 // explicitly specialized then that specialization shall be declared
8329 // before the first use of that specialization that would cause an implicit
8330 // instantiation to take place, in every translation unit in which such a
8331 // use occurs; no diagnostic is required.
8332 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8333 bool Okay = false;
8334 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8335 // Is there any previous explicit specialization declaration?
8337 Okay = true;
8338 break;
8339 }
8340 }
8341
8342 if (!Okay) {
8343 SourceRange Range(TemplateNameLoc, RAngleLoc);
8344 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8346
8347 Diag(PrevDecl->getPointOfInstantiation(),
8348 diag::note_instantiation_required_here)
8349 << (PrevDecl->getTemplateSpecializationKind()
8351 return true;
8352 }
8353 }
8354
8355 // If this is not a friend, note that this is an explicit specialization.
8356 if (TUK != TagUseKind::Friend)
8357 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8358
8359 // Check that this isn't a redefinition of this specialization.
8360 if (TUK == TagUseKind::Definition) {
8361 RecordDecl *Def = Specialization->getDefinition();
8362 NamedDecl *Hidden = nullptr;
8363 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8364 SkipBody->ShouldSkip = true;
8365 SkipBody->Previous = Def;
8367 } else if (Def) {
8368 SourceRange Range(TemplateNameLoc, RAngleLoc);
8369 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8370 Diag(Def->getLocation(), diag::note_previous_definition);
8371 Specialization->setInvalidDecl();
8372 return true;
8373 }
8374 }
8375
8378
8379 // Add alignment attributes if necessary; these attributes are checked when
8380 // the ASTContext lays out the structure.
8381 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8384 }
8385
8386 if (ModulePrivateLoc.isValid())
8387 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8388 << (isPartialSpecialization? 1 : 0)
8389 << FixItHint::CreateRemoval(ModulePrivateLoc);
8390
8391 // C++ [temp.expl.spec]p9:
8392 // A template explicit specialization is in the scope of the
8393 // namespace in which the template was defined.
8394 //
8395 // We actually implement this paragraph where we set the semantic
8396 // context (in the creation of the ClassTemplateSpecializationDecl),
8397 // but we also maintain the lexical context where the actual
8398 // definition occurs.
8399 Specialization->setLexicalDeclContext(CurContext);
8400
8401 // We may be starting the definition of this specialization.
8402 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8403 Specialization->startDefinition();
8404
8405 if (TUK == TagUseKind::Friend) {
8406 // Build the fully-sugared type for this class template
8407 // specialization as the user wrote in the specialization
8408 // itself. This means that we'll pretty-print the type retrieved
8409 // from the specialization's declaration the way that the user
8410 // actually wrote the specialization, rather than formatting the
8411 // name based on the "canonical" representation used to store the
8412 // template arguments in the specialization.
8414 Name, TemplateNameLoc, TemplateArgs, CanonType);
8416 TemplateNameLoc,
8417 WrittenTy,
8418 /*FIXME:*/KWLoc);
8419 Friend->setAccess(AS_public);
8421 } else {
8422 // Add the specialization into its lexical context, so that it can
8423 // be seen when iterating through the list of declarations in that
8424 // context. However, specializations are not found by name lookup.
8426 }
8427
8428 if (SkipBody && SkipBody->ShouldSkip)
8429 return SkipBody->Previous;
8430
8431 Specialization->setInvalidDecl(Invalid);
8432 return Specialization;
8433}
8434
8436 MultiTemplateParamsArg TemplateParameterLists,
8437 Declarator &D) {
8438 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8439 ActOnDocumentableDecl(NewDecl);
8440 return NewDecl;
8441}
8442
8444 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8445 const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr,
8446 const ParsedAttributesView &Attrs) {
8447 DeclContext *DC = CurContext;
8448
8449 if (!DC->getRedeclContext()->isFileContext()) {
8450 Diag(NameLoc,
8451 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8452 return nullptr;
8453 }
8454
8455 if (TemplateParameterLists.size() > 1) {
8456 Diag(NameLoc, diag::err_concept_extra_headers);
8457 return nullptr;
8458 }
8459
8460 TemplateParameterList *Params = TemplateParameterLists.front();
8461
8462 if (Params->size() == 0) {
8463 Diag(NameLoc, diag::err_concept_no_parameters);
8464 return nullptr;
8465 }
8466
8467 // Ensure that the parameter pack, if present, is the last parameter in the
8468 // template.
8469 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8470 ParamEnd = Params->end();
8471 ParamIt != ParamEnd; ++ParamIt) {
8472 Decl const *Param = *ParamIt;
8473 if (Param->isParameterPack()) {
8474 if (++ParamIt == ParamEnd)
8475 break;
8476 Diag(Param->getLocation(),
8477 diag::err_template_param_pack_must_be_last_template_parameter);
8478 return nullptr;
8479 }
8480 }
8481
8482 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8483 return nullptr;
8484
8485 ConceptDecl *NewDecl =
8486 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
8487
8488 if (NewDecl->hasAssociatedConstraints()) {
8489 // C++2a [temp.concept]p4:
8490 // A concept shall not have associated constraints.
8491 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8492 NewDecl->setInvalidDecl();
8493 }
8494
8495 // Check for conflicting previous declaration.
8496 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8497 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8499 LookupName(Previous, S);
8500 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8501 /*AllowInlineNamespace*/false);
8502 bool AddToScope = true;
8503 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
8504
8505 ActOnDocumentableDecl(NewDecl);
8506 if (AddToScope)
8507 PushOnScopeChains(NewDecl, S);
8508
8509 ProcessDeclAttributeList(S, NewDecl, Attrs);
8510
8511 return NewDecl;
8512}
8513
8515 LookupResult &Previous, bool &AddToScope) {
8516 AddToScope = true;
8517
8518 if (Previous.empty())
8519 return;
8520
8521 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8522 if (!OldConcept) {
8523 auto *Old = Previous.getRepresentativeDecl();
8524 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8525 << NewDecl->getDeclName();
8526 notePreviousDefinition(Old, NewDecl->getLocation());
8527 AddToScope = false;
8528 return;
8529 }
8530 // Check if we can merge with a concept declaration.
8531 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8532 if (!IsSame) {
8533 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8534 << NewDecl->getDeclName();
8535 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8536 AddToScope = false;
8537 return;
8538 }
8539 if (hasReachableDefinition(OldConcept) &&
8540 IsRedefinitionInModule(NewDecl, OldConcept)) {
8541 Diag(NewDecl->getLocation(), diag::err_redefinition)
8542 << NewDecl->getDeclName();
8543 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8544 AddToScope = false;
8545 return;
8546 }
8547 if (!Previous.isSingleResult()) {
8548 // FIXME: we should produce an error in case of ambig and failed lookups.
8549 // Other decls (e.g. namespaces) also have this shortcoming.
8550 return;
8551 }
8552 // We unwrap canonical decl late to check for module visibility.
8553 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8554}
8555
8556/// \brief Strips various properties off an implicit instantiation
8557/// that has just been explicitly specialized.
8558static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8559 if (MinGW || (isa<FunctionDecl>(D) &&
8560 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8561 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8562
8563 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8564 FD->setInlineSpecified(false);
8565}
8566
8567/// Compute the diagnostic location for an explicit instantiation
8568// declaration or definition.
8570 NamedDecl* D, SourceLocation PointOfInstantiation) {
8571 // Explicit instantiations following a specialization have no effect and
8572 // hence no PointOfInstantiation. In that case, walk decl backwards
8573 // until a valid name loc is found.
8574 SourceLocation PrevDiagLoc = PointOfInstantiation;
8575 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8576 Prev = Prev->getPreviousDecl()) {
8577 PrevDiagLoc = Prev->getLocation();
8578 }
8579 assert(PrevDiagLoc.isValid() &&
8580 "Explicit instantiation without point of instantiation?");
8581 return PrevDiagLoc;
8582}
8583
8584bool
8587 NamedDecl *PrevDecl,
8589 SourceLocation PrevPointOfInstantiation,
8590 bool &HasNoEffect) {
8591 HasNoEffect = false;
8592
8593 switch (NewTSK) {
8594 case TSK_Undeclared:
8596 assert(
8597 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8598 "previous declaration must be implicit!");
8599 return false;
8600
8602 switch (PrevTSK) {
8603 case TSK_Undeclared:
8605 // Okay, we're just specializing something that is either already
8606 // explicitly specialized or has merely been mentioned without any
8607 // instantiation.
8608 return false;
8609
8611 if (PrevPointOfInstantiation.isInvalid()) {
8612 // The declaration itself has not actually been instantiated, so it is
8613 // still okay to specialize it.
8615 PrevDecl,
8616 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8617 return false;
8618 }
8619 // Fall through
8620 [[fallthrough]];
8621
8624 assert((PrevTSK == TSK_ImplicitInstantiation ||
8625 PrevPointOfInstantiation.isValid()) &&
8626 "Explicit instantiation without point of instantiation?");
8627
8628 // C++ [temp.expl.spec]p6:
8629 // If a template, a member template or the member of a class template
8630 // is explicitly specialized then that specialization shall be declared
8631 // before the first use of that specialization that would cause an
8632 // implicit instantiation to take place, in every translation unit in
8633 // which such a use occurs; no diagnostic is required.
8634 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8635 // Is there any previous explicit specialization declaration?
8637 return false;
8638 }
8639
8640 Diag(NewLoc, diag::err_specialization_after_instantiation)
8641 << PrevDecl;
8642 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8643 << (PrevTSK != TSK_ImplicitInstantiation);
8644
8645 return true;
8646 }
8647 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8648
8650 switch (PrevTSK) {
8652 // This explicit instantiation declaration is redundant (that's okay).
8653 HasNoEffect = true;
8654 return false;
8655
8656 case TSK_Undeclared:
8658 // We're explicitly instantiating something that may have already been
8659 // implicitly instantiated; that's fine.
8660 return false;
8661
8663 // C++0x [temp.explicit]p4:
8664 // For a given set of template parameters, if an explicit instantiation
8665 // of a template appears after a declaration of an explicit
8666 // specialization for that template, the explicit instantiation has no
8667 // effect.
8668 HasNoEffect = true;
8669 return false;
8670
8672 // C++0x [temp.explicit]p10:
8673 // If an entity is the subject of both an explicit instantiation
8674 // declaration and an explicit instantiation definition in the same
8675 // translation unit, the definition shall follow the declaration.
8676 Diag(NewLoc,
8677 diag::err_explicit_instantiation_declaration_after_definition);
8678
8679 // Explicit instantiations following a specialization have no effect and
8680 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8681 // until a valid name loc is found.
8682 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8683 diag::note_explicit_instantiation_definition_here);
8684 HasNoEffect = true;
8685 return false;
8686 }
8687 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8688
8690 switch (PrevTSK) {
8691 case TSK_Undeclared:
8693 // We're explicitly instantiating something that may have already been
8694 // implicitly instantiated; that's fine.
8695 return false;
8696
8698 // C++ DR 259, C++0x [temp.explicit]p4:
8699 // For a given set of template parameters, if an explicit
8700 // instantiation of a template appears after a declaration of
8701 // an explicit specialization for that template, the explicit
8702 // instantiation has no effect.
8703 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8704 << PrevDecl;
8705 Diag(PrevDecl->getLocation(),
8706 diag::note_previous_template_specialization);
8707 HasNoEffect = true;
8708 return false;
8709
8711 // We're explicitly instantiating a definition for something for which we
8712 // were previously asked to suppress instantiations. That's fine.
8713
8714 // C++0x [temp.explicit]p4:
8715 // For a given set of template parameters, if an explicit instantiation
8716 // of a template appears after a declaration of an explicit
8717 // specialization for that template, the explicit instantiation has no
8718 // effect.
8719 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8720 // Is there any previous explicit specialization declaration?
8722 HasNoEffect = true;
8723 break;
8724 }
8725 }
8726
8727 return false;
8728
8730 // C++0x [temp.spec]p5:
8731 // For a given template and a given set of template-arguments,
8732 // - an explicit instantiation definition shall appear at most once
8733 // in a program,
8734
8735 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8736 Diag(NewLoc, (getLangOpts().MSVCCompat)
8737 ? diag::ext_explicit_instantiation_duplicate
8738 : diag::err_explicit_instantiation_duplicate)
8739 << PrevDecl;
8740 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8741 diag::note_previous_explicit_instantiation);
8742 HasNoEffect = true;
8743 return false;
8744 }
8745 }
8746
8747 llvm_unreachable("Missing specialization/instantiation case?");
8748}
8749
8751 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
8753 // Remove anything from Previous that isn't a function template in
8754 // the correct context.
8755 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8756 LookupResult::Filter F = Previous.makeFilter();
8757 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8758 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8759 while (F.hasNext()) {
8761 if (!isa<FunctionTemplateDecl>(D)) {
8762 F.erase();
8763 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8764 continue;
8765 }
8766
8767 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8769 F.erase();
8770 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8771 continue;
8772 }
8773 }
8774 F.done();
8775
8776 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
8777 if (Previous.empty()) {
8778 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
8779 << IsFriend;
8780 for (auto &P : DiscardedCandidates)
8781 Diag(P.second->getLocation(),
8782 diag::note_dependent_function_template_spec_discard_reason)
8783 << P.first << IsFriend;
8784 return true;
8785 }
8786
8788 ExplicitTemplateArgs);
8789 return false;
8790}
8791
8793 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8794 LookupResult &Previous, bool QualifiedFriend) {
8795 // The set of function template specializations that could match this
8796 // explicit function template specialization.
8797 UnresolvedSet<8> Candidates;
8798 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8799 /*ForTakingAddress=*/false);
8800
8801 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8802 ConvertedTemplateArgs;
8803
8804 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8805 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8806 I != E; ++I) {
8807 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8808 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8809 // Only consider templates found within the same semantic lookup scope as
8810 // FD.
8811 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8813 continue;
8814
8815 QualType FT = FD->getType();
8816 // C++11 [dcl.constexpr]p8:
8817 // A constexpr specifier for a non-static member function that is not
8818 // a constructor declares that member function to be const.
8819 //
8820 // When matching a constexpr member function template specialization
8821 // against the primary template, we don't yet know whether the
8822 // specialization has an implicit 'const' (because we don't know whether
8823 // it will be a static member function until we know which template it
8824 // specializes). This rule was removed in C++14.
8825 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
8826 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
8827 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
8828 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8829 if (OldMD && OldMD->isConst()) {
8830 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8832 EPI.TypeQuals.addConst();
8834 FPT->getParamTypes(), EPI);
8835 }
8836 }
8837
8839 if (ExplicitTemplateArgs)
8840 Args = *ExplicitTemplateArgs;
8841
8842 // C++ [temp.expl.spec]p11:
8843 // A trailing template-argument can be left unspecified in the
8844 // template-id naming an explicit function template specialization
8845 // provided it can be deduced from the function argument type.
8846 // Perform template argument deduction to determine whether we may be
8847 // specializing this template.
8848 // FIXME: It is somewhat wasteful to build
8849 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8850 FunctionDecl *Specialization = nullptr;
8852 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8853 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
8855 // Template argument deduction failed; record why it failed, so
8856 // that we can provide nifty diagnostics.
8857 FailedCandidates.addCandidate().set(
8858 I.getPair(), FunTmpl->getTemplatedDecl(),
8859 MakeDeductionFailureInfo(Context, TDK, Info));
8860 (void)TDK;
8861 continue;
8862 }
8863
8864 // Target attributes are part of the cuda function signature, so
8865 // the deduced template's cuda target must match that of the
8866 // specialization. Given that C++ template deduction does not
8867 // take target attributes into account, we reject candidates
8868 // here that have a different target.
8869 if (LangOpts.CUDA &&
8871 /* IgnoreImplicitHDAttr = */ true) !=
8872 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8873 FailedCandidates.addCandidate().set(
8874 I.getPair(), FunTmpl->getTemplatedDecl(),
8877 continue;
8878 }
8879
8880 // Record this candidate.
8881 if (ExplicitTemplateArgs)
8882 ConvertedTemplateArgs[Specialization] = std::move(Args);
8883 Candidates.addDecl(Specialization, I.getAccess());
8884 }
8885 }
8886
8887 // For a qualified friend declaration (with no explicit marker to indicate
8888 // that a template specialization was intended), note all (template and
8889 // non-template) candidates.
8890 if (QualifiedFriend && Candidates.empty()) {
8891 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8892 << FD->getDeclName() << FDLookupContext;
8893 // FIXME: We should form a single candidate list and diagnose all
8894 // candidates at once, to get proper sorting and limiting.
8895 for (auto *OldND : Previous) {
8896 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8897 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8898 }
8899 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8900 return true;
8901 }
8902
8903 // Find the most specialized function template.
8905 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8906 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8907 PDiag(diag::err_function_template_spec_ambiguous)
8908 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8909 PDiag(diag::note_function_template_spec_matched));
8910
8911 if (Result == Candidates.end())
8912 return true;
8913
8914 // Ignore access information; it doesn't figure into redeclaration checking.
8915 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8916
8917 // C++23 [except.spec]p13:
8918 // An exception specification is considered to be needed when:
8919 // - [...]
8920 // - the exception specification is compared to that of another declaration
8921 // (e.g., an explicit specialization or an overriding virtual function);
8922 // - [...]
8923 //
8924 // The exception specification of a defaulted function is evaluated as
8925 // described above only when needed; similarly, the noexcept-specifier of a
8926 // specialization of a function template or member function of a class
8927 // template is instantiated only when needed.
8928 //
8929 // The standard doesn't specify what the "comparison with another declaration"
8930 // entails, nor the exact circumstances in which it occurs. Moreover, it does
8931 // not state which properties of an explicit specialization must match the
8932 // primary template.
8933 //
8934 // We assume that an explicit specialization must correspond with (per
8935 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
8936 // the declaration produced by substitution into the function template.
8937 //
8938 // Since the determination whether two function declarations correspond does
8939 // not consider exception specification, we only need to instantiate it once
8940 // we determine the primary template when comparing types per
8941 // [basic.link]p11.1.
8942 auto *SpecializationFPT =
8943 Specialization->getType()->castAs<FunctionProtoType>();
8944 // If the function has a dependent exception specification, resolve it after
8945 // we have selected the primary template so we can check whether it matches.
8946 if (getLangOpts().CPlusPlus17 &&
8947 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
8948 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
8949 return true;
8950
8952 = Specialization->getTemplateSpecializationInfo();
8953 assert(SpecInfo && "Function template specialization info missing?");
8954
8955 // Note: do not overwrite location info if previous template
8956 // specialization kind was explicit.
8958 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8959 Specialization->setLocation(FD->getLocation());
8960 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8961 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8962 // function can differ from the template declaration with respect to
8963 // the constexpr specifier.
8964 // FIXME: We need an update record for this AST mutation.
8965 // FIXME: What if there are multiple such prior declarations (for instance,
8966 // from different modules)?
8967 Specialization->setConstexprKind(FD->getConstexprKind());
8968 }
8969
8970 // FIXME: Check if the prior specialization has a point of instantiation.
8971 // If so, we have run afoul of .
8972
8973 // If this is a friend declaration, then we're not really declaring
8974 // an explicit specialization.
8975 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8976
8977 // Check the scope of this explicit specialization.
8978 if (!isFriend &&
8980 Specialization->getPrimaryTemplate(),
8982 false))
8983 return true;
8984
8985 // C++ [temp.expl.spec]p6:
8986 // If a template, a member template or the member of a class template is
8987 // explicitly specialized then that specialization shall be declared
8988 // before the first use of that specialization that would cause an implicit
8989 // instantiation to take place, in every translation unit in which such a
8990 // use occurs; no diagnostic is required.
8991 bool HasNoEffect = false;
8992 if (!isFriend &&
8997 SpecInfo->getPointOfInstantiation(),
8998 HasNoEffect))
8999 return true;
9000
9001 // Mark the prior declaration as an explicit specialization, so that later
9002 // clients know that this is an explicit specialization.
9003 if (!isFriend) {
9004 // Since explicit specializations do not inherit '=delete' from their
9005 // primary function template - check if the 'specialization' that was
9006 // implicitly generated (during template argument deduction for partial
9007 // ordering) from the most specialized of all the function templates that
9008 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9009 // first check that it was implicitly generated during template argument
9010 // deduction by making sure it wasn't referenced, and then reset the deleted
9011 // flag to not-deleted, so that we can inherit that information from 'FD'.
9012 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9013 !Specialization->getCanonicalDecl()->isReferenced()) {
9014 // FIXME: This assert will not hold in the presence of modules.
9015 assert(
9016 Specialization->getCanonicalDecl() == Specialization &&
9017 "This must be the only existing declaration of this specialization");
9018 // FIXME: We need an update record for this AST mutation.
9019 Specialization->setDeletedAsWritten(false);
9020 }
9021 // FIXME: We need an update record for this AST mutation.
9024 }
9025
9026 // Turn the given function declaration into a function template
9027 // specialization, with the template arguments from the previous
9028 // specialization.
9029 // Take copies of (semantic and syntactic) template argument lists.
9031 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9032 FD->setFunctionTemplateSpecialization(
9033 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9035 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9036
9037 // A function template specialization inherits the target attributes
9038 // of its template. (We require the attributes explicitly in the
9039 // code to match, but a template may have implicit attributes by
9040 // virtue e.g. of being constexpr, and it passes these implicit
9041 // attributes on to its specializations.)
9042 if (LangOpts.CUDA)
9043 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9044
9045 // The "previous declaration" for this function template specialization is
9046 // the prior function template specialization.
9047 Previous.clear();
9048 Previous.addDecl(Specialization);
9049 return false;
9050}
9051
9052bool
9054 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9055
9056 // Try to find the member we are instantiating.
9057 NamedDecl *FoundInstantiation = nullptr;
9058 NamedDecl *Instantiation = nullptr;
9059 NamedDecl *InstantiatedFrom = nullptr;
9060 MemberSpecializationInfo *MSInfo = nullptr;
9061
9062 if (Previous.empty()) {
9063 // Nowhere to look anyway.
9064 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9065 SmallVector<FunctionDecl *> Candidates;
9066 bool Ambiguous = false;
9067 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9068 I != E; ++I) {
9069 CXXMethodDecl *Method =
9070 dyn_cast<CXXMethodDecl>((*I)->getUnderlyingDecl());
9071 if (!Method)
9072 continue;
9073 QualType Adjusted = Function->getType();
9074 if (!hasExplicitCallingConv(Adjusted))
9075 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9076 // This doesn't handle deduced return types, but both function
9077 // declarations should be undeduced at this point.
9078 if (!Context.hasSameType(Adjusted, Method->getType()))
9079 continue;
9080 if (ConstraintSatisfaction Satisfaction;
9081 Method->getTrailingRequiresClause() &&
9082 (CheckFunctionConstraints(Method, Satisfaction,
9083 /*UsageLoc=*/Member->getLocation(),
9084 /*ForOverloadResolution=*/true) ||
9085 !Satisfaction.IsSatisfied))
9086 continue;
9087 Candidates.push_back(Method);
9088 FunctionDecl *MoreConstrained =
9089 Instantiation ? getMoreConstrainedFunction(
9090 Method, cast<FunctionDecl>(Instantiation))
9091 : Method;
9092 if (!MoreConstrained) {
9093 Ambiguous = true;
9094 continue;
9095 }
9096 if (MoreConstrained == Method) {
9097 Ambiguous = false;
9098 FoundInstantiation = *I;
9099 Instantiation = Method;
9100 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9101 MSInfo = Method->getMemberSpecializationInfo();
9102 }
9103 }
9104 if (Ambiguous) {
9105 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9106 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9107 for (FunctionDecl *Candidate : Candidates)
9108 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9109 << Candidate;
9110 return true;
9111 }
9112 } else if (isa<VarDecl>(Member)) {
9113 VarDecl *PrevVar;
9114 if (Previous.isSingleResult() &&
9115 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9116 if (PrevVar->isStaticDataMember()) {
9117 FoundInstantiation = Previous.getRepresentativeDecl();
9118 Instantiation = PrevVar;
9119 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9120 MSInfo = PrevVar->getMemberSpecializationInfo();
9121 }
9122 } else if (isa<RecordDecl>(Member)) {
9123 CXXRecordDecl *PrevRecord;
9124 if (Previous.isSingleResult() &&
9125 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9126 FoundInstantiation = Previous.getRepresentativeDecl();
9127 Instantiation = PrevRecord;
9128 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9129 MSInfo = PrevRecord->getMemberSpecializationInfo();
9130 }
9131 } else if (isa<EnumDecl>(Member)) {
9132 EnumDecl *PrevEnum;
9133 if (Previous.isSingleResult() &&
9134 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9135 FoundInstantiation = Previous.getRepresentativeDecl();
9136 Instantiation = PrevEnum;
9137 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9138 MSInfo = PrevEnum->getMemberSpecializationInfo();
9139 }
9140 }
9141
9142 if (!Instantiation) {
9143 // There is no previous declaration that matches. Since member
9144 // specializations are always out-of-line, the caller will complain about
9145 // this mismatch later.
9146 return false;
9147 }
9148
9149 // A member specialization in a friend declaration isn't really declaring
9150 // an explicit specialization, just identifying a specific (possibly implicit)
9151 // specialization. Don't change the template specialization kind.
9152 //
9153 // FIXME: Is this really valid? Other compilers reject.
9154 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9155 // Preserve instantiation information.
9156 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9157 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9158 cast<CXXMethodDecl>(InstantiatedFrom),
9159 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9160 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9161 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9162 cast<CXXRecordDecl>(InstantiatedFrom),
9163 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9164 }
9165
9166 Previous.clear();
9167 Previous.addDecl(FoundInstantiation);
9168 return false;
9169 }
9170
9171 // Make sure that this is a specialization of a member.
9172 if (!InstantiatedFrom) {
9173 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9174 << Member;
9175 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9176 return true;
9177 }
9178
9179 // C++ [temp.expl.spec]p6:
9180 // If a template, a member template or the member of a class template is
9181 // explicitly specialized then that specialization shall be declared
9182 // before the first use of that specialization that would cause an implicit
9183 // instantiation to take place, in every translation unit in which such a
9184 // use occurs; no diagnostic is required.
9185 assert(MSInfo && "Member specialization info missing?");
9186
9187 bool HasNoEffect = false;
9190 Instantiation,
9192 MSInfo->getPointOfInstantiation(),
9193 HasNoEffect))
9194 return true;
9195
9196 // Check the scope of this explicit specialization.
9198 InstantiatedFrom,
9199 Instantiation, Member->getLocation(),
9200 false))
9201 return true;
9202
9203 // Note that this member specialization is an "instantiation of" the
9204 // corresponding member of the original template.
9205 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9206 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9207 if (InstantiationFunction->getTemplateSpecializationKind() ==
9209 // Explicit specializations of member functions of class templates do not
9210 // inherit '=delete' from the member function they are specializing.
9211 if (InstantiationFunction->isDeleted()) {
9212 // FIXME: This assert will not hold in the presence of modules.
9213 assert(InstantiationFunction->getCanonicalDecl() ==
9214 InstantiationFunction);
9215 // FIXME: We need an update record for this AST mutation.
9216 InstantiationFunction->setDeletedAsWritten(false);
9217 }
9218 }
9219
9220 MemberFunction->setInstantiationOfMemberFunction(
9221 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9222 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9223 MemberVar->setInstantiationOfStaticDataMember(
9224 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9225 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9226 MemberClass->setInstantiationOfMemberClass(
9227 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9228 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9229 MemberEnum->setInstantiationOfMemberEnum(
9230 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9231 } else {
9232 llvm_unreachable("unknown member specialization kind");
9233 }
9234
9235 // Save the caller the trouble of having to figure out which declaration
9236 // this specialization matches.
9237 Previous.clear();
9238 Previous.addDecl(FoundInstantiation);
9239 return false;
9240}
9241
9242/// Complete the explicit specialization of a member of a class template by
9243/// updating the instantiated member to be marked as an explicit specialization.
9244///
9245/// \param OrigD The member declaration instantiated from the template.
9246/// \param Loc The location of the explicit specialization of the member.
9247template<typename DeclT>
9248static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9250 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9251 return;
9252
9253 // FIXME: Inform AST mutation listeners of this AST mutation.
9254 // FIXME: If there are multiple in-class declarations of the member (from
9255 // multiple modules, or a declaration and later definition of a member type),
9256 // should we update all of them?
9257 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9258 OrigD->setLocation(Loc);
9259}
9260
9263 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9264 if (Instantiation == Member)
9265 return;
9266
9267 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9268 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9269 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9270 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9271 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9272 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9273 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9274 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9275 else
9276 llvm_unreachable("unknown member specialization kind");
9277}
9278
9279/// Check the scope of an explicit instantiation.
9280///
9281/// \returns true if a serious error occurs, false otherwise.
9283 SourceLocation InstLoc,
9284 bool WasQualifiedName) {
9286 DeclContext *CurContext = S.CurContext->getRedeclContext();
9287
9288 if (CurContext->isRecord()) {
9289 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9290 << D;
9291 return true;
9292 }
9293
9294 // C++11 [temp.explicit]p3:
9295 // An explicit instantiation shall appear in an enclosing namespace of its
9296 // template. If the name declared in the explicit instantiation is an
9297 // unqualified name, the explicit instantiation shall appear in the
9298 // namespace where its template is declared or, if that namespace is inline
9299 // (7.3.1), any namespace from its enclosing namespace set.
9300 //
9301 // This is DR275, which we do not retroactively apply to C++98/03.
9302 if (WasQualifiedName) {
9303 if (CurContext->Encloses(OrigContext))
9304 return false;
9305 } else {
9306 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9307 return false;
9308 }
9309
9310 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9311 if (WasQualifiedName)
9312 S.Diag(InstLoc,
9313 S.getLangOpts().CPlusPlus11?
9314 diag::err_explicit_instantiation_out_of_scope :
9315 diag::warn_explicit_instantiation_out_of_scope_0x)
9316 << D << NS;
9317 else
9318 S.Diag(InstLoc,
9319 S.getLangOpts().CPlusPlus11?
9320 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9321 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9322 << D << NS;
9323 } else
9324 S.Diag(InstLoc,
9325 S.getLangOpts().CPlusPlus11?
9326 diag::err_explicit_instantiation_must_be_global :
9327 diag::warn_explicit_instantiation_must_be_global_0x)
9328 << D;
9329 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9330 return false;
9331}
9332
9333/// Common checks for whether an explicit instantiation of \p D is valid.
9335 SourceLocation InstLoc,
9336 bool WasQualifiedName,
9338 // C++ [temp.explicit]p13:
9339 // An explicit instantiation declaration shall not name a specialization of
9340 // a template with internal linkage.
9342 D->getFormalLinkage() == Linkage::Internal) {
9343 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9344 return true;
9345 }
9346
9347 // C++11 [temp.explicit]p3: [DR 275]
9348 // An explicit instantiation shall appear in an enclosing namespace of its
9349 // template.
9350 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9351 return true;
9352
9353 return false;
9354}
9355
9356/// Determine whether the given scope specifier has a template-id in it.
9358 if (!SS.isSet())
9359 return false;
9360
9361 // C++11 [temp.explicit]p3:
9362 // If the explicit instantiation is for a member function, a member class
9363 // or a static data member of a class template specialization, the name of
9364 // the class template specialization in the qualified-id for the member
9365 // name shall be a simple-template-id.
9366 //
9367 // C++98 has the same restriction, just worded differently.
9368 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9369 NNS = NNS->getPrefix())
9370 if (const Type *T = NNS->getAsType())
9371 if (isa<TemplateSpecializationType>(T))
9372 return true;
9373
9374 return false;
9375}
9376
9377/// Make a dllexport or dllimport attr on a class template specialization take
9378/// effect.
9381 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9382 assert(A && "dllExportImportClassTemplateSpecialization called "
9383 "on Def without dllexport or dllimport");
9384
9385 // We reject explicit instantiations in class scope, so there should
9386 // never be any delayed exported classes to worry about.
9387 assert(S.DelayedDllExportClasses.empty() &&
9388 "delayed exports present at explicit instantiation");
9390
9391 // Propagate attribute to base class templates.
9392 for (auto &B : Def->bases()) {
9393 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9394 B.getType()->getAsCXXRecordDecl()))
9396 }
9397
9399}
9400
9402 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9403 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9404 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9405 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9406 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9407 // Find the class template we're specializing
9408 TemplateName Name = TemplateD.get();
9409 TemplateDecl *TD = Name.getAsTemplateDecl();
9410 // Check that the specialization uses the same tag kind as the
9411 // original template.
9413 assert(Kind != TagTypeKind::Enum &&
9414 "Invalid enum tag in class template explicit instantiation!");
9415
9416 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9417
9418 if (!ClassTemplate) {
9419 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9420 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9421 << TD << NTK << llvm::to_underlying(Kind);
9422 Diag(TD->getLocation(), diag::note_previous_use);
9423 return true;
9424 }
9425
9426 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9427 Kind, /*isDefinition*/false, KWLoc,
9428 ClassTemplate->getIdentifier())) {
9429 Diag(KWLoc, diag::err_use_with_wrong_tag)
9430 << ClassTemplate
9432 ClassTemplate->getTemplatedDecl()->getKindName());
9433 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9434 diag::note_previous_use);
9435 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9436 }
9437
9438 // C++0x [temp.explicit]p2:
9439 // There are two forms of explicit instantiation: an explicit instantiation
9440 // definition and an explicit instantiation declaration. An explicit
9441 // instantiation declaration begins with the extern keyword. [...]
9442 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9445
9447 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9448 // Check for dllexport class template instantiation declarations,
9449 // except for MinGW mode.
9450 for (const ParsedAttr &AL : Attr) {
9451 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9452 Diag(ExternLoc,
9453 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9454 Diag(AL.getLoc(), diag::note_attribute);
9455 break;
9456 }
9457 }
9458
9459 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9460 Diag(ExternLoc,
9461 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9462 Diag(A->getLocation(), diag::note_attribute);
9463 }
9464 }
9465
9466 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9467 // instantiation declarations for most purposes.
9468 bool DLLImportExplicitInstantiationDef = false;
9471 // Check for dllimport class template instantiation definitions.
9472 bool DLLImport =
9473 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9474 for (const ParsedAttr &AL : Attr) {
9475 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9476 DLLImport = true;
9477 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9478 // dllexport trumps dllimport here.
9479 DLLImport = false;
9480 break;
9481 }
9482 }
9483 if (DLLImport) {
9485 DLLImportExplicitInstantiationDef = true;
9486 }
9487 }
9488
9489 // Translate the parser's template argument list in our AST format.
9490 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9491 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9492
9493 // Check that the template argument list is well-formed for this
9494 // template.
9495 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9496 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9497 false, SugaredConverted, CanonicalConverted,
9498 /*UpdateArgsWithConversions=*/true))
9499 return true;
9500
9501 // Find the class template specialization declaration that
9502 // corresponds to these arguments.
9503 void *InsertPos = nullptr;
9505 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9506
9507 TemplateSpecializationKind PrevDecl_TSK
9508 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9509
9510 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9511 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9512 // Check for dllexport class template instantiation definitions in MinGW
9513 // mode, if a previous declaration of the instantiation was seen.
9514 for (const ParsedAttr &AL : Attr) {
9515 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9516 Diag(AL.getLoc(),
9517 diag::warn_attribute_dllexport_explicit_instantiation_def);
9518 break;
9519 }
9520 }
9521 }
9522
9523 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9524 SS.isSet(), TSK))
9525 return true;
9526
9528
9529 bool HasNoEffect = false;
9530 if (PrevDecl) {
9531 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9532 PrevDecl, PrevDecl_TSK,
9533 PrevDecl->getPointOfInstantiation(),
9534 HasNoEffect))
9535 return PrevDecl;
9536
9537 // Even though HasNoEffect == true means that this explicit instantiation
9538 // has no effect on semantics, we go on to put its syntax in the AST.
9539
9540 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9541 PrevDecl_TSK == TSK_Undeclared) {
9542 // Since the only prior class template specialization with these
9543 // arguments was referenced but not declared, reuse that
9544 // declaration node as our own, updating the source location
9545 // for the template name to reflect our new declaration.
9546 // (Other source locations will be updated later.)
9547 Specialization = PrevDecl;
9548 Specialization->setLocation(TemplateNameLoc);
9549 PrevDecl = nullptr;
9550 }
9551
9552 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9553 DLLImportExplicitInstantiationDef) {
9554 // The new specialization might add a dllimport attribute.
9555 HasNoEffect = false;
9556 }
9557 }
9558
9559 if (!Specialization) {
9560 // Create a new class template specialization declaration node for
9561 // this explicit specialization.
9563 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9564 ClassTemplate, CanonicalConverted, PrevDecl);
9566
9567 // A MSInheritanceAttr attached to the previous declaration must be
9568 // propagated to the new node prior to instantiation.
9569 if (PrevDecl) {
9570 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9571 auto *Clone = A->clone(getASTContext());
9572 Clone->setInherited(true);
9573 Specialization->addAttr(Clone);
9575 }
9576 }
9577
9578 if (!HasNoEffect && !PrevDecl) {
9579 // Insert the new specialization.
9580 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9581 }
9582 }
9583
9584 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9585
9586 // Set source locations for keywords.
9587 Specialization->setExternKeywordLoc(ExternLoc);
9588 Specialization->setTemplateKeywordLoc(TemplateLoc);
9589 Specialization->setBraceRange(SourceRange());
9590
9591 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9594
9595 // Add the explicit instantiation into its lexical context. However,
9596 // since explicit instantiations are never found by name lookup, we
9597 // just put it into the declaration context directly.
9598 Specialization->setLexicalDeclContext(CurContext);
9600
9601 // Syntax is now OK, so return if it has no other effect on semantics.
9602 if (HasNoEffect) {
9603 // Set the template specialization kind.
9604 Specialization->setTemplateSpecializationKind(TSK);
9605 return Specialization;
9606 }
9607
9608 // C++ [temp.explicit]p3:
9609 // A definition of a class template or class member template
9610 // shall be in scope at the point of the explicit instantiation of
9611 // the class template or class member template.
9612 //
9613 // This check comes when we actually try to perform the
9614 // instantiation.
9616 = cast_or_null<ClassTemplateSpecializationDecl>(
9617 Specialization->getDefinition());
9618 if (!Def)
9620 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9621 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9622 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9623 }
9624
9625 // Instantiate the members of this class template specialization.
9626 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9627 Specialization->getDefinition());
9628 if (Def) {
9630 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9631 // TSK_ExplicitInstantiationDefinition
9632 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9634 DLLImportExplicitInstantiationDef)) {
9635 // FIXME: Need to notify the ASTMutationListener that we did this.
9637
9638 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9640 // An explicit instantiation definition can add a dll attribute to a
9641 // template with a previous instantiation declaration. MinGW doesn't
9642 // allow this.
9643 auto *A = cast<InheritableAttr>(
9645 A->setInherited(true);
9646 Def->addAttr(A);
9648 }
9649 }
9650
9651 // Fix a TSK_ImplicitInstantiation followed by a
9652 // TSK_ExplicitInstantiationDefinition
9653 bool NewlyDLLExported =
9654 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9655 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9657 // An explicit instantiation definition can add a dll attribute to a
9658 // template with a previous implicit instantiation. MinGW doesn't allow
9659 // this. We limit clang to only adding dllexport, to avoid potentially
9660 // strange codegen behavior. For example, if we extend this conditional
9661 // to dllimport, and we have a source file calling a method on an
9662 // implicitly instantiated template class instance and then declaring a
9663 // dllimport explicit instantiation definition for the same template
9664 // class, the codegen for the method call will not respect the dllimport,
9665 // while it will with cl. The Def will already have the DLL attribute,
9666 // since the Def and Specialization will be the same in the case of
9667 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9668 // attribute to the Specialization; we just need to make it take effect.
9669 assert(Def == Specialization &&
9670 "Def and Specialization should match for implicit instantiation");
9672 }
9673
9674 // In MinGW mode, export the template instantiation if the declaration
9675 // was marked dllexport.
9676 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9677 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9678 PrevDecl->hasAttr<DLLExportAttr>()) {
9680 }
9681
9682 // Set the template specialization kind. Make sure it is set before
9683 // instantiating the members which will trigger ASTConsumer callbacks.
9684 Specialization->setTemplateSpecializationKind(TSK);
9685 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9686 } else {
9687
9688 // Set the template specialization kind.
9689 Specialization->setTemplateSpecializationKind(TSK);
9690 }
9691
9692 return Specialization;
9693}
9694
9697 SourceLocation TemplateLoc, unsigned TagSpec,
9698 SourceLocation KWLoc, CXXScopeSpec &SS,
9699 IdentifierInfo *Name, SourceLocation NameLoc,
9700 const ParsedAttributesView &Attr) {
9701
9702 bool Owned = false;
9703 bool IsDependent = false;
9704 Decl *TagD =
9705 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
9706 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9707 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
9708 false, TypeResult(), /*IsTypeSpecifier*/ false,
9709 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
9710 .get();
9711 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9712
9713 if (!TagD)
9714 return true;
9715
9716 TagDecl *Tag = cast<TagDecl>(TagD);
9717 assert(!Tag->isEnum() && "shouldn't see enumerations here");
9718
9719 if (Tag->isInvalidDecl())
9720 return true;
9721
9722 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9724 if (!Pattern) {
9725 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9727 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9728 return true;
9729 }
9730
9731 // C++0x [temp.explicit]p2:
9732 // If the explicit instantiation is for a class or member class, the
9733 // elaborated-type-specifier in the declaration shall include a
9734 // simple-template-id.
9735 //
9736 // C++98 has the same restriction, just worded differently.
9738 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9739 << Record << SS.getRange();
9740
9741 // C++0x [temp.explicit]p2:
9742 // There are two forms of explicit instantiation: an explicit instantiation
9743 // definition and an explicit instantiation declaration. An explicit
9744 // instantiation declaration begins with the extern keyword. [...]
9748
9749 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9750
9751 // Verify that it is okay to explicitly instantiate here.
9752 CXXRecordDecl *PrevDecl
9753 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9754 if (!PrevDecl && Record->getDefinition())
9755 PrevDecl = Record;
9756 if (PrevDecl) {
9758 bool HasNoEffect = false;
9759 assert(MSInfo && "No member specialization information?");
9760 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9761 PrevDecl,
9763 MSInfo->getPointOfInstantiation(),
9764 HasNoEffect))
9765 return true;
9766 if (HasNoEffect)
9767 return TagD;
9768 }
9769
9770 CXXRecordDecl *RecordDef
9771 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9772 if (!RecordDef) {
9773 // C++ [temp.explicit]p3:
9774 // A definition of a member class of a class template shall be in scope
9775 // at the point of an explicit instantiation of the member class.
9776 CXXRecordDecl *Def
9777 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9778 if (!Def) {
9779 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9780 << 0 << Record->getDeclName() << Record->getDeclContext();
9781 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9782 << Pattern;
9783 return true;
9784 } else {
9785 if (InstantiateClass(NameLoc, Record, Def,
9787 TSK))
9788 return true;
9789
9790 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9791 if (!RecordDef)
9792 return true;
9793 }
9794 }
9795
9796 // Instantiate all of the members of the class.
9797 InstantiateClassMembers(NameLoc, RecordDef,
9799
9801 MarkVTableUsed(NameLoc, RecordDef, true);
9802
9803 // FIXME: We don't have any representation for explicit instantiations of
9804 // member classes. Such a representation is not needed for compilation, but it
9805 // should be available for clients that want to see all of the declarations in
9806 // the source code.
9807 return TagD;
9808}
9809
9811 SourceLocation ExternLoc,
9812 SourceLocation TemplateLoc,
9813 Declarator &D) {
9814 // Explicit instantiations always require a name.
9815 // TODO: check if/when DNInfo should replace Name.
9817 DeclarationName Name = NameInfo.getName();
9818 if (!Name) {
9819 if (!D.isInvalidType())
9820 Diag(D.getDeclSpec().getBeginLoc(),
9821 diag::err_explicit_instantiation_requires_name)
9822 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9823
9824 return true;
9825 }
9826
9827 // Get the innermost enclosing declaration scope.
9828 S = S->getDeclParent();
9829
9830 // Determine the type of the declaration.
9832 QualType R = T->getType();
9833 if (R.isNull())
9834 return true;
9835
9836 // C++ [dcl.stc]p1:
9837 // A storage-class-specifier shall not be specified in [...] an explicit
9838 // instantiation (14.7.2) directive.
9839 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9840 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9841 << Name;
9842 return true;
9843 } else if (D.getDeclSpec().getStorageClassSpec()
9845 // Complain about then remove the storage class specifier.
9846 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9847 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9848
9849 D.getMutableDeclSpec().ClearStorageClassSpecs();
9850 }
9851
9852 // C++0x [temp.explicit]p1:
9853 // [...] An explicit instantiation of a function template shall not use the
9854 // inline or constexpr specifiers.
9855 // Presumably, this also applies to member functions of class templates as
9856 // well.
9857 if (D.getDeclSpec().isInlineSpecified())
9858 Diag(D.getDeclSpec().getInlineSpecLoc(),
9860 diag::err_explicit_instantiation_inline :
9861 diag::warn_explicit_instantiation_inline_0x)
9862 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9863 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9864 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9865 // not already specified.
9866 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9867 diag::err_explicit_instantiation_constexpr);
9868
9869 // A deduction guide is not on the list of entities that can be explicitly
9870 // instantiated.
9871 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9872 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9873 << /*explicit instantiation*/ 0;
9874 return true;
9875 }
9876
9877 // C++0x [temp.explicit]p2:
9878 // There are two forms of explicit instantiation: an explicit instantiation
9879 // definition and an explicit instantiation declaration. An explicit
9880 // instantiation declaration begins with the extern keyword. [...]
9884
9885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9886 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
9887 /*ObjectType=*/QualType());
9888
9889 if (!R->isFunctionType()) {
9890 // C++ [temp.explicit]p1:
9891 // A [...] static data member of a class template can be explicitly
9892 // instantiated from the member definition associated with its class
9893 // template.
9894 // C++1y [temp.explicit]p1:
9895 // A [...] variable [...] template specialization can be explicitly
9896 // instantiated from its template.
9897 if (Previous.isAmbiguous())
9898 return true;
9899
9900 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9901 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9902
9903 if (!PrevTemplate) {
9904 if (!Prev || !Prev->isStaticDataMember()) {
9905 // We expect to see a static data member here.
9906 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9907 << Name;
9908 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9909 P != PEnd; ++P)
9910 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9911 return true;
9912 }
9913
9915 // FIXME: Check for explicit specialization?
9916 Diag(D.getIdentifierLoc(),
9917 diag::err_explicit_instantiation_data_member_not_instantiated)
9918 << Prev;
9919 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9920 // FIXME: Can we provide a note showing where this was declared?
9921 return true;
9922 }
9923 } else {
9924 // Explicitly instantiate a variable template.
9925
9926 // C++1y [dcl.spec.auto]p6:
9927 // ... A program that uses auto or decltype(auto) in a context not
9928 // explicitly allowed in this section is ill-formed.
9929 //
9930 // This includes auto-typed variable template instantiations.
9931 if (R->isUndeducedType()) {
9932 Diag(T->getTypeLoc().getBeginLoc(),
9933 diag::err_auto_not_allowed_var_inst);
9934 return true;
9935 }
9936
9937 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9938 // C++1y [temp.explicit]p3:
9939 // If the explicit instantiation is for a variable, the unqualified-id
9940 // in the declaration shall be a template-id.
9941 Diag(D.getIdentifierLoc(),
9942 diag::err_explicit_instantiation_without_template_id)
9943 << PrevTemplate;
9944 Diag(PrevTemplate->getLocation(),
9945 diag::note_explicit_instantiation_here);
9946 return true;
9947 }
9948
9949 // Translate the parser's template argument list into our AST format.
9950 TemplateArgumentListInfo TemplateArgs =
9951 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9952
9953 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9954 D.getIdentifierLoc(), TemplateArgs);
9955 if (Res.isInvalid())
9956 return true;
9957
9958 if (!Res.isUsable()) {
9959 // We somehow specified dependent template arguments in an explicit
9960 // instantiation. This should probably only happen during error
9961 // recovery.
9962 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
9963 return true;
9964 }
9965
9966 // Ignore access control bits, we don't need them for redeclaration
9967 // checking.
9968 Prev = cast<VarDecl>(Res.get());
9969 }
9970
9971 // C++0x [temp.explicit]p2:
9972 // If the explicit instantiation is for a member function, a member class
9973 // or a static data member of a class template specialization, the name of
9974 // the class template specialization in the qualified-id for the member
9975 // name shall be a simple-template-id.
9976 //
9977 // C++98 has the same restriction, just worded differently.
9978 //
9979 // This does not apply to variable template specializations, where the
9980 // template-id is in the unqualified-id instead.
9981 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9982 Diag(D.getIdentifierLoc(),
9983 diag::ext_explicit_instantiation_without_qualified_id)
9984 << Prev << D.getCXXScopeSpec().getRange();
9985
9986 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9987
9988 // Verify that it is okay to explicitly instantiate here.
9991 bool HasNoEffect = false;
9992 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9993 PrevTSK, POI, HasNoEffect))
9994 return true;
9995
9996 if (!HasNoEffect) {
9997 // Instantiate static data member or variable template.
9998 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9999 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10000 VTSD->setExternKeywordLoc(ExternLoc);
10001 VTSD->setTemplateKeywordLoc(TemplateLoc);
10002 }
10003
10004 // Merge attributes.
10005 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10006 if (PrevTemplate)
10007 ProcessAPINotes(Prev);
10008
10010 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10011 }
10012
10013 // Check the new variable specialization against the parsed input.
10014 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10015 Diag(T->getTypeLoc().getBeginLoc(),
10016 diag::err_invalid_var_template_spec_type)
10017 << 0 << PrevTemplate << R << Prev->getType();
10018 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10019 << 2 << PrevTemplate->getDeclName();
10020 return true;
10021 }
10022
10023 // FIXME: Create an ExplicitInstantiation node?
10024 return (Decl*) nullptr;
10025 }
10026
10027 // If the declarator is a template-id, translate the parser's template
10028 // argument list into our AST format.
10029 bool HasExplicitTemplateArgs = false;
10030 TemplateArgumentListInfo TemplateArgs;
10031 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10032 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10033 HasExplicitTemplateArgs = true;
10034 }
10035
10036 // C++ [temp.explicit]p1:
10037 // A [...] function [...] can be explicitly instantiated from its template.
10038 // A member function [...] of a class template can be explicitly
10039 // instantiated from the member definition associated with its class
10040 // template.
10041 UnresolvedSet<8> TemplateMatches;
10042 FunctionDecl *NonTemplateMatch = nullptr;
10043 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10044 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10045 P != PEnd; ++P) {
10046 NamedDecl *Prev = *P;
10047 if (!HasExplicitTemplateArgs) {
10048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10049 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10050 /*AdjustExceptionSpec*/true);
10051 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10052 if (Method->getPrimaryTemplate()) {
10053 TemplateMatches.addDecl(Method, P.getAccess());
10054 } else {
10055 // FIXME: Can this assert ever happen? Needs a test.
10056 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10057 NonTemplateMatch = Method;
10058 }
10059 }
10060 }
10061 }
10062
10063 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10064 if (!FunTmpl)
10065 continue;
10066
10067 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10068 FunctionDecl *Specialization = nullptr;
10070 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10071 Specialization, Info);
10073 // Keep track of almost-matches.
10074 FailedCandidates.addCandidate()
10075 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10076 MakeDeductionFailureInfo(Context, TDK, Info));
10077 (void)TDK;
10078 continue;
10079 }
10080
10081 // Target attributes are part of the cuda function signature, so
10082 // the cuda target of the instantiated function must match that of its
10083 // template. Given that C++ template deduction does not take
10084 // target attributes into account, we reject candidates here that
10085 // have a different target.
10086 if (LangOpts.CUDA &&
10088 /* IgnoreImplicitHDAttr = */ true) !=
10089 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10090 FailedCandidates.addCandidate().set(
10091 P.getPair(), FunTmpl->getTemplatedDecl(),
10094 continue;
10095 }
10096
10097 TemplateMatches.addDecl(Specialization, P.getAccess());
10098 }
10099
10100 FunctionDecl *Specialization = NonTemplateMatch;
10101 if (!Specialization) {
10102 // Find the most specialized function template specialization.
10104 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10105 D.getIdentifierLoc(),
10106 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10107 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10108 PDiag(diag::note_explicit_instantiation_candidate));
10109
10110 if (Result == TemplateMatches.end())
10111 return true;
10112
10113 // Ignore access control bits, we don't need them for redeclaration checking.
10114 Specialization = cast<FunctionDecl>(*Result);
10115 }
10116
10117 // C++11 [except.spec]p4
10118 // In an explicit instantiation an exception-specification may be specified,
10119 // but is not required.
10120 // If an exception-specification is specified in an explicit instantiation
10121 // directive, it shall be compatible with the exception-specifications of
10122 // other declarations of that function.
10123 if (auto *FPT = R->getAs<FunctionProtoType>())
10124 if (FPT->hasExceptionSpec()) {
10125 unsigned DiagID =
10126 diag::err_mismatched_exception_spec_explicit_instantiation;
10127 if (getLangOpts().MicrosoftExt)
10128 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10130 PDiag(DiagID) << Specialization->getType(),
10131 PDiag(diag::note_explicit_instantiation_here),
10132 Specialization->getType()->getAs<FunctionProtoType>(),
10133 Specialization->getLocation(), FPT, D.getBeginLoc());
10134 // In Microsoft mode, mismatching exception specifications just cause a
10135 // warning.
10136 if (!getLangOpts().MicrosoftExt && Result)
10137 return true;
10138 }
10139
10140 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10141 Diag(D.getIdentifierLoc(),
10142 diag::err_explicit_instantiation_member_function_not_instantiated)
10144 << (Specialization->getTemplateSpecializationKind() ==
10146 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10147 return true;
10148 }
10149
10150 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10151 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10152 PrevDecl = Specialization;
10153
10154 if (PrevDecl) {
10155 bool HasNoEffect = false;
10156 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10157 PrevDecl,
10159 PrevDecl->getPointOfInstantiation(),
10160 HasNoEffect))
10161 return true;
10162
10163 // FIXME: We may still want to build some representation of this
10164 // explicit specialization.
10165 if (HasNoEffect)
10166 return (Decl*) nullptr;
10167 }
10168
10169 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10170 // functions
10171 // valarray<size_t>::valarray(size_t) and
10172 // valarray<size_t>::~valarray()
10173 // that it declared to have internal linkage with the internal_linkage
10174 // attribute. Ignore the explicit instantiation declaration in this case.
10175 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10177 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10178 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10179 RD->isInStdNamespace())
10180 return (Decl*) nullptr;
10181 }
10182
10183 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10185
10186 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10187 // instantiation declarations.
10189 Specialization->hasAttr<DLLImportAttr>() &&
10192
10193 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10194
10195 if (Specialization->isDefined()) {
10196 // Let the ASTConsumer know that this function has been explicitly
10197 // instantiated now, and its linkage might have changed.
10199 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10200 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10201
10202 // C++0x [temp.explicit]p2:
10203 // If the explicit instantiation is for a member function, a member class
10204 // or a static data member of a class template specialization, the name of
10205 // the class template specialization in the qualified-id for the member
10206 // name shall be a simple-template-id.
10207 //
10208 // C++98 has the same restriction, just worded differently.
10209 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10210 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10211 D.getCXXScopeSpec().isSet() &&
10212 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10213 Diag(D.getIdentifierLoc(),
10214 diag::ext_explicit_instantiation_without_qualified_id)
10215 << Specialization << D.getCXXScopeSpec().getRange();
10216
10218 *this,
10219 FunTmpl ? (NamedDecl *)FunTmpl
10220 : Specialization->getInstantiatedFromMemberFunction(),
10221 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10222
10223 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10224 return (Decl*) nullptr;
10225}
10226
10228 const CXXScopeSpec &SS,
10229 const IdentifierInfo *Name,
10230 SourceLocation TagLoc,
10231 SourceLocation NameLoc) {
10232 // This has to hold, because SS is expected to be defined.
10233 assert(Name && "Expected a name in a dependent tag");
10234
10235 NestedNameSpecifier *NNS = SS.getScopeRep();
10236 if (!NNS)
10237 return true;
10238
10240
10241 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10242 Diag(NameLoc, diag::err_dependent_tag_decl)
10243 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10244 << SS.getRange();
10245 return true;
10246 }
10247
10248 // Create the resulting type.
10250 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10251
10252 // Create type-source location information for this type.
10253 TypeLocBuilder TLB;
10255 TL.setElaboratedKeywordLoc(TagLoc);
10257 TL.setNameLoc(NameLoc);
10259}
10260
10262 const CXXScopeSpec &SS,
10263 const IdentifierInfo &II,
10264 SourceLocation IdLoc,
10265 ImplicitTypenameContext IsImplicitTypename) {
10266 if (SS.isInvalid())
10267 return true;
10268
10269 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10270 Diag(TypenameLoc,
10272 diag::warn_cxx98_compat_typename_outside_of_template :
10273 diag::ext_typename_outside_of_template)
10274 << FixItHint::CreateRemoval(TypenameLoc);
10275
10277 TypeSourceInfo *TSI = nullptr;
10278 QualType T =
10279 CheckTypenameType((TypenameLoc.isValid() ||
10280 IsImplicitTypename == ImplicitTypenameContext::Yes)
10283 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10284 /*DeducedTSTContext=*/true);
10285 if (T.isNull())
10286 return true;
10287 return CreateParsedType(T, TSI);
10288}
10289
10292 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10293 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10294 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10295 ASTTemplateArgsPtr TemplateArgsIn,
10296 SourceLocation RAngleLoc) {
10297 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10298 Diag(TypenameLoc,
10300 diag::warn_cxx98_compat_typename_outside_of_template :
10301 diag::ext_typename_outside_of_template)
10302 << FixItHint::CreateRemoval(TypenameLoc);
10303
10304 // Strangely, non-type results are not ignored by this lookup, so the
10305 // program is ill-formed if it finds an injected-class-name.
10306 if (TypenameLoc.isValid()) {
10307 auto *LookupRD =
10308 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10309 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10310 Diag(TemplateIILoc,
10311 diag::ext_out_of_line_qualified_id_type_names_constructor)
10312 << TemplateII << 0 /*injected-class-name used as template name*/
10313 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10314 }
10315 }
10316
10317 // Translate the parser's template argument list in our AST format.
10318 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10319 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10320
10321 TemplateName Template = TemplateIn.get();
10322 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10323 // Construct a dependent template specialization type.
10324 assert(DTN && "dependent template has non-dependent name?");
10325 assert(DTN->getQualifier() == SS.getScopeRep());
10326
10327 if (!DTN->isIdentifier()) {
10328 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10329 NoteAllFoundTemplates(Template);
10330 return true;
10331 }
10332
10334 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10335 DTN->getIdentifier(), TemplateArgs.arguments());
10336
10337 // Create source-location information for this type.
10338 TypeLocBuilder Builder;
10341 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10343 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10344 SpecTL.setTemplateNameLoc(TemplateIILoc);
10345 SpecTL.setLAngleLoc(LAngleLoc);
10346 SpecTL.setRAngleLoc(RAngleLoc);
10347 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10348 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10349 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10350 }
10351
10352 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10353 if (T.isNull())
10354 return true;
10355
10356 // Provide source-location information for the template specialization type.
10357 TypeLocBuilder Builder;
10359 = Builder.push<TemplateSpecializationTypeLoc>(T);
10360 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10361 SpecTL.setTemplateNameLoc(TemplateIILoc);
10362 SpecTL.setLAngleLoc(LAngleLoc);
10363 SpecTL.setRAngleLoc(RAngleLoc);
10364 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10365 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10366
10368 SS.getScopeRep(), T);
10369 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10370 TL.setElaboratedKeywordLoc(TypenameLoc);
10372
10373 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10374 return CreateParsedType(T, TSI);
10375}
10376
10377/// Determine whether this failed name lookup should be treated as being
10378/// disabled by a usage of std::enable_if.
10380 SourceRange &CondRange, Expr *&Cond) {
10381 // We must be looking for a ::type...
10382 if (!II.isStr("type"))
10383 return false;
10384
10385 // ... within an explicitly-written template specialization...
10386 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10387 return false;
10388 TypeLoc EnableIfTy = NNS.getTypeLoc();
10389 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10391 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10392 return false;
10393 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10394
10395 // ... which names a complete class template declaration...
10396 const TemplateDecl *EnableIfDecl =
10397 EnableIfTST->getTemplateName().getAsTemplateDecl();
10398 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10399 return false;
10400
10401 // ... called "enable_if".
10402 const IdentifierInfo *EnableIfII =
10403 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10404 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10405 return false;
10406
10407 // Assume the first template argument is the condition.
10408 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10409
10410 // Dig out the condition.
10411 Cond = nullptr;
10412 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10414 return true;
10415
10416 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10417
10418 // Ignore Boolean literals; they add no value.
10419 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10420 Cond = nullptr;
10421
10422 return true;
10423}
10424
10427 SourceLocation KeywordLoc,
10428 NestedNameSpecifierLoc QualifierLoc,
10429 const IdentifierInfo &II,
10430 SourceLocation IILoc,
10431 TypeSourceInfo **TSI,
10432 bool DeducedTSTContext) {
10433 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10434 DeducedTSTContext);
10435 if (T.isNull())
10436 return QualType();
10437
10439 if (isa<DependentNameType>(T)) {
10441 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10442 TL.setElaboratedKeywordLoc(KeywordLoc);
10443 TL.setQualifierLoc(QualifierLoc);
10444 TL.setNameLoc(IILoc);
10445 } else {
10446 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10447 TL.setElaboratedKeywordLoc(KeywordLoc);
10448 TL.setQualifierLoc(QualifierLoc);
10449 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10450 }
10451 return T;
10452}
10453
10454/// Build the type that describes a C++ typename specifier,
10455/// e.g., "typename T::type".
10458 SourceLocation KeywordLoc,
10459 NestedNameSpecifierLoc QualifierLoc,
10460 const IdentifierInfo &II,
10461 SourceLocation IILoc, bool DeducedTSTContext) {
10462 CXXScopeSpec SS;
10463 SS.Adopt(QualifierLoc);
10464
10465 DeclContext *Ctx = nullptr;
10466 if (QualifierLoc) {
10467 Ctx = computeDeclContext(SS);
10468 if (!Ctx) {
10469 // If the nested-name-specifier is dependent and couldn't be
10470 // resolved to a type, build a typename type.
10471 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10472 return Context.getDependentNameType(Keyword,
10473 QualifierLoc.getNestedNameSpecifier(),
10474 &II);
10475 }
10476
10477 // If the nested-name-specifier refers to the current instantiation,
10478 // the "typename" keyword itself is superfluous. In C++03, the
10479 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10480 // allows such extraneous "typename" keywords, and we retroactively
10481 // apply this DR to C++03 code with only a warning. In any case we continue.
10482
10483 if (RequireCompleteDeclContext(SS, Ctx))
10484 return QualType();
10485 }
10486
10487 DeclarationName Name(&II);
10488 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10489 if (Ctx)
10490 LookupQualifiedName(Result, Ctx, SS);
10491 else
10492 LookupName(Result, CurScope);
10493 unsigned DiagID = 0;
10494 Decl *Referenced = nullptr;
10495 switch (Result.getResultKind()) {
10497 // If we're looking up 'type' within a template named 'enable_if', produce
10498 // a more specific diagnostic.
10499 SourceRange CondRange;
10500 Expr *Cond = nullptr;
10501 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10502 // If we have a condition, narrow it down to the specific failed
10503 // condition.
10504 if (Cond) {
10505 Expr *FailedCond;
10506 std::string FailedDescription;
10507 std::tie(FailedCond, FailedDescription) =
10509
10510 Diag(FailedCond->getExprLoc(),
10511 diag::err_typename_nested_not_found_requirement)
10512 << FailedDescription
10513 << FailedCond->getSourceRange();
10514 return QualType();
10515 }
10516
10517 Diag(CondRange.getBegin(),
10518 diag::err_typename_nested_not_found_enable_if)
10519 << Ctx << CondRange;
10520 return QualType();
10521 }
10522
10523 DiagID = Ctx ? diag::err_typename_nested_not_found
10524 : diag::err_unknown_typename;
10525 break;
10526 }
10527
10529 // We found a using declaration that is a value. Most likely, the using
10530 // declaration itself is meant to have the 'typename' keyword.
10531 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10532 IILoc);
10533 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10534 << Name << Ctx << FullRange;
10535 if (UnresolvedUsingValueDecl *Using
10536 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10537 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10538 Diag(Loc, diag::note_using_value_decl_missing_typename)
10539 << FixItHint::CreateInsertion(Loc, "typename ");
10540 }
10541 }
10542 // Fall through to create a dependent typename type, from which we can recover
10543 // better.
10544 [[fallthrough]];
10545
10547 // Okay, it's a member of an unknown instantiation.
10548 return Context.getDependentNameType(Keyword,
10549 QualifierLoc.getNestedNameSpecifier(),
10550 &II);
10551
10553 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10554 // C++ [class.qual]p2:
10555 // In a lookup in which function names are not ignored and the
10556 // nested-name-specifier nominates a class C, if the name specified
10557 // after the nested-name-specifier, when looked up in C, is the
10558 // injected-class-name of C [...] then the name is instead considered
10559 // to name the constructor of class C.
10560 //
10561 // Unlike in an elaborated-type-specifier, function names are not ignored
10562 // in typename-specifier lookup. However, they are ignored in all the
10563 // contexts where we form a typename type with no keyword (that is, in
10564 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10565 //
10566 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10567 // ignore functions, but that appears to be an oversight.
10568 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10569 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10570 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10571 FoundRD->isInjectedClassName() &&
10572 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10573 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10574 << &II << 1 << 0 /*'typename' keyword used*/;
10575
10576 // We found a type. Build an ElaboratedType, since the
10577 // typename-specifier was just sugar.
10578 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10579 return Context.getElaboratedType(Keyword,
10580 QualifierLoc.getNestedNameSpecifier(),
10582 }
10583
10584 // C++ [dcl.type.simple]p2:
10585 // A type-specifier of the form
10586 // typename[opt] nested-name-specifier[opt] template-name
10587 // is a placeholder for a deduced class type [...].
10588 if (getLangOpts().CPlusPlus17) {
10589 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10590 if (!DeducedTSTContext) {
10591 QualType T(QualifierLoc
10592 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10593 : nullptr, 0);
10594 if (!T.isNull())
10595 Diag(IILoc, diag::err_dependent_deduced_tst)
10597 else
10598 Diag(IILoc, diag::err_deduced_tst)
10601 return QualType();
10602 }
10604 Keyword, QualifierLoc.getNestedNameSpecifier(),
10606 QualType(), false));
10607 }
10608 }
10609
10610 DiagID = Ctx ? diag::err_typename_nested_not_type
10611 : diag::err_typename_not_type;
10612 Referenced = Result.getFoundDecl();
10613 break;
10614
10616 DiagID = Ctx ? diag::err_typename_nested_not_type
10617 : diag::err_typename_not_type;
10618 Referenced = *Result.begin();
10619 break;
10620
10622 return QualType();
10623 }
10624
10625 // If we get here, it's because name lookup did not find a
10626 // type. Emit an appropriate diagnostic and return an error.
10627 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10628 IILoc);
10629 if (Ctx)
10630 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10631 else
10632 Diag(IILoc, DiagID) << FullRange << Name;
10633 if (Referenced)
10634 Diag(Referenced->getLocation(),
10635 Ctx ? diag::note_typename_member_refers_here
10636 : diag::note_typename_refers_here)
10637 << Name;
10638 return QualType();
10639}
10640
10641namespace {
10642 // See Sema::RebuildTypeInCurrentInstantiation
10643 class CurrentInstantiationRebuilder
10644 : public TreeTransform<CurrentInstantiationRebuilder> {
10646 DeclarationName Entity;
10647
10648 public:
10650
10651 CurrentInstantiationRebuilder(Sema &SemaRef,
10653 DeclarationName Entity)
10654 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10655 Loc(Loc), Entity(Entity) { }
10656
10657 /// Determine whether the given type \p T has already been
10658 /// transformed.
10659 ///
10660 /// For the purposes of type reconstruction, a type has already been
10661 /// transformed if it is NULL or if it is not dependent.
10662 bool AlreadyTransformed(QualType T) {
10663 return T.isNull() || !T->isInstantiationDependentType();
10664 }
10665
10666 /// Returns the location of the entity whose type is being
10667 /// rebuilt.
10668 SourceLocation getBaseLocation() { return Loc; }
10669
10670 /// Returns the name of the entity whose type is being rebuilt.
10671 DeclarationName getBaseEntity() { return Entity; }
10672
10673 /// Sets the "base" location and entity when that
10674 /// information is known based on another transformation.
10675 void setBase(SourceLocation Loc, DeclarationName Entity) {
10676 this->Loc = Loc;
10677 this->Entity = Entity;
10678 }
10679
10680 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10681 // Lambdas never need to be transformed.
10682 return E;
10683 }
10684 };
10685} // end anonymous namespace
10686
10689 DeclarationName Name) {
10690 if (!T || !T->getType()->isInstantiationDependentType())
10691 return T;
10692
10693 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10694 return Rebuilder.TransformType(T);
10695}
10696
10698 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10699 DeclarationName());
10700 return Rebuilder.TransformExpr(E);
10701}
10702
10704 if (SS.isInvalid())
10705 return true;
10706
10708 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10709 DeclarationName());
10711 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10712 if (!Rebuilt)
10713 return true;
10714
10715 SS.Adopt(Rebuilt);
10716 return false;
10717}
10718
10720 TemplateParameterList *Params) {
10721 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10722 Decl *Param = Params->getParam(I);
10723
10724 // There is nothing to rebuild in a type parameter.
10725 if (isa<TemplateTypeParmDecl>(Param))
10726 continue;
10727
10728 // Rebuild the template parameter list of a template template parameter.
10730 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10732 TTP->getTemplateParameters()))
10733 return true;
10734
10735 continue;
10736 }
10737
10738 // Rebuild the type of a non-type template parameter.
10739 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10740 TypeSourceInfo *NewTSI
10742 NTTP->getLocation(),
10743 NTTP->getDeclName());
10744 if (!NewTSI)
10745 return true;
10746
10747 if (NewTSI->getType()->isUndeducedType()) {
10748 // C++17 [temp.dep.expr]p3:
10749 // An id-expression is type-dependent if it contains
10750 // - an identifier associated by name lookup with a non-type
10751 // template-parameter declared with a type that contains a
10752 // placeholder type (7.1.7.4),
10753 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
10754 }
10755
10756 if (NewTSI != NTTP->getTypeSourceInfo()) {
10757 NTTP->setTypeSourceInfo(NewTSI);
10758 NTTP->setType(NewTSI->getType());
10759 }
10760 }
10761
10762 return false;
10763}
10764
10765std::string
10767 const TemplateArgumentList &Args) {
10768 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10769}
10770
10771std::string
10773 const TemplateArgument *Args,
10774 unsigned NumArgs) {
10775 SmallString<128> Str;
10776 llvm::raw_svector_ostream Out(Str);
10777
10778 if (!Params || Params->size() == 0 || NumArgs == 0)
10779 return std::string();
10780
10781 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10782 if (I >= NumArgs)
10783 break;
10784
10785 if (I == 0)
10786 Out << "[with ";
10787 else
10788 Out << ", ";
10789
10790 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10791 Out << Id->getName();
10792 } else {
10793 Out << '$' << I;
10794 }
10795
10796 Out << " = ";
10797 Args[I].print(getPrintingPolicy(), Out,
10799 getPrintingPolicy(), Params, I));
10800 }
10801
10802 Out << ']';
10803 return std::string(Out.str());
10804}
10805
10807 CachedTokens &Toks) {
10808 if (!FD)
10809 return;
10810
10811 auto LPT = std::make_unique<LateParsedTemplate>();
10812
10813 // Take tokens to avoid allocations
10814 LPT->Toks.swap(Toks);
10815 LPT->D = FnD;
10816 LPT->FPO = getCurFPFeatures();
10817 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10818
10819 FD->setLateTemplateParsed(true);
10820}
10821
10823 if (!FD)
10824 return;
10825 FD->setLateTemplateParsed(false);
10826}
10827
10829 DeclContext *DC = CurContext;
10830
10831 while (DC) {
10832 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10833 const FunctionDecl *FD = RD->isLocalClass();
10834 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10835 } else if (DC->isTranslationUnit() || DC->isNamespace())
10836 return false;
10837
10838 DC = DC->getParent();
10839 }
10840 return false;
10841}
10842
10843namespace {
10844/// Walk the path from which a declaration was instantiated, and check
10845/// that every explicit specialization along that path is visible. This enforces
10846/// C++ [temp.expl.spec]/6:
10847///
10848/// If a template, a member template or a member of a class template is
10849/// explicitly specialized then that specialization shall be declared before
10850/// the first use of that specialization that would cause an implicit
10851/// instantiation to take place, in every translation unit in which such a
10852/// use occurs; no diagnostic is required.
10853///
10854/// and also C++ [temp.class.spec]/1:
10855///
10856/// A partial specialization shall be declared before the first use of a
10857/// class template specialization that would make use of the partial
10858/// specialization as the result of an implicit or explicit instantiation
10859/// in every translation unit in which such a use occurs; no diagnostic is
10860/// required.
10861class ExplicitSpecializationVisibilityChecker {
10862 Sema &S;
10866
10867public:
10868 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
10870 : S(S), Loc(Loc), Kind(Kind) {}
10871
10872 void check(NamedDecl *ND) {
10873 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10874 return checkImpl(FD);
10875 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10876 return checkImpl(RD);
10877 if (auto *VD = dyn_cast<VarDecl>(ND))
10878 return checkImpl(VD);
10879 if (auto *ED = dyn_cast<EnumDecl>(ND))
10880 return checkImpl(ED);
10881 }
10882
10883private:
10884 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10885 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10886 : Sema::MissingImportKind::ExplicitSpecialization;
10887 const bool Recover = true;
10888
10889 // If we got a custom set of modules (because only a subset of the
10890 // declarations are interesting), use them, otherwise let
10891 // diagnoseMissingImport intelligently pick some.
10892 if (Modules.empty())
10893 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10894 else
10895 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10896 }
10897
10898 bool CheckMemberSpecialization(const NamedDecl *D) {
10899 return Kind == Sema::AcceptableKind::Visible
10902 }
10903
10904 bool CheckExplicitSpecialization(const NamedDecl *D) {
10905 return Kind == Sema::AcceptableKind::Visible
10908 }
10909
10910 bool CheckDeclaration(const NamedDecl *D) {
10911 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
10913 }
10914
10915 // Check a specific declaration. There are three problematic cases:
10916 //
10917 // 1) The declaration is an explicit specialization of a template
10918 // specialization.
10919 // 2) The declaration is an explicit specialization of a member of an
10920 // templated class.
10921 // 3) The declaration is an instantiation of a template, and that template
10922 // is an explicit specialization of a member of a templated class.
10923 //
10924 // We don't need to go any deeper than that, as the instantiation of the
10925 // surrounding class / etc is not triggered by whatever triggered this
10926 // instantiation, and thus should be checked elsewhere.
10927 template<typename SpecDecl>
10928 void checkImpl(SpecDecl *Spec) {
10929 bool IsHiddenExplicitSpecialization = false;
10930 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10931 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
10932 ? !CheckMemberSpecialization(Spec)
10933 : !CheckExplicitSpecialization(Spec);
10934 } else {
10935 checkInstantiated(Spec);
10936 }
10937
10938 if (IsHiddenExplicitSpecialization)
10939 diagnose(Spec->getMostRecentDecl(), false);
10940 }
10941
10942 void checkInstantiated(FunctionDecl *FD) {
10943 if (auto *TD = FD->getPrimaryTemplate())
10944 checkTemplate(TD);
10945 }
10946
10947 void checkInstantiated(CXXRecordDecl *RD) {
10948 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10949 if (!SD)
10950 return;
10951
10952 auto From = SD->getSpecializedTemplateOrPartial();
10953 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10954 checkTemplate(TD);
10955 else if (auto *TD =
10956 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10957 if (!CheckDeclaration(TD))
10958 diagnose(TD, true);
10959 checkTemplate(TD);
10960 }
10961 }
10962
10963 void checkInstantiated(VarDecl *RD) {
10964 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10965 if (!SD)
10966 return;
10967
10968 auto From = SD->getSpecializedTemplateOrPartial();
10969 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10970 checkTemplate(TD);
10971 else if (auto *TD =
10972 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10973 if (!CheckDeclaration(TD))
10974 diagnose(TD, true);
10975 checkTemplate(TD);
10976 }
10977 }
10978
10979 void checkInstantiated(EnumDecl *FD) {}
10980
10981 template<typename TemplDecl>
10982 void checkTemplate(TemplDecl *TD) {
10983 if (TD->isMemberSpecialization()) {
10984 if (!CheckMemberSpecialization(TD))
10985 diagnose(TD->getMostRecentDecl(), false);
10986 }
10987 }
10988};
10989} // end anonymous namespace
10990
10992 if (!getLangOpts().Modules)
10993 return;
10994
10995 ExplicitSpecializationVisibilityChecker(*this, Loc,
10997 .check(Spec);
10998}
10999
11001 NamedDecl *Spec) {
11002 if (!getLangOpts().CPlusPlusModules)
11003 return checkSpecializationVisibility(Loc, Spec);
11004
11005 ExplicitSpecializationVisibilityChecker(*this, Loc,
11007 .check(Spec);
11008}
11009
11012 return N->getLocation();
11013 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11015 return FD->getLocation();
11018 return N->getLocation();
11019 }
11020 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11021 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11022 continue;
11023 return CSC.PointOfInstantiation;
11024 }
11025 return N->getLocation();
11026}
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
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1152
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:1143
This file declares semantic analysis for CUDA constructs.
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6806
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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 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 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.
Defines utilities for dealing with stack allocation and stack space.
static const TemplateArgument & getArgument(const TemplateArgument &A)
StateNode * Previous
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APSInt & getInt()
Definition: APValue.h:423
APSInt & getComplexIntImag()
Definition: APValue.h:461
ValueKind getKind() const
Definition: APValue.h:395
APFixedPoint & getFixedPoint()
Definition: APValue.h:445
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getVectorElt(unsigned I)
Definition: APValue.h:497
unsigned getVectorLength() const
Definition: APValue.h:505
bool isLValue() const
Definition: APValue.h:406
bool isMemberPointer() const
Definition: APValue.h:411
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isNullPointer() const
Definition: APValue.cpp:1010
APSInt & getComplexIntReal()
Definition: APValue.h:453
APFloat & getComplexFloatImag()
Definition: APValue.h:477
APFloat & getComplexFloatReal()
Definition: APValue.h:469
APFloat & getFloat()
Definition: APValue.h:437
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:113
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
bool hasSimilarType(QualType T1, QualType T2)
Determine if two types are similar, according to the C++ rules.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:663
TemplateName getCanonicalTemplateName(const TemplateName &Name) const
Retrieves the "canonical" template name that refers to a given template.
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType NullPtrTy
Definition: ASTContext.h:1145
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:1634
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
CanQualType UnresolvedTemplateTy
Definition: ASTContext.h:1146
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:1127
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType OverloadTy
Definition: ASTContext.h:1146
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2391
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:1612
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:778
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:1060
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:3710
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
Attr - This represents one attribute.
Definition: Attr.h:42
AutoTypeKeyword getAutoKeyword() const
Definition: TypeLoc.h:2189
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition: TypeLoc.h:2207
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:2257
ConceptDecl * getNamedConcept() const
Definition: TypeLoc.h:2231
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:2250
NamedDecl * getFoundDecl() const
Definition: TypeLoc.h:2225
DeclarationNameInfo getConceptNameInfo() const
Definition: TypeLoc.h:2237
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6368
bool isDecltypeAuto() const
Definition: Type.h:6391
A fixed int type of a specified bitwidth.
Definition: Type.h:7626
Pointer to a block type.
Definition: Type.h:3371
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:3000
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:2105
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3681
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:1531
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1879
base_class_range bases()
Definition: DeclCXX.h:619
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1908
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1904
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1886
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1919
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:531
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:126
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:152
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:132
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:3108
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
bool isTypeConcept() const
static ConceptDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, Expr *ConstraintExpr)
ConceptDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:88
static ConceptSpecializationExpr * Create(const ASTContext &C, ConceptReference *ConceptRef, ImplicitConceptSpecializationDecl *SpecDecl, const ConstraintSatisfaction *Satisfaction)
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4189
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:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2208
bool isFileContext() const
Definition: DeclBase.h:2150
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2019
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
Definition: DeclBase.cpp:1343
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
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:2001
bool isNamespace() const
Definition: DeclBase.h:2168
bool isTranslationUnit() const
Definition: DeclBase.h:2155
bool isRecord() const
Definition: DeclBase.h:2159
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1982
bool isFunctionOrMethod() const
Definition: DeclBase.h:2131
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1260
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1360
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1364
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1379
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:645
bool isNoreturnSpecified() const
Definition: DeclSpec.h:658
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SCS getStorageClassSpec() const
Definition: DeclSpec.h:498
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:659
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:651
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:499
bool isInlineSpecified() const
Definition: DeclSpec.h:634
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:508
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:646
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:833
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:637
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:648
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:834
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:1040
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1205
T * getAttr() const
Definition: DeclBase.h:579
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1196
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:825
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:249
Module * getImportedOwningModule() const
Get the imported owning module, if this decl is from an imported (non-local) module.
Definition: DeclBase.h:795
void dropAttrs()
Definition: DeclBase.cpp:1007
static DeclContext * castToDeclContext(const Decl *)
Definition: DeclBase.cpp:1055
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:1159
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2756
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:232
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
bool hasAttr() const
Definition: DeclBase.h:583
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
Kind getKind() const
Definition: DeclBase.h:448
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
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:766
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
Represents the type decltype(expr) (C++11).
Definition: Type.h:5745
Represents a C++17 deduced template specialization type.
Definition: Type.h:6416
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6334
bool isDeduced() const
Definition: Type.h:6356
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3881
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2423
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2403
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2412
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6836
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3321
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:529
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3823
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3921
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4248
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:550
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:547
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:553
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2472
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2492
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2460
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2516
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2508
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2524
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2500
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6888
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4043
bool isEmpty() const
Definition: TypeLoc.h:2365
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:2361
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3840
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4099
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4926
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
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:3075
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:3070
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:3050
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:3941
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:4083
Represents a member of a struct/union/class.
Definition: Decl.h:3030
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=std::nullopt)
Definition: DeclFriend.cpp:34
Represents a function declaration or definition.
Definition: Decl.h:1932
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4042
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:4348
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4150
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4009
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3605
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3981
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:4214
void setLateTemplateParsed(bool ILT=true)
State that this templated function will be late parsed.
Definition: Decl.h:2294
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4254
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3114
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
ArrayRef< QualType > param_types() const
Definition: Type.h:5382
Declaration of a template function.
Definition: DeclTemplate.h:957
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:467
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:542
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:553
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:525
QualType getReturnType() const
Definition: Type.h:4600
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:3675
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Represents a C array with an unspecified size.
Definition: Type.h:3725
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
Describes an C or C++ initializer list.
Definition: Expr.h:5029
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:7482
Describes an entity that is being initialized.
static InitializedEntity InitializeTemplateParameter(QualType T, NonTypeTemplateParmDecl *Param)
Create the initialization entity for a template parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6605
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3446
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:2934
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
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:4289
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
QualType getPointeeType() const
Definition: Type.h:3498
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:244
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
void 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:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
NamedDecl * getMostRecentDecl()
Definition: Decl.h:476
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:689
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1912
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
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:7336
Represents a pointer to an Objective C object.
Definition: Type.h:7392
Represents a class type in Objective C.
Definition: Type.h:7138
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
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4178
Represents a pack expansion of types.
Definition: Type.h:6953
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:250
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
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:7592
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
QualType getPointeeType() const
Definition: Type.h:3171
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A (possibly-)qualified type.
Definition: Type.h:941
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
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:7944
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
void * getAsOpaquePtr() const
Definition: Type.h:988
bool isCanonical() const
Definition: Type.h:7800
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7789
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
The collection of all-type qualifiers we support.
Definition: Type.h:319
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
void addConst()
Definition: Type.h:447
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:535
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3464
Represents a struct/union/class.
Definition: Decl.h:4141
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4332
Wrapper for source info for record types.
Definition: TypeLoc.h:741
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:865
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4974
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
QualType getPointeeType() const
Definition: Type.h:3420
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:262
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
@ 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:136
void inheritTargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD)
Copies target attributes from the template TD to the function FD.
Definition: SemaCUDA.cpp:1062
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13186
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8057
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:11092
SourceLocation getTemplateKeywordLoc() const
Definition: Sema.h:11100
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7233
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
Definition: SemaType.cpp:9024
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6321
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)
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13120
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12637
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:1557
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15265
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8995
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8999
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9007
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9002
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19378
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS)
SetMemberAccessSpecifier - Set the access specifier of a member.
Definition: SemaAccess.cpp:37
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:6074
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:9309
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:6059
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:1164
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...
Decl * ActOnConceptDefinition(Scope *S, MultiTemplateParamsArg TemplateParameterLists, const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr, const ParsedAttributesView &Attrs)
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:6202
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:16917
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic=false)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
void AddAlignmentAttributesForRecord(RecordDecl *RD)
AddAlignmentAttributesForRecord - Adds any needed alignment attributes to a the record decl,...
Definition: SemaAttr.cpp:53
bool RequireStructuralType(QualType T, SourceLocation Loc)
Require the given type to be a structural type, and diagnose if it is not.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1731
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
bool hasVisibleExplicitSpecialization(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if there is a visible declaration of D that is an explicit specialization declaration for a...
bool IsInsideALocalClassWithinATemplateFunction()
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:11063
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:11636
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11639
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11643
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:1002
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:5766
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:597
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:1495
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:600
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:1711
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:694
bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg, bool IsDeduced)
Check a template argument against its corresponding template template parameter.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:9252
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:908
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:16773
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2186
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:11053
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc, bool IsDeduced)
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:11778
@ TPL_TemplateTemplateParmMatch
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:11796
@ TPL_TemplateTemplateArgumentMatch
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:11807
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:11786
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:11817
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:11113
@ FoundFunctions
This is assumed to be a template name because lookup found one or more functions (but no function tem...
@ None
This is not assumed to be a template name.
@ FoundNothing
This is assumed to be a template name because lookup found nothing.
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
ArrayRef< InventedTemplateParameterInfo > getInventedParameterInfos() const
Definition: Sema.h:11046
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record)
Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
Definition: SemaAttr.cpp:167
FPOptions & getCurFPFeatures()
Definition: Sema.h:595
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, const MultiLevelTemplateArgumentList &TemplateArgs, SourceRange TemplateIDRange)
Ensure that the given template arguments satisfy the constraints associated with the given template,...
@ UPPC_PartialSpecialization
Partial specialization.
Definition: Sema.h:13919
@ UPPC_DefaultArgument
A default argument.
Definition: Sema.h:13907
@ UPPC_ExplicitSpecialization
Explicit specialization.
Definition: Sema.h:13916
@ UPPC_NonTypeTemplateParameterType
The type of a non-type template parameter.
Definition: Sema.h:13910
@ UPPC_TypeConstraint
A type constraint.
Definition: Sema.h:13934
const LangOptions & getLangOpts() const
Definition: Sema.h:593
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl, bool SupportedForCompatibility=false)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
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:1001
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:14345
const LangOptions & LangOpts
Definition: Sema.h:1000
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 ...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr, bool PartialOrderingTTP=false)
Check that the given template arguments can be provided to the given template, converting the argumen...
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:19790
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:8987
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:9348
bool hasExplicitCallingConv(QualType T)
Definition: SemaType.cpp:7983
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:16748
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
void AddPushedVisibilityAttribute(Decl *RD)
AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, add an appropriate visibility at...
Definition: SemaAttr.cpp:1216
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:9686
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:635
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3163
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:1137
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:14786
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5771
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
bool 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:1287
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4698
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:9007
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3839
@ NTK_TypeAliasTemplate
Definition: Sema.h:3847
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:215
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:14915
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:9393
RedeclarationKind forRedeclarationInCurContext() const
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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:10010
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:3077
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:1891
ASTConsumer & Consumer
Definition: Sema.h:1003
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)
@ 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:9470
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:5645
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:16957
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8885
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:11090
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:511
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:14821
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:11278
@ TPC_ClassTemplate
Definition: Sema.h:11279
@ TPC_FriendFunctionTemplate
Definition: Sema.h:11284
@ TPC_ClassTemplateMember
Definition: Sema.h:11282
@ TPC_FunctionTemplate
Definition: Sema.h:11281
@ TPC_FriendClassTemplate
Definition: Sema.h:11283
@ TPC_FriendFunctionTemplateDefinition
Definition: Sema.h:11285
@ TPC_TypeAliasTemplate
Definition: Sema.h:11286
@ TPC_VarTemplate
Definition: Sema.h:11280
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:1577
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:1562
ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs)
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2372
@ OOK_Outside
Definition: Sema.h:3865
void CheckConceptRedefinition(ConceptDecl *NewDecl, LookupResult &Previous, bool &AddToScope)
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5804
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:20889
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:1701
@ 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:2723
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:11055
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool hasReachableDeclaration(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine whether any declaration of an entity is reachable.
Definition: Sema.h:9318
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12481
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef< UnexpandedParameterPack > Unexpanded)
Diagnose unexpanded parameter packs.
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:6020
void inferNullableClassAttribute(CXXRecordDecl *CRD)
Add _Nullable attributes for std:: types.
Definition: SemaAttr.cpp:219
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8277
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4482
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6276
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6206
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3557
StringRef getKindName() const
Definition: Decl.h:3748
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4725
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4808
TagKind getTagKind() const
Definition: Decl.h:3752
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:4073
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:1256
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:283
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
SourceLocation getLocation() const
Definition: TemplateBase.h:563
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:623
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:616
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:578
SourceRange getSourceRange() const LLVM_READONLY
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:609
Expr * getSourceExpression() const
Definition: TemplateBase.h:584
Represents a template argument.
Definition: TemplateBase.h:61
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
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:394
bool hasAssociatedConstraints() const
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:426
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
bool hasAssociatedConstraints() const
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to form a template specialization.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
NamedDecl *const * const_iterator
Iterates through the template parameters in this list.
Definition: DeclTemplate.h:129
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
void getAssociatedConstraints(llvm::SmallVectorImpl< const Expr * > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
static bool shouldIncludeTypeForArgument(const PrintingPolicy &Policy, const TemplateParameterList *TPL, unsigned Idx)
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1687
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1663
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1695
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1704
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1671
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1679
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6473
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6539
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, ArrayRef< TemplateArgument > Converted)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:4262
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, bool Typename, TemplateParameterList *Params)
void removeDefaultArgument()
Removes the default argument of this template parameter.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getDepth() const
Retrieve the depth of the template parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:758
TemplateTypeParmDecl * getDecl() const
Definition: TypeLoc.h:760
unsigned getIndex() const
Definition: Type.h:6166
unsigned getDepth() const
Definition: Type.h:6165
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:3528
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:228
Represents a declaration of a type.
Definition: Decl.h:3363
const Type * getTypeForDecl() const
Definition: Decl.h:3387
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3390
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:742
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:5668
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5718
A container of type source information.
Definition: Type.h:7714
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:7725
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier.
Definition: TypeLoc.h:528
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
An operation on a type.
Definition: TypeVisitor.h:64
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:3148
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:3130
The base class of the type hierarchy.
Definition: Type.h:1829
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2416
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBooleanType() const
Definition: Type.h:8423
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2167
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2217
bool isRValueReferenceType() const
Definition: Type.h:8018
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8064
bool isPointerType() const
Definition: Type.h:7996
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isScalarType() const
Definition: Type.h:8394
bool isChar8Type() const
Definition: Type.cpp:2105
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
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:427
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8410
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2125
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:8142
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2777
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2680
bool isLValueReferenceType() const
Definition: Type.h:8014
bool isBitIntType() const
Definition: Type.h:8230
bool isStructuralType() const
Determine if this type is a structural type, per C++20 [temp.param]p7.
Definition: Type.cpp:2954
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isChar16Type() const
Definition: Type.cpp:2111
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
bool isMemberPointerType() const
Definition: Type.h:8046
bool isChar32Type() const
Definition: Type.cpp:2117
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2690
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4961
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:4580
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7992
bool isVectorType() const
Definition: Type.h:8104
bool isWideCharType() const
Definition: Type.cpp:2098
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
QualType getUnderlyingType() const
Definition: Decl.h:3460
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:2188
A unary type transform, which is a type constructed from another.
Definition: Type.h:5853
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:419
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5538
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3384
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
TLSKind getTLSKind() const
Definition: Decl.cpp:2150
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
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:2864
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:2765
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:2744
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2855
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...
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:3769
Represents a GCC generic vector type.
Definition: Type.h:3991
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
ImplicitTypenameContext
Definition: DeclSpec.h:1883
bool isa(CodeGen::Address addr)
Definition: Address.h:328
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:59
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Extern
Definition: Specifiers.h:248
@ TSCS_unspecified
Definition: Specifiers.h:233
@ CRK_None
Candidate is not a rewritten candidate.
Definition: Overload.h:91
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
@ Result
The result type of a method or function.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
TagUseKind
Definition: Sema.h:469
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
TagTypeKind
The kind of a tag type.
Definition: Type.h:6683
@ 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:312
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:309
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
CastKind
CastKind - The kind of operation required for a conversion.
std::optional< unsigned > getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
bool isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg, const NamedDecl *Param, ArrayRef< TemplateArgument > Args, unsigned Depth)
Make a best-effort determination of whether the type T can be produced by substituting Args into the ...
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:20
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
@ TNK_Dependent_template_name
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
@ TNK_Function_template
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
@ TNK_Non_template
The name does not refer to a template.
Definition: TemplateKinds.h:22
@ TNK_Undeclared_template
Lookup for the name failed, but we're assuming it was a template name anyway.
Definition: TemplateKinds.h:50
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:250
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1264
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:387
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6658
@ 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:120
@ AS_public
Definition: Specifiers.h:121
@ AS_none
Definition: Specifiers.h:124
#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
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:5058
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:12654
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12761
A stack object to be created when performing template instantiation.
Definition: Sema.h:12839
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12993
NamedDecl * Previous
Definition: Sema.h:374
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.