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"
12#include "clang/AST/ASTConcept.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclFriend.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/DynamicRecursiveASTVisitor.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/TypeVisitor.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/DiagnosticSema.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/EnterExpressionEvaluationContext.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "clang/Sema/TemplateDeduction.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
52SourceRange
53clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
74 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
90 getInventedParameterInfos()) {
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
106NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(Val: D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
146 return D;
147
148 return nullptr;
149}
150
151void Sema::FilterAcceptableTemplateNames(LookupResult &R,
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
163bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
178TemplateNameKind Sema::isTemplateName(Scope *S,
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
193 case UnqualifiedIdKind::IK_Identifier:
194 TName = DeclarationName(Name.Identifier);
195 break;
196
197 case UnqualifiedIdKind::IK_OperatorFunctionId:
198 TName = Context.DeclarationNames.getCXXOperatorName(
199 Op: Name.OperatorFunctionId.Operator);
200 break;
201
202 case UnqualifiedIdKind::IK_LiteralOperatorId:
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 ATK: &AssumedTemplate,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
227 ? TNK_Undeclared_template
228 : TNK_Function_template;
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
242 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
262 FilterAcceptableTemplateNames(R);
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
269 TemplateName Template;
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
280 R.suppressDiagnostics();
281 } else {
282 if (!D) {
283 D = getAsTemplateNameDecl(D: *R.begin());
284 assert(D && "unambiguous result is not a template name");
285 }
286
287 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
293 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
300 Template);
301 }
302
303 if (isa<FunctionTemplateDecl>(Val: TD)) {
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
307 R.suppressDiagnostics();
308 } else {
309 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
310 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
311 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
312 TemplateKind =
313 isa<TemplateTemplateParmDecl>(Val: TD)
314 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
315 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
316 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
317 : TNK_Type_template;
318 }
319 }
320
321 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
322 S->getTemplateParamParent() == nullptr)
323 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(P: Template);
328 return TemplateKind;
329}
330
331bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
345 R.suppressDiagnostics();
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
352 if (!TD || !getAsTypeTemplateDecl(D: TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
358 *Template = TemplateTy::make(P: Name);
359 }
360 return true;
361}
362
363bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
373 computeDeclContext(SS: *SS))
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
379 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
387bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
390 AssumedTemplateKind *ATK,
391 bool AllowTypoCorrection) {
392 if (ATK)
393 *ATK = AssumedTemplateKind::None;
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(T: ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
412 "Caller should have completed object type");
413
414 // Template names cannot appear inside an Objective-C class or object type
415 // or a vector type.
416 //
417 // FIXME: This is wrong. For example:
418 //
419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
420 // Vec<int> vi;
421 // vi.Vec<int>::~Vec<int>();
422 //
423 // ... should be accepted but we will not treat 'Vec' as a template name
424 // here. The right thing to do would be to check if the name is a valid
425 // vector component name, and look up a template name if not. And similarly
426 // for lookups into Objective-C class and object types, where the same
427 // problem can arise.
428 if (ObjectType->isObjCObjectOrInterfaceType() ||
429 ObjectType->isVectorType()) {
430 Found.clear();
431 return false;
432 }
433 } else if (SS.isNotEmpty()) {
434 // This nested-name-specifier occurs after another nested-name-specifier,
435 // so long into the context associated with the prior nested-name-specifier.
436 LookupCtx = computeDeclContext(SS, EnteringContext);
437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
438
439 // The declaration context must be complete.
440 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
441 return true;
442 }
443
444 bool ObjectTypeSearchedInScope = false;
445 bool AllowFunctionTemplatesInLookup = true;
446 if (LookupCtx) {
447 // Perform "qualified" name lookup into the declaration context we
448 // computed, which is either the type of the base of a member access
449 // expression or the declaration context associated with a prior
450 // nested-name-specifier.
451 LookupQualifiedName(R&: Found, LookupCtx);
452
453 // FIXME: The C++ standard does not clearly specify what happens in the
454 // case where the object type is dependent, and implementations vary. In
455 // Clang, we treat a name after a . or -> as a template-name if lookup
456 // finds a non-dependent member or member of the current instantiation that
457 // is a type template, or finds no such members and lookup in the context
458 // of the postfix-expression finds a type template. In the latter case, the
459 // name is nonetheless dependent, and we may resolve it to a member of an
460 // unknown specialization when we come to instantiate the template.
461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
462 }
463
464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
465 // C++ [basic.lookup.classref]p1:
466 // In a class member access expression (5.2.5), if the . or -> token is
467 // immediately followed by an identifier followed by a <, the
468 // identifier must be looked up to determine whether the < is the
469 // beginning of a template argument list (14.2) or a less-than operator.
470 // The identifier is first looked up in the class of the object
471 // expression. If the identifier is not found, it is then looked up in
472 // the context of the entire postfix-expression and shall name a class
473 // template.
474 if (S)
475 LookupName(R&: Found, S);
476
477 if (!ObjectType.isNull()) {
478 // FIXME: We should filter out all non-type templates here, particularly
479 // variable templates and concepts. But the exclusion of alias templates
480 // and template template parameters is a wording defect.
481 AllowFunctionTemplatesInLookup = false;
482 ObjectTypeSearchedInScope = true;
483 }
484
485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
486 }
487
488 if (Found.isAmbiguous())
489 return false;
490
491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
492 !RequiredTemplate.hasTemplateKeyword()) {
493 // C++2a [temp.names]p2:
494 // A name is also considered to refer to a template if it is an
495 // unqualified-id followed by a < and name lookup finds either one or more
496 // functions or finds nothing.
497 //
498 // To keep our behavior consistent, we apply the "finds nothing" part in
499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
500 // successfully form a call to an undeclared template-id.
501 bool AllFunctions =
502 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
503 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
504 });
505 if (AllFunctions || (Found.empty() && !IsDependent)) {
506 // If lookup found any functions, or if this is a name that can only be
507 // used for a function, then strongly assume this is a function
508 // template-id.
509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
510 ? AssumedTemplateKind::FoundNothing
511 : AssumedTemplateKind::FoundFunctions;
512 Found.clear();
513 return false;
514 }
515 }
516
517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
518 // If we did not find any names, and this is not a disambiguation, attempt
519 // to correct any typos.
520 DeclarationName Name = Found.getLookupName();
521 Found.clear();
522 // Simple filter callback that, for keywords, only accepts the C++ *_cast
523 DefaultFilterCCC FilterCCC{};
524 FilterCCC.WantTypeSpecifiers = false;
525 FilterCCC.WantExpressionKeywords = false;
526 FilterCCC.WantRemainingKeywords = false;
527 FilterCCC.WantCXXNamedCasts = true;
528 if (TypoCorrection Corrected = CorrectTypo(
529 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
530 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
531 if (auto *ND = Corrected.getFoundDecl())
532 Found.addDecl(D: ND);
533 FilterAcceptableTemplateNames(R&: Found);
534 if (Found.isAmbiguous()) {
535 Found.clear();
536 } else if (!Found.empty()) {
537 // Do not erase the typo-corrected result to avoid duplicated
538 // diagnostics.
539 AllowFunctionTemplatesInLookup = true;
540 Found.setLookupName(Corrected.getCorrection());
541 if (LookupCtx) {
542 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
543 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
544 Name.getAsString() == CorrectedStr;
545 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
546 << Name << LookupCtx << DroppedSpecifier
547 << SS.getRange());
548 } else {
549 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
550 }
551 }
552 }
553 }
554
555 NamedDecl *ExampleLookupResult =
556 Found.empty() ? nullptr : Found.getRepresentativeDecl();
557 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
558 if (Found.empty()) {
559 if (IsDependent) {
560 Found.setNotFoundInCurrentInstantiation();
561 return false;
562 }
563
564 // If a 'template' keyword was used, a lookup that finds only non-template
565 // names is an error.
566 if (ExampleLookupResult && RequiredTemplate) {
567 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
568 << Found.getLookupName() << SS.getRange()
569 << RequiredTemplate.hasTemplateKeyword()
570 << RequiredTemplate.getTemplateKeywordLoc();
571 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
572 DiagID: diag::note_template_kw_refers_to_non_template)
573 << Found.getLookupName();
574 return true;
575 }
576
577 return false;
578 }
579
580 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
581 !getLangOpts().CPlusPlus11) {
582 // C++03 [basic.lookup.classref]p1:
583 // [...] If the lookup in the class of the object expression finds a
584 // template, the name is also looked up in the context of the entire
585 // postfix-expression and [...]
586 //
587 // Note: C++11 does not perform this second lookup.
588 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
589 LookupOrdinaryName);
590 FoundOuter.setTemplateNameLookup(true);
591 LookupName(R&: FoundOuter, S);
592 // FIXME: We silently accept an ambiguous lookup here, in violation of
593 // [basic.lookup]/1.
594 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
595
596 NamedDecl *OuterTemplate;
597 if (FoundOuter.empty()) {
598 // - if the name is not found, the name found in the class of the
599 // object expression is used, otherwise
600 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
601 !(OuterTemplate =
602 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
603 // - if the name is found in the context of the entire
604 // postfix-expression and does not name a class template, the name
605 // found in the class of the object expression is used, otherwise
606 FoundOuter.clear();
607 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
608 // - if the name found is a class template, it must refer to the same
609 // entity as the one found in the class of the object expression,
610 // otherwise the program is ill-formed.
611 if (!Found.isSingleResult() ||
612 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
613 OuterTemplate->getCanonicalDecl()) {
614 Diag(Loc: Found.getNameLoc(),
615 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
616 << Found.getLookupName()
617 << ObjectType;
618 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
619 DiagID: diag::note_ambig_member_ref_object_type)
620 << ObjectType;
621 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
622 DiagID: diag::note_ambig_member_ref_scope);
623
624 // Recover by taking the template that we found in the object
625 // expression's type.
626 }
627 }
628 }
629
630 return false;
631}
632
633void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
634 SourceLocation Less,
635 SourceLocation Greater) {
636 if (TemplateName.isInvalid())
637 return;
638
639 DeclarationNameInfo NameInfo;
640 CXXScopeSpec SS;
641 LookupNameKind LookupKind;
642
643 DeclContext *LookupCtx = nullptr;
644 NamedDecl *Found = nullptr;
645 bool MissingTemplateKeyword = false;
646
647 // Figure out what name we looked up.
648 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
649 NameInfo = DRE->getNameInfo();
650 SS.Adopt(Other: DRE->getQualifierLoc());
651 LookupKind = LookupOrdinaryName;
652 Found = DRE->getFoundDecl();
653 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
654 NameInfo = ME->getMemberNameInfo();
655 SS.Adopt(Other: ME->getQualifierLoc());
656 LookupKind = LookupMemberName;
657 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
658 Found = ME->getMemberDecl();
659 } else if (auto *DSDRE =
660 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
661 NameInfo = DSDRE->getNameInfo();
662 SS.Adopt(Other: DSDRE->getQualifierLoc());
663 MissingTemplateKeyword = true;
664 } else if (auto *DSME =
665 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
666 NameInfo = DSME->getMemberNameInfo();
667 SS.Adopt(Other: DSME->getQualifierLoc());
668 MissingTemplateKeyword = true;
669 } else {
670 llvm_unreachable("unexpected kind of potential template name");
671 }
672
673 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
674 // was missing.
675 if (MissingTemplateKeyword) {
676 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
677 << NameInfo.getName() << SourceRange(Less, Greater);
678 return;
679 }
680
681 // Try to correct the name by looking for templates and C++ named casts.
682 struct TemplateCandidateFilter : CorrectionCandidateCallback {
683 Sema &S;
684 TemplateCandidateFilter(Sema &S) : S(S) {
685 WantTypeSpecifiers = false;
686 WantExpressionKeywords = false;
687 WantRemainingKeywords = false;
688 WantCXXNamedCasts = true;
689 };
690 bool ValidateCandidate(const TypoCorrection &Candidate) override {
691 if (auto *ND = Candidate.getCorrectionDecl())
692 return S.getAsTemplateNameDecl(D: ND);
693 return Candidate.isKeyword();
694 }
695
696 std::unique_ptr<CorrectionCandidateCallback> clone() override {
697 return std::make_unique<TemplateCandidateFilter>(args&: *this);
698 }
699 };
700
701 DeclarationName Name = NameInfo.getName();
702 TemplateCandidateFilter CCC(*this);
703 if (TypoCorrection Corrected =
704 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
705 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
706 auto *ND = Corrected.getFoundDecl();
707 if (ND)
708 ND = getAsTemplateNameDecl(D: ND);
709 if (ND || Corrected.isKeyword()) {
710 if (LookupCtx) {
711 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
712 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
713 Name.getAsString() == CorrectedStr;
714 diagnoseTypo(Correction: Corrected,
715 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
716 << Name << LookupCtx << DroppedSpecifier
717 << SS.getRange(), ErrorRecovery: false);
718 } else {
719 diagnoseTypo(Correction: Corrected,
720 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
721 << Name, ErrorRecovery: false);
722 }
723 if (Found)
724 Diag(Loc: Found->getLocation(),
725 DiagID: diag::note_non_template_in_template_id_found);
726 return;
727 }
728 }
729
730 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
731 << Name << SourceRange(Less, Greater);
732 if (Found)
733 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
734}
735
736ExprResult
737Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
738 SourceLocation TemplateKWLoc,
739 const DeclarationNameInfo &NameInfo,
740 bool isAddressOfOperand,
741 const TemplateArgumentListInfo *TemplateArgs) {
742 if (SS.isEmpty()) {
743 // FIXME: This codepath is only used by dependent unqualified names
744 // (e.g. a dependent conversion-function-id, or operator= once we support
745 // it). It doesn't quite do the right thing, and it will silently fail if
746 // getCurrentThisType() returns null.
747 QualType ThisType = getCurrentThisType();
748 if (ThisType.isNull())
749 return ExprError();
750
751 return CXXDependentScopeMemberExpr::Create(
752 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
753 /*IsArrow=*/!Context.getLangOpts().HLSL,
754 /*OperatorLoc=*/SourceLocation(),
755 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
756 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
757 }
758 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
759}
760
761ExprResult
762Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
763 SourceLocation TemplateKWLoc,
764 const DeclarationNameInfo &NameInfo,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
767 if (!SS.isValid())
768 return CreateRecoveryExpr(
769 Begin: SS.getBeginLoc(),
770 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
771
772 return DependentScopeDeclRefExpr::Create(
773 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
774 TemplateArgs);
775}
776
777ExprResult Sema::BuildSubstNonTypeTemplateParmExpr(
778 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
779 SourceLocation Loc, TemplateArgument Arg, UnsignedOrNone PackIndex,
780 bool Final) {
781 // The template argument itself might be an expression, in which case we just
782 // return that expression. This happens when substituting into an alias
783 // template.
784 Expr *Replacement;
785 bool refParam = true;
786 if (Arg.getKind() == TemplateArgument::Expression) {
787 Replacement = Arg.getAsExpr();
788 refParam = Replacement->isLValue();
789 if (refParam && Replacement->getType()->isRecordType()) {
790 QualType ParamType =
791 NTTP->isExpandedParameterPack()
792 ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex)
793 : NTTP->getType();
794 if (const auto *PET = dyn_cast<PackExpansionType>(Val&: ParamType))
795 ParamType = PET->getPattern();
796 refParam = ParamType->isReferenceType();
797 }
798 } else {
799 ExprResult result =
800 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
801 if (result.isInvalid())
802 return ExprError();
803 Replacement = result.get();
804 refParam = Arg.getNonTypeTemplateArgumentType()->isReferenceType();
805 }
806 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
807 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
808 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
809}
810
811bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
812 NamedDecl *Instantiation,
813 bool InstantiatedFromMember,
814 const NamedDecl *Pattern,
815 const NamedDecl *PatternDef,
816 TemplateSpecializationKind TSK,
817 bool Complain, bool *Unreachable) {
818 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
819 isa<VarDecl>(Instantiation));
820
821 bool IsEntityBeingDefined = false;
822 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
823 IsEntityBeingDefined = TD->isBeingDefined();
824
825 if (PatternDef && !IsEntityBeingDefined) {
826 NamedDecl *SuggestedDef = nullptr;
827 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
828 Suggested: &SuggestedDef,
829 /*OnlyNeedComplete*/ false)) {
830 if (Unreachable)
831 *Unreachable = true;
832 // If we're allowed to diagnose this and recover, do so.
833 bool Recover = Complain && !isSFINAEContext();
834 if (Complain)
835 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
836 MIK: Sema::MissingImportKind::Definition, Recover);
837 return !Recover;
838 }
839 return false;
840 }
841
842 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
843 return true;
844
845 CanQualType InstantiationTy;
846 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
847 InstantiationTy = Context.getCanonicalTagType(TD);
848 if (PatternDef) {
849 Diag(Loc: PointOfInstantiation,
850 DiagID: diag::err_template_instantiate_within_definition)
851 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
852 << InstantiationTy;
853 // Not much point in noting the template declaration here, since
854 // we're lexically inside it.
855 Instantiation->setInvalidDecl();
856 } else if (InstantiatedFromMember) {
857 if (isa<FunctionDecl>(Val: Instantiation)) {
858 Diag(Loc: PointOfInstantiation,
859 DiagID: diag::err_explicit_instantiation_undefined_member)
860 << /*member function*/ 1 << Instantiation->getDeclName()
861 << Instantiation->getDeclContext();
862 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
863 } else {
864 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
865 Diag(Loc: PointOfInstantiation,
866 DiagID: diag::err_implicit_instantiate_member_undefined)
867 << InstantiationTy;
868 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
869 }
870 } else {
871 if (isa<FunctionDecl>(Val: Instantiation)) {
872 Diag(Loc: PointOfInstantiation,
873 DiagID: diag::err_explicit_instantiation_undefined_func_template)
874 << Pattern;
875 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
876 } else if (isa<TagDecl>(Val: Instantiation)) {
877 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
878 << (TSK != TSK_ImplicitInstantiation)
879 << InstantiationTy;
880 NoteTemplateLocation(Decl: *Pattern);
881 } else {
882 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
883 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
884 Diag(Loc: PointOfInstantiation,
885 DiagID: diag::err_explicit_instantiation_undefined_var_template)
886 << Instantiation;
887 Instantiation->setInvalidDecl();
888 } else
889 Diag(Loc: PointOfInstantiation,
890 DiagID: diag::err_explicit_instantiation_undefined_member)
891 << /*static data member*/ 2 << Instantiation->getDeclName()
892 << Instantiation->getDeclContext();
893 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
894 }
895 }
896
897 // In general, Instantiation isn't marked invalid to get more than one
898 // error for multiple undefined instantiations. But the code that does
899 // explicit declaration -> explicit definition conversion can't handle
900 // invalid declarations, so mark as invalid in that case.
901 if (TSK == TSK_ExplicitInstantiationDeclaration)
902 Instantiation->setInvalidDecl();
903 return true;
904}
905
906void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
907 bool SupportedForCompatibility) {
908 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
909
910 // C++23 [temp.local]p6:
911 // The name of a template-parameter shall not be bound to any following.
912 // declaration whose locus is contained by the scope to which the
913 // template-parameter belongs.
914 //
915 // When MSVC compatibility is enabled, the diagnostic is always a warning
916 // by default. Otherwise, it an error unless SupportedForCompatibility is
917 // true, in which case it is a default-to-error warning.
918 unsigned DiagId =
919 getLangOpts().MSVCCompat
920 ? diag::ext_template_param_shadow
921 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
922 : diag::err_template_param_shadow);
923 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
924 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
925 NoteTemplateParameterLocation(Decl: *ND);
926}
927
928TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
929 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
930 D = Temp->getTemplatedDecl();
931 return Temp;
932 }
933 return nullptr;
934}
935
936ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
937 SourceLocation EllipsisLoc) const {
938 assert(Kind == Template &&
939 "Only template template arguments can be pack expansions here");
940 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
941 "Template template argument pack expansion without packs");
942 ParsedTemplateArgument Result(*this);
943 Result.EllipsisLoc = EllipsisLoc;
944 return Result;
945}
946
947static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
948 const ParsedTemplateArgument &Arg) {
949
950 switch (Arg.getKind()) {
951 case ParsedTemplateArgument::Type: {
952 TypeSourceInfo *TSI;
953 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
954 if (!TSI)
955 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
956 return TemplateArgumentLoc(TemplateArgument(T), TSI);
957 }
958
959 case ParsedTemplateArgument::NonType: {
960 Expr *E = Arg.getAsExpr();
961 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
962 }
963
964 case ParsedTemplateArgument::Template: {
965 TemplateName Template = Arg.getAsTemplate().get();
966 TemplateArgument TArg;
967 if (Arg.getEllipsisLoc().isValid())
968 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
969 else
970 TArg = Template;
971 return TemplateArgumentLoc(
972 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
973 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
974 Arg.getNameLoc(), Arg.getEllipsisLoc());
975 }
976 }
977
978 llvm_unreachable("Unhandled parsed template argument");
979}
980
981void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
982 TemplateArgumentListInfo &TemplateArgs) {
983 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
984 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
985 Arg: TemplateArgsIn[I]));
986}
987
988static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
989 SourceLocation Loc,
990 const IdentifierInfo *Name) {
991 NamedDecl *PrevDecl =
992 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
993 Redecl: RedeclarationKind::ForVisibleRedeclaration);
994 if (PrevDecl && PrevDecl->isTemplateParameter())
995 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
996}
997
998ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
999 TypeSourceInfo *TInfo;
1000 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1001 if (T.isNull())
1002 return ParsedTemplateArgument();
1003 assert(TInfo && "template argument with no location");
1004
1005 // If we might have formed a deduced template specialization type, convert
1006 // it to a template template argument.
1007 if (getLangOpts().CPlusPlus17) {
1008 TypeLoc TL = TInfo->getTypeLoc();
1009 SourceLocation EllipsisLoc;
1010 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1011 EllipsisLoc = PET.getEllipsisLoc();
1012 TL = PET.getPatternLoc();
1013 }
1014
1015 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1016 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1017 CXXScopeSpec SS;
1018 SS.Adopt(Other: DTST.getQualifierLoc());
1019 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1020 TemplateTy::make(P: Name),
1021 DTST.getTemplateNameLoc());
1022 if (EllipsisLoc.isValid())
1023 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1024 return Result;
1025 }
1026 }
1027
1028 // This is a normal type template argument. Note, if the type template
1029 // argument is an injected-class-name for a template, it has a dual nature
1030 // and can be used as either a type or a template. We handle that in
1031 // convertTypeTemplateArgumentToTemplate.
1032 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1033 ParsedType.get().getAsOpaquePtr(),
1034 TInfo->getTypeLoc().getBeginLoc());
1035}
1036
1037NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1038 SourceLocation EllipsisLoc,
1039 SourceLocation KeyLoc,
1040 IdentifierInfo *ParamName,
1041 SourceLocation ParamNameLoc,
1042 unsigned Depth, unsigned Position,
1043 SourceLocation EqualLoc,
1044 ParsedType DefaultArg,
1045 bool HasTypeConstraint) {
1046 assert(S->isTemplateParamScope() &&
1047 "Template type parameter not in template parameter scope!");
1048
1049 bool IsParameterPack = EllipsisLoc.isValid();
1050 TemplateTypeParmDecl *Param
1051 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1052 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1053 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1054 HasTypeConstraint);
1055 Param->setAccess(AS_public);
1056
1057 if (Param->isParameterPack())
1058 if (auto *CSI = getEnclosingLambdaOrBlock())
1059 CSI->LocalPacks.push_back(Elt: Param);
1060
1061 if (ParamName) {
1062 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1063
1064 // Add the template parameter into the current scope.
1065 S->AddDecl(D: Param);
1066 IdResolver.AddDecl(D: Param);
1067 }
1068
1069 // C++0x [temp.param]p9:
1070 // A default template-argument may be specified for any kind of
1071 // template-parameter that is not a template parameter pack.
1072 if (DefaultArg && IsParameterPack) {
1073 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1074 DefaultArg = nullptr;
1075 }
1076
1077 // Handle the default argument, if provided.
1078 if (DefaultArg) {
1079 TypeSourceInfo *DefaultTInfo;
1080 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1081
1082 assert(DefaultTInfo && "expected source information for type");
1083
1084 // Check for unexpanded parameter packs.
1085 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1086 UPPC: UPPC_DefaultArgument))
1087 return Param;
1088
1089 // Check the template argument itself.
1090 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1091 Param->setInvalidDecl();
1092 return Param;
1093 }
1094
1095 Param->setDefaultArgument(
1096 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1097 }
1098
1099 return Param;
1100}
1101
1102/// Convert the parser's template argument list representation into our form.
1103static TemplateArgumentListInfo
1104makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1105 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1106 TemplateId.RAngleLoc);
1107 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1108 TemplateId.NumArgs);
1109 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1110 return TemplateArgs;
1111}
1112
1113bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1114
1115 TemplateName TN = TypeConstr->Template.get();
1116 NamedDecl *CD = nullptr;
1117 bool IsTypeConcept = false;
1118 bool RequiresArguments = false;
1119 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TN.getAsTemplateDecl())) {
1120 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1121 RequiresArguments =
1122 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1123 CD = TTP;
1124 } else {
1125 CD = TN.getAsTemplateDecl();
1126 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1127 RequiresArguments = cast<ConceptDecl>(Val: CD)
1128 ->getTemplateParameters()
1129 ->getMinRequiredArguments() > 1;
1130 }
1131
1132 // C++2a [temp.param]p4:
1133 // [...] The concept designated by a type-constraint shall be a type
1134 // concept ([temp.concept]).
1135 if (!IsTypeConcept) {
1136 Diag(Loc: TypeConstr->TemplateNameLoc,
1137 DiagID: diag::err_type_constraint_non_type_concept);
1138 return true;
1139 }
1140
1141 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1142 return true;
1143
1144 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1145
1146 if (!WereArgsSpecified && RequiresArguments) {
1147 Diag(Loc: TypeConstr->TemplateNameLoc,
1148 DiagID: diag::err_type_constraint_missing_arguments)
1149 << CD;
1150 return true;
1151 }
1152 return false;
1153}
1154
1155bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1156 TemplateIdAnnotation *TypeConstr,
1157 TemplateTypeParmDecl *ConstrainedParameter,
1158 SourceLocation EllipsisLoc) {
1159 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1160 AllowUnexpandedPack: false);
1161}
1162
1163bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1164 TemplateIdAnnotation *TypeConstr,
1165 TemplateTypeParmDecl *ConstrainedParameter,
1166 SourceLocation EllipsisLoc,
1167 bool AllowUnexpandedPack) {
1168
1169 if (CheckTypeConstraint(TypeConstr))
1170 return true;
1171
1172 TemplateName TN = TypeConstr->Template.get();
1173 TemplateDecl *CD = cast<TemplateDecl>(Val: TN.getAsTemplateDecl());
1174 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1175
1176 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1177 TypeConstr->TemplateNameLoc);
1178
1179 TemplateArgumentListInfo TemplateArgs;
1180 if (TypeConstr->LAngleLoc.isValid()) {
1181 TemplateArgs =
1182 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1183
1184 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1185 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1186 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1187 return true;
1188 }
1189 }
1190 }
1191 return AttachTypeConstraint(
1192 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1193 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1194 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1195 ConstrainedParameter, EllipsisLoc);
1196}
1197
1198template <typename ArgumentLocAppender>
1199static ExprResult formImmediatelyDeclaredConstraint(
1200 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1201 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1202 SourceLocation RAngleLoc, QualType ConstrainedType,
1203 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1204 SourceLocation EllipsisLoc) {
1205
1206 TemplateArgumentListInfo ConstraintArgs;
1207 ConstraintArgs.addArgument(
1208 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1209 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1210
1211 ConstraintArgs.setRAngleLoc(RAngleLoc);
1212 ConstraintArgs.setLAngleLoc(LAngleLoc);
1213 Appender(ConstraintArgs);
1214
1215 // C++2a [temp.param]p4:
1216 // [...] This constraint-expression E is called the immediately-declared
1217 // constraint of T. [...]
1218 CXXScopeSpec SS;
1219 SS.Adopt(Other: NS);
1220 ExprResult ImmediatelyDeclaredConstraint;
1221 if (auto *CD = dyn_cast<ConceptDecl>(Val: NamedConcept)) {
1222 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1223 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1224 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1225 /*DoCheckConstraintSatisfaction=*/
1226 !S.inParameterMappingSubstitution());
1227 }
1228 // We have a template template parameter
1229 else {
1230 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(Val: NamedConcept);
1231 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1232 SS, NameInfo, Template: CDT, TemplateLoc: SourceLocation(), TemplateArgs: &ConstraintArgs);
1233 }
1234 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1235 return ImmediatelyDeclaredConstraint;
1236
1237 // C++2a [temp.param]p4:
1238 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1239 //
1240 // We have the following case:
1241 //
1242 // template<typename T> concept C1 = true;
1243 // template<C1... T> struct s1;
1244 //
1245 // The constraint: (C1<T> && ...)
1246 //
1247 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1248 // any unqualified lookups for 'operator&&' here.
1249 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1250 /*LParenLoc=*/SourceLocation(),
1251 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1252 EllipsisLoc, /*RHS=*/nullptr,
1253 /*RParenLoc=*/SourceLocation(),
1254 /*NumExpansions=*/std::nullopt);
1255}
1256
1257bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1258 DeclarationNameInfo NameInfo,
1259 TemplateDecl *NamedConcept,
1260 NamedDecl *FoundDecl,
1261 const TemplateArgumentListInfo *TemplateArgs,
1262 TemplateTypeParmDecl *ConstrainedParameter,
1263 SourceLocation EllipsisLoc) {
1264 // C++2a [temp.param]p4:
1265 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1266 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1267 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1268 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1269 List: *TemplateArgs) : nullptr;
1270
1271 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1272
1273 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1274 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1275 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1276 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1277 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1278 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1279 if (TemplateArgs)
1280 for (const auto &ArgLoc : TemplateArgs->arguments())
1281 ConstraintArgs.addArgument(Loc: ArgLoc);
1282 },
1283 EllipsisLoc);
1284 if (ImmediatelyDeclaredConstraint.isInvalid())
1285 return true;
1286
1287 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1288 /*TemplateKWLoc=*/SourceLocation{},
1289 /*ConceptNameInfo=*/NameInfo,
1290 /*FoundDecl=*/FoundDecl,
1291 /*NamedConcept=*/NamedConcept,
1292 /*ArgsWritten=*/ArgsAsWritten);
1293 ConstrainedParameter->setTypeConstraint(
1294 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1295 return false;
1296}
1297
1298bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1299 NonTypeTemplateParmDecl *NewConstrainedParm,
1300 NonTypeTemplateParmDecl *OrigConstrainedParm,
1301 SourceLocation EllipsisLoc) {
1302 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1303 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1304 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1305 DiagID: diag::err_unsupported_placeholder_constraint)
1306 << NewConstrainedParm->getTypeSourceInfo()
1307 ->getTypeLoc()
1308 .getSourceRange();
1309 return true;
1310 }
1311 // FIXME: Concepts: This should be the type of the placeholder, but this is
1312 // unclear in the wording right now.
1313 DeclRefExpr *Ref =
1314 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1315 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1316 if (!Ref)
1317 return true;
1318 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1319 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1320 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1321 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1322 ParamNameLoc: OrigConstrainedParm->getLocation(),
1323 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1324 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1325 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1326 },
1327 EllipsisLoc);
1328 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1329 !ImmediatelyDeclaredConstraint.isUsable())
1330 return true;
1331
1332 NewConstrainedParm->setPlaceholderTypeConstraint(
1333 ImmediatelyDeclaredConstraint.get());
1334 return false;
1335}
1336
1337QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1338 SourceLocation Loc) {
1339 if (TSI->getType()->isUndeducedType()) {
1340 // C++17 [temp.dep.expr]p3:
1341 // An id-expression is type-dependent if it contains
1342 // - an identifier associated by name lookup with a non-type
1343 // template-parameter declared with a type that contains a
1344 // placeholder type (7.1.7.4),
1345 TSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1346 }
1347
1348 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1349}
1350
1351bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1352 if (T->isDependentType())
1353 return false;
1354
1355 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1356 return true;
1357
1358 if (T->isStructuralType())
1359 return false;
1360
1361 // Structural types are required to be object types or lvalue references.
1362 if (T->isRValueReferenceType()) {
1363 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1364 return true;
1365 }
1366
1367 // Don't mention structural types in our diagnostic prior to C++20. Also,
1368 // there's not much more we can say about non-scalar non-class types --
1369 // because we can't see functions or arrays here, those can only be language
1370 // extensions.
1371 if (!getLangOpts().CPlusPlus20 ||
1372 (!T->isScalarType() && !T->isRecordType())) {
1373 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1374 return true;
1375 }
1376
1377 // Structural types are required to be literal types.
1378 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1379 return true;
1380
1381 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1382
1383 // Drill down into the reason why the class is non-structural.
1384 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1385 // All members are required to be public and non-mutable, and can't be of
1386 // rvalue reference type. Check these conditions first to prefer a "local"
1387 // reason over a more distant one.
1388 for (const FieldDecl *FD : RD->fields()) {
1389 if (FD->getAccess() != AS_public) {
1390 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1391 return true;
1392 }
1393 if (FD->isMutable()) {
1394 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1395 return true;
1396 }
1397 if (FD->getType()->isRValueReferenceType()) {
1398 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1399 << T;
1400 return true;
1401 }
1402 }
1403
1404 // All bases are required to be public.
1405 for (const auto &BaseSpec : RD->bases()) {
1406 if (BaseSpec.getAccessSpecifier() != AS_public) {
1407 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1408 << T << 1;
1409 return true;
1410 }
1411 }
1412
1413 // All subobjects are required to be of structural types.
1414 SourceLocation SubLoc;
1415 QualType SubType;
1416 int Kind = -1;
1417
1418 for (const FieldDecl *FD : RD->fields()) {
1419 QualType T = Context.getBaseElementType(QT: FD->getType());
1420 if (!T->isStructuralType()) {
1421 SubLoc = FD->getLocation();
1422 SubType = T;
1423 Kind = 0;
1424 break;
1425 }
1426 }
1427
1428 if (Kind == -1) {
1429 for (const auto &BaseSpec : RD->bases()) {
1430 QualType T = BaseSpec.getType();
1431 if (!T->isStructuralType()) {
1432 SubLoc = BaseSpec.getBaseTypeLoc();
1433 SubType = T;
1434 Kind = 1;
1435 break;
1436 }
1437 }
1438 }
1439
1440 assert(Kind != -1 && "couldn't find reason why type is not structural");
1441 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1442 << T << Kind << SubType;
1443 T = SubType;
1444 RD = T->getAsCXXRecordDecl();
1445 }
1446
1447 return true;
1448}
1449
1450QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1451 SourceLocation Loc) {
1452 // We don't allow variably-modified types as the type of non-type template
1453 // parameters.
1454 if (T->isVariablyModifiedType()) {
1455 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1456 << T;
1457 return QualType();
1458 }
1459
1460 // C++ [temp.param]p4:
1461 //
1462 // A non-type template-parameter shall have one of the following
1463 // (optionally cv-qualified) types:
1464 //
1465 // -- integral or enumeration type,
1466 if (T->isIntegralOrEnumerationType() ||
1467 // -- pointer to object or pointer to function,
1468 T->isPointerType() ||
1469 // -- lvalue reference to object or lvalue reference to function,
1470 T->isLValueReferenceType() ||
1471 // -- pointer to member,
1472 T->isMemberPointerType() ||
1473 // -- std::nullptr_t, or
1474 T->isNullPtrType() ||
1475 // -- a type that contains a placeholder type.
1476 T->isUndeducedType()) {
1477 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1478 // are ignored when determining its type.
1479 return T.getUnqualifiedType();
1480 }
1481
1482 // C++ [temp.param]p8:
1483 //
1484 // A non-type template-parameter of type "array of T" or
1485 // "function returning T" is adjusted to be of type "pointer to
1486 // T" or "pointer to function returning T", respectively.
1487 if (T->isArrayType() || T->isFunctionType())
1488 return Context.getDecayedType(T);
1489
1490 // If T is a dependent type, we can't do the check now, so we
1491 // assume that it is well-formed. Note that stripping off the
1492 // qualifiers here is not really correct if T turns out to be
1493 // an array type, but we'll recompute the type everywhere it's
1494 // used during instantiation, so that should be OK. (Using the
1495 // qualified type is equally wrong.)
1496 if (T->isDependentType())
1497 return T.getUnqualifiedType();
1498
1499 // C++20 [temp.param]p6:
1500 // -- a structural type
1501 if (RequireStructuralType(T, Loc))
1502 return QualType();
1503
1504 if (!getLangOpts().CPlusPlus20) {
1505 // FIXME: Consider allowing structural types as an extension in C++17. (In
1506 // earlier language modes, the template argument evaluation rules are too
1507 // inflexible.)
1508 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1509 return QualType();
1510 }
1511
1512 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1513 return T.getUnqualifiedType();
1514}
1515
1516NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1517 unsigned Depth,
1518 unsigned Position,
1519 SourceLocation EqualLoc,
1520 Expr *Default) {
1521 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1522
1523 // Check that we have valid decl-specifiers specified.
1524 auto CheckValidDeclSpecifiers = [this, &D] {
1525 // C++ [temp.param]
1526 // p1
1527 // template-parameter:
1528 // ...
1529 // parameter-declaration
1530 // p2
1531 // ... A storage class shall not be specified in a template-parameter
1532 // declaration.
1533 // [dcl.typedef]p1:
1534 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1535 // of a parameter-declaration
1536 const DeclSpec &DS = D.getDeclSpec();
1537 auto EmitDiag = [this](SourceLocation Loc) {
1538 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1539 << FixItHint::CreateRemoval(RemoveRange: Loc);
1540 };
1541 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1542 EmitDiag(DS.getStorageClassSpecLoc());
1543
1544 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1545 EmitDiag(DS.getThreadStorageClassSpecLoc());
1546
1547 // [dcl.inline]p1:
1548 // The inline specifier can be applied only to the declaration or
1549 // definition of a variable or function.
1550
1551 if (DS.isInlineSpecified())
1552 EmitDiag(DS.getInlineSpecLoc());
1553
1554 // [dcl.constexpr]p1:
1555 // The constexpr specifier shall be applied only to the definition of a
1556 // variable or variable template or the declaration of a function or
1557 // function template.
1558
1559 if (DS.hasConstexprSpecifier())
1560 EmitDiag(DS.getConstexprSpecLoc());
1561
1562 // [dcl.fct.spec]p1:
1563 // Function-specifiers can be used only in function declarations.
1564
1565 if (DS.isVirtualSpecified())
1566 EmitDiag(DS.getVirtualSpecLoc());
1567
1568 if (DS.hasExplicitSpecifier())
1569 EmitDiag(DS.getExplicitSpecLoc());
1570
1571 if (DS.isNoreturnSpecified())
1572 EmitDiag(DS.getNoreturnSpecLoc());
1573 };
1574
1575 CheckValidDeclSpecifiers();
1576
1577 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1578 if (isa<AutoType>(Val: T))
1579 Diag(Loc: D.getIdentifierLoc(),
1580 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1581 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1582
1583 assert(S->isTemplateParamScope() &&
1584 "Non-type template parameter not in template parameter scope!");
1585 bool Invalid = false;
1586
1587 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1588 if (T.isNull()) {
1589 T = Context.IntTy; // Recover with an 'int' type.
1590 Invalid = true;
1591 }
1592
1593 CheckFunctionOrTemplateParamDeclarator(S, D);
1594
1595 const IdentifierInfo *ParamName = D.getIdentifier();
1596 bool IsParameterPack = D.hasEllipsis();
1597 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1598 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1599 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1600 TInfo);
1601 Param->setAccess(AS_public);
1602
1603 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1604 if (TL.isConstrained()) {
1605 if (D.getEllipsisLoc().isInvalid() &&
1606 T->containsUnexpandedParameterPack()) {
1607 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1608 for (auto &Loc :
1609 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1610 Invalid |= DiagnoseUnexpandedParameterPack(
1611 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1612 }
1613 if (!Invalid &&
1614 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1615 Invalid = true;
1616 }
1617
1618 if (Invalid)
1619 Param->setInvalidDecl();
1620
1621 if (Param->isParameterPack())
1622 if (auto *CSI = getEnclosingLambdaOrBlock())
1623 CSI->LocalPacks.push_back(Elt: Param);
1624
1625 if (ParamName) {
1626 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1627 Name: ParamName);
1628
1629 // Add the template parameter into the current scope.
1630 S->AddDecl(D: Param);
1631 IdResolver.AddDecl(D: Param);
1632 }
1633
1634 // C++0x [temp.param]p9:
1635 // A default template-argument may be specified for any kind of
1636 // template-parameter that is not a template parameter pack.
1637 if (Default && IsParameterPack) {
1638 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1639 Default = nullptr;
1640 }
1641
1642 // Check the well-formedness of the default template argument, if provided.
1643 if (Default) {
1644 // Check for unexpanded parameter packs.
1645 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1646 return Param;
1647
1648 Param->setDefaultArgument(
1649 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1650 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1651 NTTPType: QualType(), Loc: SourceLocation()));
1652 }
1653
1654 return Param;
1655}
1656
1657/// ActOnTemplateTemplateParameter - Called when a C++ template template
1658/// parameter (e.g. T in template <template \<typename> class T> class array)
1659/// has been parsed. S is the current scope.
1660NamedDecl *Sema::ActOnTemplateTemplateParameter(
1661 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1662 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1663 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1664 unsigned Position, SourceLocation EqualLoc,
1665 ParsedTemplateArgument Default) {
1666 assert(S->isTemplateParamScope() &&
1667 "Template template parameter not in template parameter scope!");
1668
1669 bool IsParameterPack = EllipsisLoc.isValid();
1670
1671 bool Invalid = false;
1672 if (CheckTemplateParameterList(
1673 NewParams: Params,
1674 /*OldParams=*/nullptr,
1675 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1676 Invalid = true;
1677
1678 // Construct the parameter object.
1679 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1680 C: Context, DC: Context.getTranslationUnitDecl(),
1681 L: NameLoc.isInvalid() ? TmpLoc : NameLoc, D: Depth, P: Position, ParameterPack: IsParameterPack,
1682 Id: Name, ParameterKind: Kind, Typename, Params);
1683 Param->setAccess(AS_public);
1684
1685 if (Param->isParameterPack())
1686 if (auto *LSI = getEnclosingLambdaOrBlock())
1687 LSI->LocalPacks.push_back(Elt: Param);
1688
1689 // If the template template parameter has a name, then link the identifier
1690 // into the scope and lookup mechanisms.
1691 if (Name) {
1692 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1693
1694 S->AddDecl(D: Param);
1695 IdResolver.AddDecl(D: Param);
1696 }
1697
1698 if (Params->size() == 0) {
1699 Diag(Loc: Param->getLocation(), DiagID: diag::err_template_template_parm_no_parms)
1700 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1701 Invalid = true;
1702 }
1703
1704 if (Invalid)
1705 Param->setInvalidDecl();
1706
1707 // C++0x [temp.param]p9:
1708 // A default template-argument may be specified for any kind of
1709 // template-parameter that is not a template parameter pack.
1710 if (IsParameterPack && !Default.isInvalid()) {
1711 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1712 Default = ParsedTemplateArgument();
1713 }
1714
1715 if (!Default.isInvalid()) {
1716 // Check only that we have a template template argument. We don't want to
1717 // try to check well-formedness now, because our template template parameter
1718 // might have dependent types in its template parameters, which we wouldn't
1719 // be able to match now.
1720 //
1721 // If none of the template template parameter's template arguments mention
1722 // other template parameters, we could actually perform more checking here.
1723 // However, it isn't worth doing.
1724 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1725 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1726 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1727 << DefaultArg.getSourceRange();
1728 return Param;
1729 }
1730
1731 TemplateName Name =
1732 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1733 TemplateDecl *Template = Name.getAsTemplateDecl();
1734 if (Template &&
1735 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1736 return Param;
1737 }
1738
1739 // Check for unexpanded parameter packs.
1740 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1741 Template: DefaultArg.getArgument().getAsTemplate(),
1742 UPPC: UPPC_DefaultArgument))
1743 return Param;
1744
1745 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1746 }
1747
1748 return Param;
1749}
1750
1751namespace {
1752class ConstraintRefersToContainingTemplateChecker
1753 : public ConstDynamicRecursiveASTVisitor {
1754 using inherited = ConstDynamicRecursiveASTVisitor;
1755 bool Result = false;
1756 const FunctionDecl *Friend = nullptr;
1757 unsigned TemplateDepth = 0;
1758
1759 // Check a record-decl that we've seen to see if it is a lexical parent of the
1760 // Friend, likely because it was referred to without its template arguments.
1761 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1762 CheckingRD = CheckingRD->getMostRecentDecl();
1763 if (!CheckingRD->isTemplated())
1764 return true;
1765
1766 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1767 DC && !DC->isFileContext(); DC = DC->getParent())
1768 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1769 if (CheckingRD == RD->getMostRecentDecl()) {
1770 Result = true;
1771 return false;
1772 }
1773
1774 return true;
1775 }
1776
1777 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1778 if (D->getDepth() < TemplateDepth)
1779 Result = true;
1780
1781 // Necessary because the type of the NTTP might be what refers to the parent
1782 // constriant.
1783 return TraverseType(T: D->getType());
1784 }
1785
1786public:
1787 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1788 unsigned TemplateDepth)
1789 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1790
1791 bool getResult() const { return Result; }
1792
1793 // This should be the only template parm type that we have to deal with.
1794 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1795 // FunctionParmPackExpr are all partially substituted, which cannot happen
1796 // with concepts at this point in translation.
1797 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1798 if (Type->getDecl()->getDepth() < TemplateDepth) {
1799 Result = true;
1800 return false;
1801 }
1802 return true;
1803 }
1804
1805 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1806 return TraverseDecl(D: E->getDecl());
1807 }
1808
1809 bool TraverseTypedefType(const TypedefType *TT,
1810 bool /*TraverseQualifier*/) override {
1811 return TraverseType(T: TT->desugar());
1812 }
1813
1814 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1815 // We don't care about TypeLocs. So traverse Types instead.
1816 return TraverseType(T: TL.getType(), TraverseQualifier);
1817 }
1818
1819 bool VisitTagType(const TagType *T) override {
1820 return TraverseDecl(D: T->getDecl());
1821 }
1822
1823 bool TraverseDecl(const Decl *D) override {
1824 assert(D);
1825 // FIXME : This is possibly an incomplete list, but it is unclear what other
1826 // Decl kinds could be used to refer to the template parameters. This is a
1827 // best guess so far based on examples currently available, but the
1828 // unreachable should catch future instances/cases.
1829 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1830 return TraverseType(T: TD->getUnderlyingType());
1831 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1832 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1833 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1834 return TraverseType(T: VD->getType());
1835 if (isa<TemplateDecl>(Val: D))
1836 return true;
1837 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1838 return CheckIfContainingRecord(CheckingRD: RD);
1839
1840 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1841 // No direct types to visit here I believe.
1842 } else
1843 llvm_unreachable("Don't know how to handle this declaration type yet");
1844 return true;
1845 }
1846};
1847} // namespace
1848
1849bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1850 const FunctionDecl *Friend, unsigned TemplateDepth,
1851 const Expr *Constraint) {
1852 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1853 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1854 Checker.TraverseStmt(S: Constraint);
1855 return Checker.getResult();
1856}
1857
1858TemplateParameterList *
1859Sema::ActOnTemplateParameterList(unsigned Depth,
1860 SourceLocation ExportLoc,
1861 SourceLocation TemplateLoc,
1862 SourceLocation LAngleLoc,
1863 ArrayRef<NamedDecl *> Params,
1864 SourceLocation RAngleLoc,
1865 Expr *RequiresClause) {
1866 if (ExportLoc.isValid())
1867 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1868
1869 for (NamedDecl *P : Params)
1870 warnOnReservedIdentifier(D: P);
1871
1872 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1873 Params: llvm::ArrayRef(Params), RAngleLoc,
1874 RequiresClause);
1875}
1876
1877static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1878 const CXXScopeSpec &SS) {
1879 if (SS.isSet())
1880 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1881}
1882
1883// Returns the template parameter list with all default template argument
1884// information.
1885TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1886 // Make sure we get the template parameter list from the most
1887 // recent declaration, since that is the only one that is guaranteed to
1888 // have all the default template argument information.
1889 Decl *D = TD->getMostRecentDecl();
1890 // C++11 N3337 [temp.param]p12:
1891 // A default template argument shall not be specified in a friend class
1892 // template declaration.
1893 //
1894 // Skip past friend *declarations* because they are not supposed to contain
1895 // default template arguments. Moreover, these declarations may introduce
1896 // template parameters living in different template depths than the
1897 // corresponding template parameters in TD, causing unmatched constraint
1898 // substitution.
1899 //
1900 // FIXME: Diagnose such cases within a class template:
1901 // template <class T>
1902 // struct S {
1903 // template <class = void> friend struct C;
1904 // };
1905 // template struct S<int>;
1906 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1907 D->getPreviousDecl())
1908 D = D->getPreviousDecl();
1909 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1910}
1911
1912DeclResult Sema::CheckClassTemplate(
1913 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1914 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1915 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1916 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1917 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1918 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1919 assert(TemplateParams && TemplateParams->size() > 0 &&
1920 "No template parameters");
1921 assert(TUK != TagUseKind::Reference &&
1922 "Can only declare or define class templates");
1923 bool Invalid = false;
1924
1925 // Check that we can declare a template here.
1926 if (CheckTemplateDeclScope(S, TemplateParams))
1927 return true;
1928
1929 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1930 assert(Kind != TagTypeKind::Enum &&
1931 "can't build template of enumerated type");
1932
1933 // There is no such thing as an unnamed class template.
1934 if (!Name) {
1935 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1936 return true;
1937 }
1938
1939 // Find any previous declaration with this name. For a friend with no
1940 // scope explicitly specified, we only look for tag declarations (per
1941 // C++11 [basic.lookup.elab]p2).
1942 DeclContext *SemanticContext;
1943 LookupResult Previous(*this, Name, NameLoc,
1944 (SS.isEmpty() && TUK == TagUseKind::Friend)
1945 ? LookupTagName
1946 : LookupOrdinaryName,
1947 forRedeclarationInCurContext());
1948 if (SS.isNotEmpty() && !SS.isInvalid()) {
1949 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1950 if (!SemanticContext) {
1951 // FIXME: Horrible, horrible hack! We can't currently represent this
1952 // in the AST, and historically we have just ignored such friend
1953 // class templates, so don't complain here.
1954 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1955 ? diag::warn_template_qualified_friend_ignored
1956 : diag::err_template_qualified_declarator_no_match)
1957 << SS.getScopeRep() << SS.getRange();
1958 return TUK != TagUseKind::Friend;
1959 }
1960
1961 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1962 return true;
1963
1964 // If we're adding a template to a dependent context, we may need to
1965 // rebuilding some of the types used within the template parameter list,
1966 // now that we know what the current instantiation is.
1967 if (SemanticContext->isDependentContext()) {
1968 ContextRAII SavedContext(*this, SemanticContext);
1969 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1970 Invalid = true;
1971 }
1972
1973 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1974 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1975 /*TemplateId-*/ TemplateId: nullptr,
1976 /*IsMemberSpecialization*/ false);
1977
1978 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1979 } else {
1980 SemanticContext = CurContext;
1981
1982 // C++14 [class.mem]p14:
1983 // If T is the name of a class, then each of the following shall have a
1984 // name different from T:
1985 // -- every member template of class T
1986 if (TUK != TagUseKind::Friend &&
1987 DiagnoseClassNameShadow(DC: SemanticContext,
1988 Info: DeclarationNameInfo(Name, NameLoc)))
1989 return true;
1990
1991 LookupName(R&: Previous, S);
1992 }
1993
1994 if (Previous.isAmbiguous())
1995 return true;
1996
1997 // Let the template parameter scope enter the lookup chain of the current
1998 // class template. For example, given
1999 //
2000 // namespace ns {
2001 // template <class> bool Param = false;
2002 // template <class T> struct N;
2003 // }
2004 //
2005 // template <class Param> struct ns::N { void foo(Param); };
2006 //
2007 // When we reference Param inside the function parameter list, our name lookup
2008 // chain for it should be like:
2009 // FunctionScope foo
2010 // -> RecordScope N
2011 // -> TemplateParamScope (where we will find Param)
2012 // -> NamespaceScope ns
2013 //
2014 // See also CppLookupName().
2015 if (S->isTemplateParamScope())
2016 EnterTemplatedContext(S, DC: SemanticContext);
2017
2018 NamedDecl *PrevDecl = nullptr;
2019 if (Previous.begin() != Previous.end())
2020 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2021
2022 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2023 // Maybe we will complain about the shadowed template parameter.
2024 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2025 // Just pretend that we didn't see the previous declaration.
2026 PrevDecl = nullptr;
2027 }
2028
2029 // If there is a previous declaration with the same name, check
2030 // whether this is a valid redeclaration.
2031 ClassTemplateDecl *PrevClassTemplate =
2032 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2033
2034 // We may have found the injected-class-name of a class template,
2035 // class template partial specialization, or class template specialization.
2036 // In these cases, grab the template that is being defined or specialized.
2037 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2038 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2039 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2040 PrevClassTemplate
2041 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2042 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2043 PrevClassTemplate
2044 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2045 ->getSpecializedTemplate();
2046 }
2047 }
2048
2049 if (TUK == TagUseKind::Friend) {
2050 // C++ [namespace.memdef]p3:
2051 // [...] When looking for a prior declaration of a class or a function
2052 // declared as a friend, and when the name of the friend class or
2053 // function is neither a qualified name nor a template-id, scopes outside
2054 // the innermost enclosing namespace scope are not considered.
2055 if (!SS.isSet()) {
2056 DeclContext *OutermostContext = CurContext;
2057 while (!OutermostContext->isFileContext())
2058 OutermostContext = OutermostContext->getLookupParent();
2059
2060 if (PrevDecl &&
2061 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2062 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2063 SemanticContext = PrevDecl->getDeclContext();
2064 } else {
2065 // Declarations in outer scopes don't matter. However, the outermost
2066 // context we computed is the semantic context for our new
2067 // declaration.
2068 PrevDecl = PrevClassTemplate = nullptr;
2069 SemanticContext = OutermostContext;
2070
2071 // Check that the chosen semantic context doesn't already contain a
2072 // declaration of this name as a non-tag type.
2073 Previous.clear(Kind: LookupOrdinaryName);
2074 DeclContext *LookupContext = SemanticContext;
2075 while (LookupContext->isTransparentContext())
2076 LookupContext = LookupContext->getLookupParent();
2077 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2078
2079 if (Previous.isAmbiguous())
2080 return true;
2081
2082 if (Previous.begin() != Previous.end())
2083 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2084 }
2085 }
2086 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2087 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2088 PrevDecl = PrevClassTemplate = nullptr;
2089
2090 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2091 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2092 if (SS.isEmpty() &&
2093 !(PrevClassTemplate &&
2094 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2095 DC: SemanticContext->getRedeclContext()))) {
2096 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2097 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2098 DiagID: diag::note_using_decl_target);
2099 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2100 // Recover by ignoring the old declaration.
2101 PrevDecl = PrevClassTemplate = nullptr;
2102 }
2103 }
2104
2105 if (PrevClassTemplate) {
2106 // Ensure that the template parameter lists are compatible. Skip this check
2107 // for a friend in a dependent context: the template parameter list itself
2108 // could be dependent.
2109 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2110 !TemplateParameterListsAreEqual(
2111 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2112 : CurContext,
2113 CurContext, KWLoc),
2114 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2115 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2116 Kind: TPL_TemplateMatch))
2117 return true;
2118
2119 // C++ [temp.class]p4:
2120 // In a redeclaration, partial specialization, explicit
2121 // specialization or explicit instantiation of a class template,
2122 // the class-key shall agree in kind with the original class
2123 // template declaration (7.1.5.3).
2124 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2125 if (!isAcceptableTagRedeclaration(
2126 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2127 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2128 << Name
2129 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2130 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2131 Kind = PrevRecordDecl->getTagKind();
2132 }
2133
2134 // Check for redefinition of this class template.
2135 if (TUK == TagUseKind::Definition) {
2136 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2137 // If we have a prior definition that is not visible, treat this as
2138 // simply making that previous definition visible.
2139 NamedDecl *Hidden = nullptr;
2140 bool HiddenDefVisible = false;
2141 if (SkipBody &&
2142 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2143 SkipBody->ShouldSkip = true;
2144 SkipBody->Previous = Def;
2145 if (!HiddenDefVisible && Hidden) {
2146 auto *Tmpl =
2147 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2148 assert(Tmpl && "original definition of a class template is not a "
2149 "class template?");
2150 makeMergedDefinitionVisible(ND: Hidden);
2151 makeMergedDefinitionVisible(ND: Tmpl);
2152 }
2153 } else {
2154 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2155 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2156 // FIXME: Would it make sense to try to "forget" the previous
2157 // definition, as part of error recovery?
2158 return true;
2159 }
2160 }
2161 }
2162 } else if (PrevDecl) {
2163 // C++ [temp]p5:
2164 // A class template shall not have the same name as any other
2165 // template, class, function, object, enumeration, enumerator,
2166 // namespace, or type in the same scope (3.3), except as specified
2167 // in (14.5.4).
2168 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2169 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2170 return true;
2171 }
2172
2173 // Check the template parameter list of this declaration, possibly
2174 // merging in the template parameter list from the previous class
2175 // template declaration. Skip this check for a friend in a dependent
2176 // context, because the template parameter list might be dependent.
2177 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2178 CheckTemplateParameterList(
2179 NewParams: TemplateParams,
2180 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2181 : nullptr,
2182 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2183 SemanticContext->isDependentContext())
2184 ? TPC_ClassTemplateMember
2185 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2186 : TPC_Other,
2187 SkipBody))
2188 Invalid = true;
2189
2190 if (SS.isSet()) {
2191 // If the name of the template was qualified, we must be defining the
2192 // template out-of-line.
2193 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2194 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2195 ? diag::err_friend_decl_does_not_match
2196 : diag::err_member_decl_does_not_match)
2197 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2198 Invalid = true;
2199 }
2200 }
2201
2202 // If this is a templated friend in a dependent context we should not put it
2203 // on the redecl chain. In some cases, the templated friend can be the most
2204 // recent declaration tricking the template instantiator to make substitutions
2205 // there.
2206 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2207 bool ShouldAddRedecl =
2208 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2209
2210 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2211 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2212 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2213 ? PrevClassTemplate->getTemplatedDecl()
2214 : nullptr);
2215 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2216 if (NumOuterTemplateParamLists > 0)
2217 NewClass->setTemplateParameterListsInfo(
2218 Context,
2219 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2220
2221 // Add alignment attributes if necessary; these attributes are checked when
2222 // the ASTContext lays out the structure.
2223 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2224 if (LangOpts.HLSL)
2225 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2226 AddAlignmentAttributesForRecord(RD: NewClass);
2227 AddMsStructLayoutForRecord(RD: NewClass);
2228 }
2229
2230 ClassTemplateDecl *NewTemplate
2231 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2232 Name: DeclarationName(Name), Params: TemplateParams,
2233 Decl: NewClass);
2234
2235 if (ShouldAddRedecl)
2236 NewTemplate->setPreviousDecl(PrevClassTemplate);
2237
2238 NewClass->setDescribedClassTemplate(NewTemplate);
2239
2240 if (ModulePrivateLoc.isValid())
2241 NewTemplate->setModulePrivate();
2242
2243 // If we are providing an explicit specialization of a member that is a
2244 // class template, make a note of that.
2245 if (PrevClassTemplate &&
2246 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2247 PrevClassTemplate->setMemberSpecialization();
2248
2249 // Set the access specifier.
2250 if (!Invalid && TUK != TagUseKind::Friend &&
2251 NewTemplate->getDeclContext()->isRecord())
2252 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2253
2254 // Set the lexical context of these templates
2255 NewClass->setLexicalDeclContext(CurContext);
2256 NewTemplate->setLexicalDeclContext(CurContext);
2257
2258 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2259 NewClass->startDefinition();
2260
2261 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2262
2263 if (PrevClassTemplate)
2264 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2265
2266 AddPushedVisibilityAttribute(RD: NewClass);
2267 inferGslOwnerPointerAttribute(Record: NewClass);
2268 inferNullableClassAttribute(CRD: NewClass);
2269
2270 if (TUK != TagUseKind::Friend) {
2271 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2272 Scope *Outer = S;
2273 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2274 Outer = Outer->getParent();
2275 PushOnScopeChains(D: NewTemplate, S: Outer);
2276 } else {
2277 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2278 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2279 NewClass->setAccess(PrevClassTemplate->getAccess());
2280 }
2281
2282 NewTemplate->setObjectOfFriendDecl();
2283
2284 // Friend templates are visible in fairly strange ways.
2285 if (!CurContext->isDependentContext()) {
2286 DeclContext *DC = SemanticContext->getRedeclContext();
2287 DC->makeDeclVisibleInContext(D: NewTemplate);
2288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2289 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2290 /* AddToContext = */ false);
2291 }
2292
2293 FriendDecl *Friend = FriendDecl::Create(
2294 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2295 Friend->setAccess(AS_public);
2296 CurContext->addDecl(D: Friend);
2297 }
2298
2299 if (PrevClassTemplate)
2300 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2301
2302 if (Invalid) {
2303 NewTemplate->setInvalidDecl();
2304 NewClass->setInvalidDecl();
2305 }
2306
2307 ActOnDocumentableDecl(D: NewTemplate);
2308
2309 if (SkipBody && SkipBody->ShouldSkip)
2310 return SkipBody->Previous;
2311
2312 return NewTemplate;
2313}
2314
2315/// Diagnose the presence of a default template argument on a
2316/// template parameter, which is ill-formed in certain contexts.
2317///
2318/// \returns true if the default template argument should be dropped.
2319static bool DiagnoseDefaultTemplateArgument(Sema &S,
2320 Sema::TemplateParamListContext TPC,
2321 SourceLocation ParamLoc,
2322 SourceRange DefArgRange) {
2323 switch (TPC) {
2324 case Sema::TPC_Other:
2325 case Sema::TPC_TemplateTemplateParameterPack:
2326 return false;
2327
2328 case Sema::TPC_FunctionTemplate:
2329 case Sema::TPC_FriendFunctionTemplateDefinition:
2330 // C++ [temp.param]p9:
2331 // A default template-argument shall not be specified in a
2332 // function template declaration or a function template
2333 // definition [...]
2334 // If a friend function template declaration specifies a default
2335 // template-argument, that declaration shall be a definition and shall be
2336 // the only declaration of the function template in the translation unit.
2337 // (C++98/03 doesn't have this wording; see DR226).
2338 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2339 << DefArgRange;
2340 return false;
2341
2342 case Sema::TPC_ClassTemplateMember:
2343 // C++0x [temp.param]p9:
2344 // A default template-argument shall not be specified in the
2345 // template-parameter-lists of the definition of a member of a
2346 // class template that appears outside of the member's class.
2347 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2348 << DefArgRange;
2349 return true;
2350
2351 case Sema::TPC_FriendClassTemplate:
2352 case Sema::TPC_FriendFunctionTemplate:
2353 // C++ [temp.param]p9:
2354 // A default template-argument shall not be specified in a
2355 // friend template declaration.
2356 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2357 << DefArgRange;
2358 return true;
2359
2360 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2361 // for friend function templates if there is only a single
2362 // declaration (and it is a definition). Strange!
2363 }
2364
2365 llvm_unreachable("Invalid TemplateParamListContext!");
2366}
2367
2368/// Check for unexpanded parameter packs within the template parameters
2369/// of a template template parameter, recursively.
2370static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2371 TemplateTemplateParmDecl *TTP) {
2372 // A template template parameter which is a parameter pack is also a pack
2373 // expansion.
2374 if (TTP->isParameterPack())
2375 return false;
2376
2377 TemplateParameterList *Params = TTP->getTemplateParameters();
2378 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2379 NamedDecl *P = Params->getParam(Idx: I);
2380 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2381 if (!TTP->isParameterPack())
2382 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2383 if (TC->hasExplicitTemplateArgs())
2384 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2385 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2386 UPPC: Sema::UPPC_TypeConstraint))
2387 return true;
2388 continue;
2389 }
2390
2391 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2392 if (!NTTP->isParameterPack() &&
2393 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2394 T: NTTP->getTypeSourceInfo(),
2395 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2396 return true;
2397
2398 continue;
2399 }
2400
2401 if (TemplateTemplateParmDecl *InnerTTP
2402 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2403 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2404 return true;
2405 }
2406
2407 return false;
2408}
2409
2410bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2411 TemplateParameterList *OldParams,
2412 TemplateParamListContext TPC,
2413 SkipBodyInfo *SkipBody) {
2414 bool Invalid = false;
2415
2416 // C++ [temp.param]p10:
2417 // The set of default template-arguments available for use with a
2418 // template declaration or definition is obtained by merging the
2419 // default arguments from the definition (if in scope) and all
2420 // declarations in scope in the same way default function
2421 // arguments are (8.3.6).
2422 bool SawDefaultArgument = false;
2423 SourceLocation PreviousDefaultArgLoc;
2424
2425 // Dummy initialization to avoid warnings.
2426 TemplateParameterList::iterator OldParam = NewParams->end();
2427 if (OldParams)
2428 OldParam = OldParams->begin();
2429
2430 bool RemoveDefaultArguments = false;
2431 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2432 NewParamEnd = NewParams->end();
2433 NewParam != NewParamEnd; ++NewParam) {
2434 // Whether we've seen a duplicate default argument in the same translation
2435 // unit.
2436 bool RedundantDefaultArg = false;
2437 // Whether we've found inconsis inconsitent default arguments in different
2438 // translation unit.
2439 bool InconsistentDefaultArg = false;
2440 // The name of the module which contains the inconsistent default argument.
2441 std::string PrevModuleName;
2442
2443 SourceLocation OldDefaultLoc;
2444 SourceLocation NewDefaultLoc;
2445
2446 // Variable used to diagnose missing default arguments
2447 bool MissingDefaultArg = false;
2448
2449 // Variable used to diagnose non-final parameter packs
2450 bool SawParameterPack = false;
2451
2452 if (TemplateTypeParmDecl *NewTypeParm
2453 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2454 // Check the presence of a default argument here.
2455 if (NewTypeParm->hasDefaultArgument() &&
2456 DiagnoseDefaultTemplateArgument(
2457 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2458 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2459 NewTypeParm->removeDefaultArgument();
2460
2461 // Merge default arguments for template type parameters.
2462 TemplateTypeParmDecl *OldTypeParm
2463 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2464 if (NewTypeParm->isParameterPack()) {
2465 assert(!NewTypeParm->hasDefaultArgument() &&
2466 "Parameter packs can't have a default argument!");
2467 SawParameterPack = true;
2468 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2469 NewTypeParm->hasDefaultArgument() &&
2470 (!SkipBody || !SkipBody->ShouldSkip)) {
2471 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2472 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2473 SawDefaultArgument = true;
2474
2475 if (!OldTypeParm->getOwningModule())
2476 RedundantDefaultArg = true;
2477 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2478 Y: NewTypeParm)) {
2479 InconsistentDefaultArg = true;
2480 PrevModuleName =
2481 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2482 }
2483 PreviousDefaultArgLoc = NewDefaultLoc;
2484 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2485 // Merge the default argument from the old declaration to the
2486 // new declaration.
2487 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2488 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2489 } else if (NewTypeParm->hasDefaultArgument()) {
2490 SawDefaultArgument = true;
2491 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2492 } else if (SawDefaultArgument)
2493 MissingDefaultArg = true;
2494 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2495 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2496 // Check for unexpanded parameter packs, except in a template template
2497 // parameter pack, as in those any unexpanded packs should be expanded
2498 // along with the parameter itself.
2499 if (TPC != TPC_TemplateTemplateParameterPack &&
2500 !NewNonTypeParm->isParameterPack() &&
2501 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2502 T: NewNonTypeParm->getTypeSourceInfo(),
2503 UPPC: UPPC_NonTypeTemplateParameterType)) {
2504 Invalid = true;
2505 continue;
2506 }
2507
2508 // Check the presence of a default argument here.
2509 if (NewNonTypeParm->hasDefaultArgument() &&
2510 DiagnoseDefaultTemplateArgument(
2511 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2512 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2513 NewNonTypeParm->removeDefaultArgument();
2514 }
2515
2516 // Merge default arguments for non-type template parameters
2517 NonTypeTemplateParmDecl *OldNonTypeParm
2518 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2519 if (NewNonTypeParm->isParameterPack()) {
2520 assert(!NewNonTypeParm->hasDefaultArgument() &&
2521 "Parameter packs can't have a default argument!");
2522 if (!NewNonTypeParm->isPackExpansion())
2523 SawParameterPack = true;
2524 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2525 NewNonTypeParm->hasDefaultArgument() &&
2526 (!SkipBody || !SkipBody->ShouldSkip)) {
2527 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2528 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2529 SawDefaultArgument = true;
2530 if (!OldNonTypeParm->getOwningModule())
2531 RedundantDefaultArg = true;
2532 else if (!getASTContext().isSameDefaultTemplateArgument(
2533 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2534 InconsistentDefaultArg = true;
2535 PrevModuleName =
2536 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2537 }
2538 PreviousDefaultArgLoc = NewDefaultLoc;
2539 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2540 // Merge the default argument from the old declaration to the
2541 // new declaration.
2542 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2543 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2544 } else if (NewNonTypeParm->hasDefaultArgument()) {
2545 SawDefaultArgument = true;
2546 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2547 } else if (SawDefaultArgument)
2548 MissingDefaultArg = true;
2549 } else {
2550 TemplateTemplateParmDecl *NewTemplateParm
2551 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2552
2553 // Check for unexpanded parameter packs, recursively.
2554 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2555 Invalid = true;
2556 continue;
2557 }
2558
2559 // Check the presence of a default argument here.
2560 if (NewTemplateParm->hasDefaultArgument() &&
2561 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2562 ParamLoc: NewTemplateParm->getLocation(),
2563 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2564 NewTemplateParm->removeDefaultArgument();
2565
2566 // Merge default arguments for template template parameters
2567 TemplateTemplateParmDecl *OldTemplateParm
2568 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2569 if (NewTemplateParm->isParameterPack()) {
2570 assert(!NewTemplateParm->hasDefaultArgument() &&
2571 "Parameter packs can't have a default argument!");
2572 if (!NewTemplateParm->isPackExpansion())
2573 SawParameterPack = true;
2574 } else if (OldTemplateParm &&
2575 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2576 NewTemplateParm->hasDefaultArgument() &&
2577 (!SkipBody || !SkipBody->ShouldSkip)) {
2578 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2579 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2580 SawDefaultArgument = true;
2581 if (!OldTemplateParm->getOwningModule())
2582 RedundantDefaultArg = true;
2583 else if (!getASTContext().isSameDefaultTemplateArgument(
2584 X: OldTemplateParm, Y: NewTemplateParm)) {
2585 InconsistentDefaultArg = true;
2586 PrevModuleName =
2587 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2588 }
2589 PreviousDefaultArgLoc = NewDefaultLoc;
2590 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2591 // Merge the default argument from the old declaration to the
2592 // new declaration.
2593 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2594 PreviousDefaultArgLoc
2595 = OldTemplateParm->getDefaultArgument().getLocation();
2596 } else if (NewTemplateParm->hasDefaultArgument()) {
2597 SawDefaultArgument = true;
2598 PreviousDefaultArgLoc
2599 = NewTemplateParm->getDefaultArgument().getLocation();
2600 } else if (SawDefaultArgument)
2601 MissingDefaultArg = true;
2602 }
2603
2604 // C++11 [temp.param]p11:
2605 // If a template parameter of a primary class template or alias template
2606 // is a template parameter pack, it shall be the last template parameter.
2607 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2608 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2609 Diag(Loc: (*NewParam)->getLocation(),
2610 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2611 Invalid = true;
2612 }
2613
2614 // [basic.def.odr]/13:
2615 // There can be more than one definition of a
2616 // ...
2617 // default template argument
2618 // ...
2619 // in a program provided that each definition appears in a different
2620 // translation unit and the definitions satisfy the [same-meaning
2621 // criteria of the ODR].
2622 //
2623 // Simply, the design of modules allows the definition of template default
2624 // argument to be repeated across translation unit. Note that the ODR is
2625 // checked elsewhere. But it is still not allowed to repeat template default
2626 // argument in the same translation unit.
2627 if (RedundantDefaultArg) {
2628 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2629 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2630 Invalid = true;
2631 } else if (InconsistentDefaultArg) {
2632 // We could only diagnose about the case that the OldParam is imported.
2633 // The case NewParam is imported should be handled in ASTReader.
2634 Diag(Loc: NewDefaultLoc,
2635 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2636 Diag(Loc: OldDefaultLoc,
2637 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2638 << PrevModuleName;
2639 Invalid = true;
2640 } else if (MissingDefaultArg &&
2641 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2642 TPC == TPC_FriendClassTemplate)) {
2643 // C++ 23[temp.param]p14:
2644 // If a template-parameter of a class template, variable template, or
2645 // alias template has a default template argument, each subsequent
2646 // template-parameter shall either have a default template argument
2647 // supplied or be a template parameter pack.
2648 Diag(Loc: (*NewParam)->getLocation(),
2649 DiagID: diag::err_template_param_default_arg_missing);
2650 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2651 Invalid = true;
2652 RemoveDefaultArguments = true;
2653 }
2654
2655 // If we have an old template parameter list that we're merging
2656 // in, move on to the next parameter.
2657 if (OldParams)
2658 ++OldParam;
2659 }
2660
2661 // We were missing some default arguments at the end of the list, so remove
2662 // all of the default arguments.
2663 if (RemoveDefaultArguments) {
2664 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2665 NewParamEnd = NewParams->end();
2666 NewParam != NewParamEnd; ++NewParam) {
2667 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2668 TTP->removeDefaultArgument();
2669 else if (NonTypeTemplateParmDecl *NTTP
2670 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2671 NTTP->removeDefaultArgument();
2672 else
2673 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2674 }
2675 }
2676
2677 return Invalid;
2678}
2679
2680namespace {
2681
2682/// A class which looks for a use of a certain level of template
2683/// parameter.
2684struct DependencyChecker : DynamicRecursiveASTVisitor {
2685 unsigned Depth;
2686
2687 // Whether we're looking for a use of a template parameter that makes the
2688 // overall construct type-dependent / a dependent type. This is strictly
2689 // best-effort for now; we may fail to match at all for a dependent type
2690 // in some cases if this is set.
2691 bool IgnoreNonTypeDependent;
2692
2693 bool Match;
2694 SourceLocation MatchLoc;
2695
2696 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2697 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2698 Match(false) {}
2699
2700 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2701 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2702 NamedDecl *ND = Params->getParam(Idx: 0);
2703 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2704 Depth = PD->getDepth();
2705 } else if (NonTypeTemplateParmDecl *PD =
2706 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2707 Depth = PD->getDepth();
2708 } else {
2709 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2710 }
2711 }
2712
2713 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2714 if (ParmDepth >= Depth) {
2715 Match = true;
2716 MatchLoc = Loc;
2717 return true;
2718 }
2719 return false;
2720 }
2721
2722 bool TraverseStmt(Stmt *S) override {
2723 // Prune out non-type-dependent expressions if requested. This can
2724 // sometimes result in us failing to find a template parameter reference
2725 // (if a value-dependent expression creates a dependent type), but this
2726 // mode is best-effort only.
2727 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2728 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2729 return true;
2730 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2731 }
2732
2733 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2734 if (IgnoreNonTypeDependent && !TL.isNull() &&
2735 !TL.getType()->isDependentType())
2736 return true;
2737 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2738 }
2739
2740 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2741 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2742 }
2743
2744 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2745 // For a best-effort search, keep looking until we find a location.
2746 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2747 }
2748
2749 bool TraverseTemplateName(TemplateName N) override {
2750 if (TemplateTemplateParmDecl *PD =
2751 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2752 if (Matches(ParmDepth: PD->getDepth()))
2753 return false;
2754 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2755 }
2756
2757 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2758 if (NonTypeTemplateParmDecl *PD =
2759 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2760 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2761 return false;
2762 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2763 }
2764
2765 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2766 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2767 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2768 if (Matches(ParmDepth: TTP->getDepth(), Loc: ULE->getExprLoc()))
2769 return false;
2770 }
2771 for (auto &TLoc : ULE->template_arguments())
2772 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
2773 }
2774 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(S: ULE);
2775 }
2776
2777 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2778 return TraverseType(T: T->getReplacementType());
2779 }
2780
2781 bool VisitSubstTemplateTypeParmPackType(
2782 SubstTemplateTypeParmPackType *T) override {
2783 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2784 }
2785
2786 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2787 bool TraverseQualifier) override {
2788 // An InjectedClassNameType will never have a dependent template name,
2789 // so no need to traverse it.
2790 return TraverseTemplateArguments(
2791 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2792 }
2793};
2794} // end anonymous namespace
2795
2796/// Determines whether a given type depends on the given parameter
2797/// list.
2798static bool
2799DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2800 if (!Params->size())
2801 return false;
2802
2803 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2804 Checker.TraverseType(T);
2805 return Checker.Match;
2806}
2807
2808// Find the source range corresponding to the named type in the given
2809// nested-name-specifier, if any.
2810static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2811 QualType T,
2812 const CXXScopeSpec &SS) {
2813 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2814 for (;;) {
2815 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2816 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2817 break;
2818 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2819 return NNSLoc.castAsTypeLoc().getSourceRange();
2820 // FIXME: This will always be empty.
2821 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2822 }
2823
2824 return SourceRange();
2825}
2826
2827TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2828 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2829 TemplateIdAnnotation *TemplateId,
2830 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2831 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2832 IsMemberSpecialization = false;
2833 Invalid = false;
2834
2835 // The sequence of nested types to which we will match up the template
2836 // parameter lists. We first build this list by starting with the type named
2837 // by the nested-name-specifier and walking out until we run out of types.
2838 SmallVector<QualType, 4> NestedTypes;
2839 QualType T;
2840 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2841 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2842 if (CXXRecordDecl *Record =
2843 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2844 T = Context.getCanonicalTagType(TD: Record);
2845 else
2846 T = QualType(Qualifier.getAsType(), 0);
2847 }
2848
2849 // If we found an explicit specialization that prevents us from needing
2850 // 'template<>' headers, this will be set to the location of that
2851 // explicit specialization.
2852 SourceLocation ExplicitSpecLoc;
2853
2854 while (!T.isNull()) {
2855 NestedTypes.push_back(Elt: T);
2856
2857 // Retrieve the parent of a record type.
2858 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2859 // If this type is an explicit specialization, we're done.
2860 if (ClassTemplateSpecializationDecl *Spec
2861 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2862 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2863 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2864 ExplicitSpecLoc = Spec->getLocation();
2865 break;
2866 }
2867 } else if (Record->getTemplateSpecializationKind()
2868 == TSK_ExplicitSpecialization) {
2869 ExplicitSpecLoc = Record->getLocation();
2870 break;
2871 }
2872
2873 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2874 T = Context.getTypeDeclType(Decl: Parent);
2875 else
2876 T = QualType();
2877 continue;
2878 }
2879
2880 if (const TemplateSpecializationType *TST
2881 = T->getAs<TemplateSpecializationType>()) {
2882 TemplateName Name = TST->getTemplateName();
2883 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2884 // Look one step prior in a dependent template specialization type.
2885 if (NestedNameSpecifier NNS = DTS->getQualifier();
2886 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2887 T = QualType(NNS.getAsType(), 0);
2888 else
2889 T = QualType();
2890 continue;
2891 }
2892 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2893 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2894 T = Context.getTypeDeclType(Decl: Parent);
2895 else
2896 T = QualType();
2897 continue;
2898 }
2899 }
2900
2901 // Look one step prior in a dependent name type.
2902 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2903 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2904 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2905 T = QualType(NNS.getAsType(), 0);
2906 else
2907 T = QualType();
2908 continue;
2909 }
2910
2911 // Retrieve the parent of an enumeration type.
2912 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2913 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2914 // check here.
2915 EnumDecl *Enum = EnumT->getDecl();
2916
2917 // Get to the parent type.
2918 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2919 T = Context.getCanonicalTypeDeclType(TD: Parent);
2920 else
2921 T = QualType();
2922 continue;
2923 }
2924
2925 T = QualType();
2926 }
2927 // Reverse the nested types list, since we want to traverse from the outermost
2928 // to the innermost while checking template-parameter-lists.
2929 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2930
2931 // C++0x [temp.expl.spec]p17:
2932 // A member or a member template may be nested within many
2933 // enclosing class templates. In an explicit specialization for
2934 // such a member, the member declaration shall be preceded by a
2935 // template<> for each enclosing class template that is
2936 // explicitly specialized.
2937 bool SawNonEmptyTemplateParameterList = false;
2938
2939 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2940 if (SawNonEmptyTemplateParameterList) {
2941 if (!SuppressDiagnostic)
2942 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2943 << !Recovery << Range;
2944 Invalid = true;
2945 IsMemberSpecialization = false;
2946 return true;
2947 }
2948
2949 return false;
2950 };
2951
2952 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2953 // Check that we can have an explicit specialization here.
2954 if (CheckExplicitSpecialization(Range, true))
2955 return true;
2956
2957 // We don't have a template header, but we should.
2958 SourceLocation ExpectedTemplateLoc;
2959 if (!ParamLists.empty())
2960 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2961 else
2962 ExpectedTemplateLoc = DeclStartLoc;
2963
2964 if (!SuppressDiagnostic)
2965 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2966 << Range
2967 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2968 return false;
2969 };
2970
2971 unsigned ParamIdx = 0;
2972 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2973 ++TypeIdx) {
2974 T = NestedTypes[TypeIdx];
2975
2976 // Whether we expect a 'template<>' header.
2977 bool NeedEmptyTemplateHeader = false;
2978
2979 // Whether we expect a template header with parameters.
2980 bool NeedNonemptyTemplateHeader = false;
2981
2982 // For a dependent type, the set of template parameters that we
2983 // expect to see.
2984 TemplateParameterList *ExpectedTemplateParams = nullptr;
2985
2986 // C++0x [temp.expl.spec]p15:
2987 // A member or a member template may be nested within many enclosing
2988 // class templates. In an explicit specialization for such a member, the
2989 // member declaration shall be preceded by a template<> for each
2990 // enclosing class template that is explicitly specialized.
2991 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2992 if (ClassTemplatePartialSpecializationDecl *Partial
2993 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
2994 ExpectedTemplateParams = Partial->getTemplateParameters();
2995 NeedNonemptyTemplateHeader = true;
2996 } else if (Record->isDependentType()) {
2997 if (Record->getDescribedClassTemplate()) {
2998 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2999 ->getTemplateParameters();
3000 NeedNonemptyTemplateHeader = true;
3001 }
3002 } else if (ClassTemplateSpecializationDecl *Spec
3003 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3004 // C++0x [temp.expl.spec]p4:
3005 // Members of an explicitly specialized class template are defined
3006 // in the same manner as members of normal classes, and not using
3007 // the template<> syntax.
3008 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3009 NeedEmptyTemplateHeader = true;
3010 else
3011 continue;
3012 } else if (Record->getTemplateSpecializationKind()) {
3013 if (Record->getTemplateSpecializationKind()
3014 != TSK_ExplicitSpecialization &&
3015 TypeIdx == NumTypes - 1)
3016 IsMemberSpecialization = true;
3017
3018 continue;
3019 }
3020 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3021 TemplateName Name = TST->getTemplateName();
3022 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3023 ExpectedTemplateParams = Template->getTemplateParameters();
3024 NeedNonemptyTemplateHeader = true;
3025 } else if (Name.getAsDeducedTemplateName()) {
3026 // FIXME: We actually could/should check the template arguments here
3027 // against the corresponding template parameter list.
3028 NeedNonemptyTemplateHeader = false;
3029 }
3030 }
3031
3032 // C++ [temp.expl.spec]p16:
3033 // In an explicit specialization declaration for a member of a class
3034 // template or a member template that appears in namespace scope, the
3035 // member template and some of its enclosing class templates may remain
3036 // unspecialized, except that the declaration shall not explicitly
3037 // specialize a class member template if its enclosing class templates
3038 // are not explicitly specialized as well.
3039 if (ParamIdx < ParamLists.size()) {
3040 if (ParamLists[ParamIdx]->size() == 0) {
3041 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3042 false))
3043 return nullptr;
3044 } else
3045 SawNonEmptyTemplateParameterList = true;
3046 }
3047
3048 if (NeedEmptyTemplateHeader) {
3049 // If we're on the last of the types, and we need a 'template<>' header
3050 // here, then it's a member specialization.
3051 if (TypeIdx == NumTypes - 1)
3052 IsMemberSpecialization = true;
3053
3054 if (ParamIdx < ParamLists.size()) {
3055 if (ParamLists[ParamIdx]->size() > 0) {
3056 // The header has template parameters when it shouldn't. Complain.
3057 if (!SuppressDiagnostic)
3058 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3059 DiagID: diag::err_template_param_list_matches_nontemplate)
3060 << T
3061 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3062 ParamLists[ParamIdx]->getRAngleLoc())
3063 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3064 Invalid = true;
3065 return nullptr;
3066 }
3067
3068 // Consume this template header.
3069 ++ParamIdx;
3070 continue;
3071 }
3072
3073 if (!IsFriend)
3074 if (DiagnoseMissingExplicitSpecialization(
3075 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3076 return nullptr;
3077
3078 continue;
3079 }
3080
3081 if (NeedNonemptyTemplateHeader) {
3082 // In friend declarations we can have template-ids which don't
3083 // depend on the corresponding template parameter lists. But
3084 // assume that empty parameter lists are supposed to match this
3085 // template-id.
3086 if (IsFriend && T->isDependentType()) {
3087 if (ParamIdx < ParamLists.size() &&
3088 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3089 ExpectedTemplateParams = nullptr;
3090 else
3091 continue;
3092 }
3093
3094 if (ParamIdx < ParamLists.size()) {
3095 // Check the template parameter list, if we can.
3096 if (ExpectedTemplateParams &&
3097 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3098 Old: ExpectedTemplateParams,
3099 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3100 Invalid = true;
3101
3102 if (!Invalid &&
3103 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3104 TPC: TPC_ClassTemplateMember))
3105 Invalid = true;
3106
3107 ++ParamIdx;
3108 continue;
3109 }
3110
3111 if (!SuppressDiagnostic)
3112 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3113 << T
3114 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3115 Invalid = true;
3116 continue;
3117 }
3118 }
3119
3120 // If there were at least as many template-ids as there were template
3121 // parameter lists, then there are no template parameter lists remaining for
3122 // the declaration itself.
3123 if (ParamIdx >= ParamLists.size()) {
3124 if (TemplateId && !IsFriend) {
3125 // We don't have a template header for the declaration itself, but we
3126 // should.
3127 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3128 TemplateId->RAngleLoc));
3129
3130 // Fabricate an empty template parameter list for the invented header.
3131 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3132 LAngleLoc: SourceLocation(), Params: {},
3133 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3134 }
3135
3136 return nullptr;
3137 }
3138
3139 // If there were too many template parameter lists, complain about that now.
3140 if (ParamIdx < ParamLists.size() - 1) {
3141 bool HasAnyExplicitSpecHeader = false;
3142 bool AllExplicitSpecHeaders = true;
3143 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3144 if (ParamLists[I]->size() == 0)
3145 HasAnyExplicitSpecHeader = true;
3146 else
3147 AllExplicitSpecHeaders = false;
3148 }
3149
3150 if (!SuppressDiagnostic)
3151 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3152 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3153 : diag::err_template_spec_extra_headers)
3154 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3155 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3156
3157 // If there was a specialization somewhere, such that 'template<>' is
3158 // not required, and there were any 'template<>' headers, note where the
3159 // specialization occurred.
3160 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3161 !SuppressDiagnostic)
3162 Diag(Loc: ExplicitSpecLoc,
3163 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3164 << NestedTypes.back();
3165
3166 // We have a template parameter list with no corresponding scope, which
3167 // means that the resulting template declaration can't be instantiated
3168 // properly (we'll end up with dependent nodes when we shouldn't).
3169 if (!AllExplicitSpecHeaders)
3170 Invalid = true;
3171 }
3172
3173 // C++ [temp.expl.spec]p16:
3174 // In an explicit specialization declaration for a member of a class
3175 // template or a member template that ap- pears in namespace scope, the
3176 // member template and some of its enclosing class templates may remain
3177 // unspecialized, except that the declaration shall not explicitly
3178 // specialize a class member template if its en- closing class templates
3179 // are not explicitly specialized as well.
3180 if (ParamLists.back()->size() == 0 &&
3181 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3182 false))
3183 return nullptr;
3184
3185 // Return the last template parameter list, which corresponds to the
3186 // entity being declared.
3187 return ParamLists.back();
3188}
3189
3190void Sema::NoteAllFoundTemplates(TemplateName Name) {
3191 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3192 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3193 << (isa<FunctionTemplateDecl>(Val: Template)
3194 ? 0
3195 : isa<ClassTemplateDecl>(Val: Template)
3196 ? 1
3197 : isa<VarTemplateDecl>(Val: Template)
3198 ? 2
3199 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3200 << Template->getDeclName();
3201 return;
3202 }
3203
3204 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3205 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3206 IEnd = OST->end();
3207 I != IEnd; ++I)
3208 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3209 << 0 << (*I)->getDeclName();
3210
3211 return;
3212 }
3213}
3214
3215static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3216 TemplateName BaseTemplate,
3217 SourceLocation TemplateLoc,
3218 ArrayRef<TemplateArgument> Ts) {
3219 auto lookUpCommonType = [&](TemplateArgument T1,
3220 TemplateArgument T2) -> QualType {
3221 // Don't bother looking for other specializations if both types are
3222 // builtins - users aren't allowed to specialize for them
3223 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3224 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3225 Ts: {T1, T2});
3226
3227 TemplateArgumentListInfo Args;
3228 Args.addArgument(Loc: TemplateArgumentLoc(
3229 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3230 Args.addArgument(Loc: TemplateArgumentLoc(
3231 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3232
3233 EnterExpressionEvaluationContext UnevaluatedContext(
3234 S, Sema::ExpressionEvaluationContext::Unevaluated);
3235 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3236 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3237
3238 QualType BaseTemplateInst = S.CheckTemplateIdType(
3239 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3240 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3241
3242 if (SFINAE.hasErrorOccurred())
3243 return QualType();
3244
3245 return BaseTemplateInst;
3246 };
3247
3248 // Note A: For the common_type trait applied to a template parameter pack T of
3249 // types, the member type shall be either defined or not present as follows:
3250 switch (Ts.size()) {
3251
3252 // If sizeof...(T) is zero, there shall be no member type.
3253 case 0:
3254 return QualType();
3255
3256 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3257 // pack T. The member typedef-name type shall denote the same type, if any, as
3258 // common_type_t<T0, T0>; otherwise there shall be no member type.
3259 case 1:
3260 return lookUpCommonType(Ts[0], Ts[0]);
3261
3262 // If sizeof...(T) is two, let the first and second types constituting T be
3263 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3264 // as decay_t<T1> and decay_t<T2>, respectively.
3265 case 2: {
3266 QualType T1 = Ts[0].getAsType();
3267 QualType T2 = Ts[1].getAsType();
3268 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3269 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3270
3271 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3272 // the same type, if any, as common_type_t<D1, D2>.
3273 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3274 return lookUpCommonType(D1, D2);
3275
3276 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3277 // denotes a valid type, let C denote that type.
3278 {
3279 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3280 EnterExpressionEvaluationContext UnevaluatedContext(
3281 S, Sema::ExpressionEvaluationContext::Unevaluated);
3282 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3283 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3284
3285 // false
3286 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3287 VK_PRValue);
3288 ExprResult Cond = &CondExpr;
3289
3290 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3291 if (ConstRefQual) {
3292 D1.addConst();
3293 D2.addConst();
3294 }
3295
3296 // declval<D1>()
3297 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3298 ExprResult LHS = &LHSExpr;
3299
3300 // declval<D2>()
3301 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3302 ExprResult RHS = &RHSExpr;
3303
3304 ExprValueKind VK = VK_PRValue;
3305 ExprObjectKind OK = OK_Ordinary;
3306
3307 // decltype(false ? declval<D1>() : declval<D2>())
3308 QualType Result =
3309 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3310
3311 if (Result.isNull() || SFINAE.hasErrorOccurred())
3312 return QualType();
3313
3314 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3315 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3316 };
3317
3318 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3319 return Res;
3320
3321 // Let:
3322 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3323 // COND-RES(X, Y) be
3324 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3325
3326 // C++20 only
3327 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3328 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3329 if (!S.Context.getLangOpts().CPlusPlus20)
3330 return QualType();
3331 return CheckConditionalOperands(true);
3332 }
3333 }
3334
3335 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3336 // denote the first, second, and (pack of) remaining types constituting T. Let
3337 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3338 // a type C, the member typedef-name type shall denote the same type, if any,
3339 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3340 default: {
3341 QualType Result = Ts.front().getAsType();
3342 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3343 Result = lookUpCommonType(Result, T.getAsType());
3344 if (Result.isNull())
3345 return QualType();
3346 }
3347 return Result;
3348 }
3349 }
3350}
3351
3352static bool isInVkNamespace(const RecordType *RT) {
3353 DeclContext *DC = RT->getDecl()->getDeclContext();
3354 if (!DC)
3355 return false;
3356
3357 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3358 if (!ND)
3359 return false;
3360
3361 return ND->getQualifiedNameAsString() == "hlsl::vk";
3362}
3363
3364static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3365 QualType OperandArg,
3366 SourceLocation Loc) {
3367 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3368 bool Literal = false;
3369 SourceLocation LiteralLoc;
3370 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3371 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3372 assert(SpecDecl);
3373
3374 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3375 QualType ConstantType = LiteralArgs[0].getAsType();
3376 RT = ConstantType->getAsCanonical<RecordType>();
3377 Literal = true;
3378 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3379 }
3380
3381 if (RT && isInVkNamespace(RT) &&
3382 RT->getDecl()->getName() == "integral_constant") {
3383 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3384 assert(SpecDecl);
3385
3386 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3387
3388 QualType ConstantType = ConstantArgs[0].getAsType();
3389 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3390
3391 if (Literal)
3392 return SpirvOperand::createLiteral(Val: Value);
3393 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3394 } else if (Literal) {
3395 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3396 return SpirvOperand();
3397 }
3398 }
3399 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3400 DiagID: diag::err_call_incomplete_argument))
3401 return SpirvOperand();
3402 return SpirvOperand::createType(T: OperandArg);
3403}
3404
3405static QualType checkBuiltinTemplateIdType(
3406 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3407 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3408 TemplateArgumentListInfo &TemplateArgs) {
3409 ASTContext &Context = SemaRef.getASTContext();
3410
3411 switch (BTD->getBuiltinTemplateKind()) {
3412 case BTK__make_integer_seq: {
3413 // Specializations of __make_integer_seq<S, T, N> are treated like
3414 // S<T, 0, ..., N-1>.
3415
3416 QualType OrigType = Converted[1].getAsType();
3417 // C++14 [inteseq.intseq]p1:
3418 // T shall be an integer type.
3419 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3420 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3421 DiagID: diag::err_integer_sequence_integral_element_type);
3422 return QualType();
3423 }
3424
3425 TemplateArgument NumArgsArg = Converted[2];
3426 if (NumArgsArg.isDependent())
3427 return QualType();
3428
3429 TemplateArgumentListInfo SyntheticTemplateArgs;
3430 // The type argument, wrapped in substitution sugar, gets reused as the
3431 // first template argument in the synthetic template argument list.
3432 SyntheticTemplateArgs.addArgument(
3433 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3434 SemaRef.Context.getTrivialTypeSourceInfo(
3435 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3436
3437 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3438 // Expand N into 0 ... N-1.
3439 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3440 I < NumArgs; ++I) {
3441 TemplateArgument TA(Context, I, OrigType);
3442 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3443 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3444 }
3445 } else {
3446 // C++14 [inteseq.make]p1:
3447 // If N is negative the program is ill-formed.
3448 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3449 DiagID: diag::err_integer_sequence_negative_length);
3450 return QualType();
3451 }
3452
3453 // The first template argument will be reused as the template decl that
3454 // our synthetic template arguments will be applied to.
3455 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3456 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3457 /*Scope=*/nullptr,
3458 /*ForNestedNameSpecifier=*/false);
3459 }
3460
3461 case BTK__type_pack_element: {
3462 // Specializations of
3463 // __type_pack_element<Index, T_1, ..., T_N>
3464 // are treated like T_Index.
3465 assert(Converted.size() == 2 &&
3466 "__type_pack_element should be given an index and a parameter pack");
3467
3468 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3469 if (IndexArg.isDependent() || Ts.isDependent())
3470 return QualType();
3471
3472 llvm::APSInt Index = IndexArg.getAsIntegral();
3473 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3474 "type std::size_t, and hence be non-negative");
3475 // If the Index is out of bounds, the program is ill-formed.
3476 if (Index >= Ts.pack_size()) {
3477 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3478 DiagID: diag::err_type_pack_element_out_of_bounds);
3479 return QualType();
3480 }
3481
3482 // We simply return the type at index `Index`.
3483 int64_t N = Index.getExtValue();
3484 return Ts.getPackAsArray()[N].getAsType();
3485 }
3486
3487 case BTK__builtin_common_type: {
3488 assert(Converted.size() == 4);
3489 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3490 return QualType();
3491
3492 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3493 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3494 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3495 TemplateLoc, Ts);
3496 !CT.isNull()) {
3497 TemplateArgumentListInfo TAs;
3498 TAs.addArgument(Loc: TemplateArgumentLoc(
3499 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3500 T: CT, Loc: TemplateArgs[1].getLocation())));
3501 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3502 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3503 TemplateArgs&: TAs, /*Scope=*/nullptr,
3504 /*ForNestedNameSpecifier=*/false);
3505 }
3506 QualType HasNoTypeMember = Converted[2].getAsType();
3507 return HasNoTypeMember;
3508 }
3509
3510 case BTK__hlsl_spirv_type: {
3511 assert(Converted.size() == 4);
3512
3513 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3514 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3515 }
3516
3517 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3518 return QualType();
3519
3520 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3521 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3522 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3523
3524 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3525
3526 llvm::SmallVector<SpirvOperand> Operands;
3527
3528 for (auto &OperandTA : OperandArgs) {
3529 QualType OperandArg = OperandTA.getAsType();
3530 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3531 Loc: TemplateArgs[3].getLocation());
3532 if (!Operand.isValid())
3533 return QualType();
3534 Operands.push_back(Elt: Operand);
3535 }
3536
3537 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3538 }
3539 case BTK__builtin_dedup_pack: {
3540 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3541 "a parameter pack");
3542 TemplateArgument Ts = Converted[0];
3543 // Delay the computation until we can compute the final result. We choose
3544 // not to remove the duplicates upfront before substitution to keep the code
3545 // simple.
3546 if (Ts.isDependent())
3547 return QualType();
3548 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3549 llvm::SmallVector<TemplateArgument> OutArgs;
3550 llvm::SmallDenseSet<QualType> Seen;
3551 // Synthesize a new template argument list, removing duplicates.
3552 for (auto T : Ts.getPackAsArray()) {
3553 assert(T.getKind() == clang::TemplateArgument::Type);
3554 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3555 continue;
3556 OutArgs.push_back(Elt: T);
3557 }
3558 return Context.getSubstBuiltinTemplatePack(
3559 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3560 }
3561 }
3562 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3563}
3564
3565/// Determine whether this alias template is "enable_if_t".
3566/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3567static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3568 return AliasTemplate->getName() == "enable_if_t" ||
3569 AliasTemplate->getName() == "__enable_if_t";
3570}
3571
3572/// Collect all of the separable terms in the given condition, which
3573/// might be a conjunction.
3574///
3575/// FIXME: The right answer is to convert the logical expression into
3576/// disjunctive normal form, so we can find the first failed term
3577/// within each possible clause.
3578static void collectConjunctionTerms(Expr *Clause,
3579 SmallVectorImpl<Expr *> &Terms) {
3580 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3581 if (BinOp->getOpcode() == BO_LAnd) {
3582 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3583 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3584 return;
3585 }
3586 }
3587
3588 Terms.push_back(Elt: Clause);
3589}
3590
3591// The ranges-v3 library uses an odd pattern of a top-level "||" with
3592// a left-hand side that is value-dependent but never true. Identify
3593// the idiom and ignore that term.
3594static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3595 // Top-level '||'.
3596 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3597 if (!BinOp) return Cond;
3598
3599 if (BinOp->getOpcode() != BO_LOr) return Cond;
3600
3601 // With an inner '==' that has a literal on the right-hand side.
3602 Expr *LHS = BinOp->getLHS();
3603 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3604 if (!InnerBinOp) return Cond;
3605
3606 if (InnerBinOp->getOpcode() != BO_EQ ||
3607 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3608 return Cond;
3609
3610 // If the inner binary operation came from a macro expansion named
3611 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3612 // of the '||', which is the real, user-provided condition.
3613 SourceLocation Loc = InnerBinOp->getExprLoc();
3614 if (!Loc.isMacroID()) return Cond;
3615
3616 StringRef MacroName = PP.getImmediateMacroName(Loc);
3617 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3618 return BinOp->getRHS();
3619
3620 return Cond;
3621}
3622
3623namespace {
3624
3625// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3626// within failing boolean expression, such as substituting template parameters
3627// for actual types.
3628class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3629public:
3630 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3631 : Policy(P) {}
3632
3633 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3634 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3635 if (DR && DR->getQualifier()) {
3636 // If this is a qualified name, expand the template arguments in nested
3637 // qualifiers.
3638 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3639 // Then print the decl itself.
3640 const ValueDecl *VD = DR->getDecl();
3641 OS << VD->getName();
3642 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3643 // This is a template variable, print the expanded template arguments.
3644 printTemplateArgumentList(
3645 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3646 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3647 }
3648 return true;
3649 }
3650 return false;
3651 }
3652
3653private:
3654 const PrintingPolicy Policy;
3655};
3656
3657} // end anonymous namespace
3658
3659std::pair<Expr *, std::string>
3660Sema::findFailedBooleanCondition(Expr *Cond) {
3661 Cond = lookThroughRangesV3Condition(PP, Cond);
3662
3663 // Separate out all of the terms in a conjunction.
3664 SmallVector<Expr *, 4> Terms;
3665 collectConjunctionTerms(Clause: Cond, Terms);
3666
3667 // Determine which term failed.
3668 Expr *FailedCond = nullptr;
3669 for (Expr *Term : Terms) {
3670 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3671
3672 // Literals are uninteresting.
3673 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3674 isa<IntegerLiteral>(Val: TermAsWritten))
3675 continue;
3676
3677 // The initialization of the parameter from the argument is
3678 // a constant-evaluated context.
3679 EnterExpressionEvaluationContext ConstantEvaluated(
3680 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3681
3682 bool Succeeded;
3683 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3684 !Succeeded) {
3685 FailedCond = TermAsWritten;
3686 break;
3687 }
3688 }
3689 if (!FailedCond)
3690 FailedCond = Cond->IgnoreParenImpCasts();
3691
3692 std::string Description;
3693 {
3694 llvm::raw_string_ostream Out(Description);
3695 PrintingPolicy Policy = getPrintingPolicy();
3696 Policy.PrintAsCanonical = true;
3697 FailedBooleanConditionPrinterHelper Helper(Policy);
3698 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3699 }
3700 return { FailedCond, Description };
3701}
3702
3703static TemplateName
3704resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3705 const AssumedTemplateStorage *ATN,
3706 SourceLocation NameLoc) {
3707 // We assumed this undeclared identifier to be an (ADL-only) function
3708 // template name, but it was used in a context where a type was required.
3709 // Try to typo-correct it now.
3710 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3711 struct CandidateCallback : CorrectionCandidateCallback {
3712 bool ValidateCandidate(const TypoCorrection &TC) override {
3713 return TC.getCorrectionDecl() &&
3714 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3715 }
3716 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3717 return std::make_unique<CandidateCallback>(args&: *this);
3718 }
3719 } FilterCCC;
3720
3721 TypoCorrection Corrected =
3722 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3723 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3724 if (Corrected && Corrected.getFoundDecl()) {
3725 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3726 << ATN->getDeclName());
3727 return S.Context.getQualifiedTemplateName(
3728 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3729 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3730 }
3731
3732 return TemplateName();
3733}
3734
3735QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3736 TemplateName Name,
3737 SourceLocation TemplateLoc,
3738 TemplateArgumentListInfo &TemplateArgs,
3739 Scope *Scope, bool ForNestedNameSpecifier) {
3740 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3741
3742 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3743 if (!Template) {
3744 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3745 Template = S->getParameterPack();
3746 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3747 if (DTN->getName().getIdentifier())
3748 // When building a template-id where the template-name is dependent,
3749 // assume the template is a type template. Either our assumption is
3750 // correct, or the code is ill-formed and will be diagnosed when the
3751 // dependent name is substituted.
3752 return Context.getTemplateSpecializationType(Keyword, T: Name,
3753 SpecifiedArgs: TemplateArgs.arguments(),
3754 /*CanonicalArgs=*/{});
3755 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3756 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3757 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3758 CorrectedName.isNull()) {
3759 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3760 return QualType();
3761 } else {
3762 Name = CorrectedName;
3763 Template = Name.getAsTemplateDecl();
3764 }
3765 }
3766 }
3767 if (!Template ||
3768 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3769 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3770 if (ForNestedNameSpecifier)
3771 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3772 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3773 else
3774 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3775 NoteAllFoundTemplates(Name);
3776 return QualType();
3777 }
3778
3779 // Check that the template argument list is well-formed for this
3780 // template.
3781 CheckTemplateArgumentInfo CTAI;
3782 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3783 DefaultArgs, /*PartialTemplateArgs=*/false,
3784 CTAI,
3785 /*UpdateArgsWithConversions=*/true))
3786 return QualType();
3787
3788 QualType CanonType;
3789
3790 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3791 // We might have a substituted template template parameter pack. If so,
3792 // build a template specialization type for it.
3793 } else if (TypeAliasTemplateDecl *AliasTemplate =
3794 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3795
3796 // C++0x [dcl.type.elab]p2:
3797 // If the identifier resolves to a typedef-name or the simple-template-id
3798 // resolves to an alias template specialization, the
3799 // elaborated-type-specifier is ill-formed.
3800 if (Keyword != ElaboratedTypeKeyword::None &&
3801 Keyword != ElaboratedTypeKeyword::Typename) {
3802 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3803 << AliasTemplate << NonTagKind::TypeAliasTemplate
3804 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3805 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3806 }
3807
3808 // Find the canonical type for this type alias template specialization.
3809 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3810 if (Pattern->isInvalidDecl())
3811 return QualType();
3812
3813 // Only substitute for the innermost template argument list.
3814 MultiLevelTemplateArgumentList TemplateArgLists;
3815 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3816 /*Final=*/true);
3817 TemplateArgLists.addOuterRetainedLevels(
3818 Num: AliasTemplate->getTemplateParameters()->getDepth());
3819
3820 LocalInstantiationScope Scope(*this);
3821
3822 // Diagnose uses of this alias.
3823 (void)DiagnoseUseOfDecl(D: AliasTemplate, Locs: TemplateLoc);
3824
3825 // FIXME: The TemplateArgs passed here are not used for the context note,
3826 // nor they should, because this note will be pointing to the specialization
3827 // anyway. These arguments are needed for a hack for instantiating lambdas
3828 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3829 // arguments will be used for collating the template arguments needed to
3830 // instantiate the lambda.
3831 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3832 /*Entity=*/AliasTemplate,
3833 /*TemplateArgs=*/CTAI.SugaredConverted);
3834 if (Inst.isInvalid())
3835 return QualType();
3836
3837 std::optional<ContextRAII> SavedContext;
3838 if (!AliasTemplate->getDeclContext()->isFileContext())
3839 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3840
3841 CanonType =
3842 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3843 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3844 if (CanonType.isNull()) {
3845 // If this was enable_if and we failed to find the nested type
3846 // within enable_if in a SFINAE context, dig out the specific
3847 // enable_if condition that failed and present that instead.
3848 if (isEnableIfAliasTemplate(AliasTemplate)) {
3849 if (SFINAETrap *Trap = getSFINAEContext();
3850 TemplateDeductionInfo *DeductionInfo =
3851 Trap ? Trap->getDeductionInfo() : nullptr) {
3852 if (DeductionInfo->hasSFINAEDiagnostic() &&
3853 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3854 diag::err_typename_nested_not_found_enable_if &&
3855 TemplateArgs[0].getArgument().getKind() ==
3856 TemplateArgument::Expression) {
3857 Expr *FailedCond;
3858 std::string FailedDescription;
3859 std::tie(args&: FailedCond, args&: FailedDescription) =
3860 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3861
3862 // Remove the old SFINAE diagnostic.
3863 PartialDiagnosticAt OldDiag =
3864 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3865 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3866
3867 // Add a new SFINAE diagnostic specifying which condition
3868 // failed.
3869 DeductionInfo->addSFINAEDiagnostic(
3870 Loc: OldDiag.first,
3871 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3872 << FailedDescription << FailedCond->getSourceRange());
3873 }
3874 }
3875 }
3876
3877 return QualType();
3878 }
3879 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3880 CanonType = checkBuiltinTemplateIdType(
3881 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3882 } else if (Name.isDependent() ||
3883 TemplateSpecializationType::anyDependentTemplateArguments(
3884 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3885 // This class template specialization is a dependent
3886 // type. Therefore, its canonical type is another class template
3887 // specialization type that contains all of the converted
3888 // arguments in canonical form. This ensures that, e.g., A<T> and
3889 // A<T, T> have identical types when A is declared as:
3890 //
3891 // template<typename T, typename U = T> struct A;
3892 CanonType = Context.getCanonicalTemplateSpecializationType(
3893 Keyword: ElaboratedTypeKeyword::None,
3894 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3895 CanonicalArgs: CTAI.CanonicalConverted);
3896 assert(CanonType->isCanonicalUnqualified());
3897
3898 // This might work out to be a current instantiation, in which
3899 // case the canonical type needs to be the InjectedClassNameType.
3900 //
3901 // TODO: in theory this could be a simple hashtable lookup; most
3902 // changes to CurContext don't change the set of current
3903 // instantiations.
3904 if (isa<ClassTemplateDecl>(Val: Template)) {
3905 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3906 // If we get out to a namespace, we're done.
3907 if (Ctx->isFileContext()) break;
3908
3909 // If this isn't a record, keep looking.
3910 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3911 if (!Record) continue;
3912
3913 // Look for one of the two cases with InjectedClassNameTypes
3914 // and check whether it's the same template.
3915 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3916 !Record->getDescribedClassTemplate())
3917 continue;
3918
3919 // Fetch the injected class name type and check whether its
3920 // injected type is equal to the type we just built.
3921 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3922 CanQualType Injected =
3923 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3924
3925 if (CanonType != Injected)
3926 continue;
3927
3928 // If so, the canonical type of this TST is the injected
3929 // class name type of the record we just found.
3930 CanonType = ICNT;
3931 break;
3932 }
3933 }
3934 } else if (ClassTemplateDecl *ClassTemplate =
3935 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3936 // Find the class template specialization declaration that
3937 // corresponds to these arguments.
3938 void *InsertPos = nullptr;
3939 ClassTemplateSpecializationDecl *Decl =
3940 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3941 if (!Decl) {
3942 // This is the first time we have referenced this class template
3943 // specialization. Create the canonical declaration and add it to
3944 // the set of specializations.
3945 Decl = ClassTemplateSpecializationDecl::Create(
3946 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3947 DC: ClassTemplate->getDeclContext(),
3948 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3949 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3950 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3951 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3952 if (ClassTemplate->isOutOfLine())
3953 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3954 }
3955
3956 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3957 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3958 NonSFINAEContext _(*this);
3959 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3960 if (!Inst.isInvalid()) {
3961 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3962 CTAI.CanonicalConverted,
3963 /*Final=*/false);
3964 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
3965 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
3966 }
3967 }
3968
3969 // Diagnose uses of this specialization.
3970 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
3971
3972 CanonType = Context.getCanonicalTagType(TD: Decl);
3973 assert(isa<RecordType>(CanonType) &&
3974 "type of non-dependent specialization is not a RecordType");
3975 } else {
3976 llvm_unreachable("Unhandled template kind");
3977 }
3978
3979 // Build the fully-sugared type for this class template
3980 // specialization, which refers back to the class template
3981 // specialization we created or found.
3982 return Context.getTemplateSpecializationType(
3983 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
3984 Canon: CanonType);
3985}
3986
3987void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3988 TemplateNameKind &TNK,
3989 SourceLocation NameLoc,
3990 IdentifierInfo *&II) {
3991 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3992
3993 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
3994 assert(ATN && "not an assumed template name");
3995 II = ATN->getDeclName().getAsIdentifierInfo();
3996
3997 if (TemplateName Name =
3998 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
3999 !Name.isNull()) {
4000 // Resolved to a type template name.
4001 ParsedName = TemplateTy::make(P: Name);
4002 TNK = TNK_Type_template;
4003 }
4004}
4005
4006TypeResult Sema::ActOnTemplateIdType(
4007 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4008 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4009 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4010 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4011 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4012 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4013 ImplicitTypenameContext AllowImplicitTypename) {
4014 if (SS.isInvalid())
4015 return true;
4016
4017 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4018 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4019
4020 // C++ [temp.res]p3:
4021 // A qualified-id that refers to a type and in which the
4022 // nested-name-specifier depends on a template-parameter (14.6.2)
4023 // shall be prefixed by the keyword typename to indicate that the
4024 // qualified-id denotes a type, forming an
4025 // elaborated-type-specifier (7.1.5.3).
4026 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4027 // C++2a relaxes some of those restrictions in [temp.res]p5.
4028 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4029 NNS: SS.getScopeRep(), Name: TemplateII);
4030 NestedNameSpecifier NNS(DNT.getTypePtr());
4031 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4032 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4033 << NNS;
4034 if (!getLangOpts().CPlusPlus20)
4035 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4036 } else
4037 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4038
4039 // FIXME: This is not quite correct recovery as we don't transform SS
4040 // into the corresponding dependent form (and we don't diagnose missing
4041 // 'template' keywords within SS as a result).
4042 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4043 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4044 TemplateArgs: TemplateArgsIn, RAngleLoc);
4045 }
4046
4047 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4048 // it's not actually allowed to be used as a type in most cases. Because
4049 // we annotate it before we know whether it's valid, we have to check for
4050 // this case here.
4051 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4052 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4053 Diag(Loc: TemplateIILoc,
4054 DiagID: TemplateKWLoc.isInvalid()
4055 ? diag::err_out_of_line_qualified_id_type_names_constructor
4056 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4057 << TemplateII << 0 /*injected-class-name used as template name*/
4058 << 1 /*if any keyword was present, it was 'template'*/;
4059 }
4060 }
4061
4062 // Translate the parser's template argument list in our AST format.
4063 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4064 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4065
4066 QualType SpecTy = CheckTemplateIdType(
4067 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4068 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4069 if (SpecTy.isNull())
4070 return true;
4071
4072 // Build type-source information.
4073 TypeLocBuilder TLB;
4074 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4075 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4076 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4077 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4078}
4079
4080TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4081 TypeSpecifierType TagSpec,
4082 SourceLocation TagLoc,
4083 CXXScopeSpec &SS,
4084 SourceLocation TemplateKWLoc,
4085 TemplateTy TemplateD,
4086 SourceLocation TemplateLoc,
4087 SourceLocation LAngleLoc,
4088 ASTTemplateArgsPtr TemplateArgsIn,
4089 SourceLocation RAngleLoc) {
4090 if (SS.isInvalid())
4091 return TypeResult(true);
4092
4093 // Translate the parser's template argument list in our AST format.
4094 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4095 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4096
4097 // Determine the tag kind
4098 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4099 ElaboratedTypeKeyword Keyword
4100 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4101
4102 QualType Result =
4103 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4104 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4105 if (Result.isNull())
4106 return TypeResult(true);
4107
4108 // Check the tag kind
4109 if (const RecordType *RT = Result->getAs<RecordType>()) {
4110 RecordDecl *D = RT->getDecl();
4111
4112 IdentifierInfo *Id = D->getIdentifier();
4113 assert(Id && "templated class must have an identifier");
4114
4115 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4116 NewTagLoc: TagLoc, Name: Id)) {
4117 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4118 << Result
4119 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4120 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4121 }
4122 }
4123
4124 // Provide source-location information for the template specialization.
4125 TypeLocBuilder TLB;
4126 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4127 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4128 TAL: TemplateArgs);
4129 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4130}
4131
4132static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4133 NamedDecl *PrevDecl,
4134 SourceLocation Loc,
4135 bool IsPartialSpecialization);
4136
4137static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4138
4139static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4140 unsigned Depth,
4141 unsigned Index) {
4142 switch (Arg.getKind()) {
4143 case TemplateArgument::Null:
4144 case TemplateArgument::NullPtr:
4145 case TemplateArgument::Integral:
4146 case TemplateArgument::Declaration:
4147 case TemplateArgument::StructuralValue:
4148 case TemplateArgument::Pack:
4149 case TemplateArgument::TemplateExpansion:
4150 return false;
4151
4152 case TemplateArgument::Type: {
4153 QualType Type = Arg.getAsType();
4154 const TemplateTypeParmType *TPT =
4155 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4156 return TPT && !Type.hasQualifiers() &&
4157 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4158 }
4159
4160 case TemplateArgument::Expression: {
4161 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4162 if (!DRE || !DRE->getDecl())
4163 return false;
4164 const NonTypeTemplateParmDecl *NTTP =
4165 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4166 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4167 }
4168
4169 case TemplateArgument::Template:
4170 const TemplateTemplateParmDecl *TTP =
4171 dyn_cast_or_null<TemplateTemplateParmDecl>(
4172 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4173 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4174 }
4175 llvm_unreachable("unexpected kind of template argument");
4176}
4177
4178static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4179 TemplateParameterList *SpecParams,
4180 ArrayRef<TemplateArgument> Args) {
4181 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4182 return false;
4183
4184 unsigned Depth = Params->getDepth();
4185
4186 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4187 TemplateArgument Arg = Args[I];
4188
4189 // If the parameter is a pack expansion, the argument must be a pack
4190 // whose only element is a pack expansion.
4191 if (Params->getParam(Idx: I)->isParameterPack()) {
4192 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4193 !Arg.pack_begin()->isPackExpansion())
4194 return false;
4195 Arg = Arg.pack_begin()->getPackExpansionPattern();
4196 }
4197
4198 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4199 return false;
4200
4201 // For NTTPs further specialization is allowed via deduced types, so
4202 // we need to make sure to only reject here if primary template and
4203 // specialization use the same type for the NTTP.
4204 if (auto *SpecNTTP =
4205 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4206 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4207 if (!NTTP || NTTP->getType().getCanonicalType() !=
4208 SpecNTTP->getType().getCanonicalType())
4209 return false;
4210 }
4211 }
4212
4213 return true;
4214}
4215
4216template<typename PartialSpecDecl>
4217static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4218 if (Partial->getDeclContext()->isDependentContext())
4219 return;
4220
4221 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4222 // for non-substitution-failure issues?
4223 TemplateDeductionInfo Info(Partial->getLocation());
4224 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4225 return;
4226
4227 auto *Template = Partial->getSpecializedTemplate();
4228 S.Diag(Partial->getLocation(),
4229 diag::ext_partial_spec_not_more_specialized_than_primary)
4230 << isa<VarTemplateDecl>(Template);
4231
4232 if (Info.hasSFINAEDiagnostic()) {
4233 PartialDiagnosticAt Diag = {SourceLocation(),
4234 PartialDiagnostic::NullDiagnostic()};
4235 Info.takeSFINAEDiagnostic(PD&: Diag);
4236 SmallString<128> SFINAEArgString;
4237 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4238 S.Diag(Loc: Diag.first,
4239 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4240 << SFINAEArgString;
4241 }
4242
4243 S.NoteTemplateLocation(Decl: *Template);
4244 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4245 Template->getAssociatedConstraints(TemplateAC);
4246 Partial->getAssociatedConstraints(PartialAC);
4247 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4248 AC2: TemplateAC);
4249}
4250
4251static void
4252noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4253 const llvm::SmallBitVector &DeducibleParams) {
4254 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4255 if (!DeducibleParams[I]) {
4256 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4257 if (Param->getDeclName())
4258 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4259 << Param->getDeclName();
4260 else
4261 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4262 << "(anonymous)";
4263 }
4264 }
4265}
4266
4267
4268template<typename PartialSpecDecl>
4269static void checkTemplatePartialSpecialization(Sema &S,
4270 PartialSpecDecl *Partial) {
4271 // C++1z [temp.class.spec]p8: (DR1495)
4272 // - The specialization shall be more specialized than the primary
4273 // template (14.5.5.2).
4274 checkMoreSpecializedThanPrimary(S, Partial);
4275
4276 // C++ [temp.class.spec]p8: (DR1315)
4277 // - Each template-parameter shall appear at least once in the
4278 // template-id outside a non-deduced context.
4279 // C++1z [temp.class.spec.match]p3 (P0127R2)
4280 // If the template arguments of a partial specialization cannot be
4281 // deduced because of the structure of its template-parameter-list
4282 // and the template-id, the program is ill-formed.
4283 auto *TemplateParams = Partial->getTemplateParameters();
4284 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4285 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4286 TemplateParams->getDepth(), DeducibleParams);
4287
4288 if (!DeducibleParams.all()) {
4289 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4290 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4291 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4292 << (NumNonDeducible > 1)
4293 << SourceRange(Partial->getLocation(),
4294 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4295 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4296 }
4297}
4298
4299void Sema::CheckTemplatePartialSpecialization(
4300 ClassTemplatePartialSpecializationDecl *Partial) {
4301 checkTemplatePartialSpecialization(S&: *this, Partial);
4302}
4303
4304void Sema::CheckTemplatePartialSpecialization(
4305 VarTemplatePartialSpecializationDecl *Partial) {
4306 checkTemplatePartialSpecialization(S&: *this, Partial);
4307}
4308
4309void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4310 // C++1z [temp.param]p11:
4311 // A template parameter of a deduction guide template that does not have a
4312 // default-argument shall be deducible from the parameter-type-list of the
4313 // deduction guide template.
4314 auto *TemplateParams = TD->getTemplateParameters();
4315 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4316 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4317 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4318 // A parameter pack is deducible (to an empty pack).
4319 auto *Param = TemplateParams->getParam(Idx: I);
4320 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4321 DeducibleParams[I] = true;
4322 }
4323
4324 if (!DeducibleParams.all()) {
4325 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4326 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4327 << (NumNonDeducible > 1);
4328 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4329 }
4330}
4331
4332DeclResult Sema::ActOnVarTemplateSpecialization(
4333 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4334 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4335 StorageClass SC, bool IsPartialSpecialization) {
4336 // D must be variable template id.
4337 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4338 "Variable template specialization is declared with a template id.");
4339
4340 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4341 TemplateArgumentListInfo TemplateArgs =
4342 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4343 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4344 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4345 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4346
4347 TemplateName Name = TemplateId->Template.get();
4348
4349 // The template-id must name a variable template.
4350 VarTemplateDecl *VarTemplate =
4351 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4352 if (!VarTemplate) {
4353 NamedDecl *FnTemplate;
4354 if (auto *OTS = Name.getAsOverloadedTemplate())
4355 FnTemplate = *OTS->begin();
4356 else
4357 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4358 if (FnTemplate)
4359 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4360 << FnTemplate->getDeclName();
4361 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4362 << IsPartialSpecialization;
4363 }
4364
4365 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4366 auto Message = DSA->getMessage();
4367 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4368 << VarTemplate << !Message.empty() << Message;
4369 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4370 }
4371
4372 // Check for unexpanded parameter packs in any of the template arguments.
4373 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4374 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4375 UPPC: IsPartialSpecialization
4376 ? UPPC_PartialSpecialization
4377 : UPPC_ExplicitSpecialization))
4378 return true;
4379
4380 // Check that the template argument list is well-formed for this
4381 // template.
4382 CheckTemplateArgumentInfo CTAI;
4383 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4384 /*DefaultArgs=*/{},
4385 /*PartialTemplateArgs=*/false, CTAI,
4386 /*UpdateArgsWithConversions=*/true))
4387 return true;
4388
4389 // Find the variable template (partial) specialization declaration that
4390 // corresponds to these arguments.
4391 if (IsPartialSpecialization) {
4392 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4393 NumExplicitArgs: TemplateArgs.size(),
4394 Args: CTAI.CanonicalConverted))
4395 return true;
4396
4397 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4398 // we also do them during instantiation.
4399 if (!Name.isDependent() &&
4400 !TemplateSpecializationType::anyDependentTemplateArguments(
4401 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4402 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4403 << VarTemplate->getDeclName();
4404 IsPartialSpecialization = false;
4405 }
4406
4407 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4408 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4409 (!Context.getLangOpts().CPlusPlus20 ||
4410 !TemplateParams->hasAssociatedConstraints())) {
4411 // C++ [temp.class.spec]p9b3:
4412 //
4413 // -- The argument list of the specialization shall not be identical
4414 // to the implicit argument list of the primary template.
4415 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4416 << /*variable template*/ 1
4417 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4418 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4419 // FIXME: Recover from this by treating the declaration as a
4420 // redeclaration of the primary template.
4421 return true;
4422 }
4423 }
4424
4425 void *InsertPos = nullptr;
4426 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4427
4428 if (IsPartialSpecialization)
4429 PrevDecl = VarTemplate->findPartialSpecialization(
4430 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4431 else
4432 PrevDecl =
4433 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4434
4435 VarTemplateSpecializationDecl *Specialization = nullptr;
4436
4437 // Check whether we can declare a variable template specialization in
4438 // the current scope.
4439 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4440 Loc: TemplateNameLoc,
4441 IsPartialSpecialization))
4442 return true;
4443
4444 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4445 // Since the only prior variable template specialization with these
4446 // arguments was referenced but not declared, reuse that
4447 // declaration node as our own, updating its source location and
4448 // the list of outer template parameters to reflect our new declaration.
4449 Specialization = PrevDecl;
4450 Specialization->setLocation(TemplateNameLoc);
4451 PrevDecl = nullptr;
4452 } else if (IsPartialSpecialization) {
4453 // Create a new class template partial specialization declaration node.
4454 VarTemplatePartialSpecializationDecl *PrevPartial =
4455 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4456 VarTemplatePartialSpecializationDecl *Partial =
4457 VarTemplatePartialSpecializationDecl::Create(
4458 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4459 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4460 S: SC, Args: CTAI.CanonicalConverted);
4461 Partial->setTemplateArgsAsWritten(TemplateArgs);
4462
4463 if (!PrevPartial)
4464 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4465 Specialization = Partial;
4466
4467 // If we are providing an explicit specialization of a member variable
4468 // template specialization, make a note of that.
4469 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4470 PrevPartial->setMemberSpecialization();
4471
4472 CheckTemplatePartialSpecialization(Partial);
4473 } else {
4474 // Create a new class template specialization declaration node for
4475 // this explicit specialization or friend declaration.
4476 Specialization = VarTemplateSpecializationDecl::Create(
4477 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4478 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4479 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4480
4481 if (!PrevDecl)
4482 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4483 }
4484
4485 // C++ [temp.expl.spec]p6:
4486 // If a template, a member template or the member of a class template is
4487 // explicitly specialized then that specialization shall be declared
4488 // before the first use of that specialization that would cause an implicit
4489 // instantiation to take place, in every translation unit in which such a
4490 // use occurs; no diagnostic is required.
4491 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4492 bool Okay = false;
4493 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4494 // Is there any previous explicit specialization declaration?
4495 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4496 Okay = true;
4497 break;
4498 }
4499 }
4500
4501 if (!Okay) {
4502 SourceRange Range(TemplateNameLoc, RAngleLoc);
4503 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4504 << Name << Range;
4505
4506 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4507 DiagID: diag::note_instantiation_required_here)
4508 << (PrevDecl->getTemplateSpecializationKind() !=
4509 TSK_ImplicitInstantiation);
4510 return true;
4511 }
4512 }
4513
4514 Specialization->setLexicalDeclContext(CurContext);
4515
4516 // Add the specialization into its lexical context, so that it can
4517 // be seen when iterating through the list of declarations in that
4518 // context. However, specializations are not found by name lookup.
4519 CurContext->addDecl(D: Specialization);
4520
4521 // Note that this is an explicit specialization.
4522 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4523
4524 Previous.clear();
4525 if (PrevDecl)
4526 Previous.addDecl(D: PrevDecl);
4527 else if (Specialization->isStaticDataMember() &&
4528 Specialization->isOutOfLine())
4529 Specialization->setAccess(VarTemplate->getAccess());
4530
4531 return Specialization;
4532}
4533
4534namespace {
4535/// A partial specialization whose template arguments have matched
4536/// a given template-id.
4537struct PartialSpecMatchResult {
4538 VarTemplatePartialSpecializationDecl *Partial;
4539 TemplateArgumentList *Args;
4540};
4541
4542// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4543// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4544static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4545 if (Var->getName() != "format_kind" ||
4546 !Var->getDeclContext()->isStdNamespace())
4547 return false;
4548
4549 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4550 // release in which users can access std::format_kind.
4551 // We can use 20250520 as the final date, see the following commits.
4552 // GCC releases/gcc-15 branch:
4553 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4554 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4555 // GCC master branch:
4556 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4557 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4558 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4559}
4560} // end anonymous namespace
4561
4562DeclResult
4563Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4564 SourceLocation TemplateNameLoc,
4565 const TemplateArgumentListInfo &TemplateArgs,
4566 bool SetWrittenArgs) {
4567 assert(Template && "A variable template id without template?");
4568
4569 // Check that the template argument list is well-formed for this template.
4570 CheckTemplateArgumentInfo CTAI;
4571 if (CheckTemplateArgumentList(
4572 Template, TemplateLoc: TemplateNameLoc,
4573 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4574 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4575 /*UpdateArgsWithConversions=*/true))
4576 return true;
4577
4578 // Produce a placeholder value if the specialization is dependent.
4579 if (Template->getDeclContext()->isDependentContext() ||
4580 TemplateSpecializationType::anyDependentTemplateArguments(
4581 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4582 if (ParsingInitForAutoVars.empty())
4583 return DeclResult();
4584
4585 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4586 const TemplateArgument &Arg2) {
4587 return Context.isSameTemplateArgument(Arg1, Arg2);
4588 };
4589
4590 if (VarDecl *Var = Template->getTemplatedDecl();
4591 ParsingInitForAutoVars.count(Ptr: Var) &&
4592 // See comments on this function definition
4593 !IsLibstdcxxStdFormatKind(PP, Var) &&
4594 llvm::equal(
4595 LRange&: CTAI.CanonicalConverted,
4596 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4597 P: IsSameTemplateArg)) {
4598 Diag(Loc: TemplateNameLoc,
4599 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4600 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4601 return true;
4602 }
4603
4604 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4605 Template->getPartialSpecializations(PS&: PartialSpecs);
4606 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4607 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4608 llvm::equal(LRange&: CTAI.CanonicalConverted,
4609 RRange: Partial->getTemplateArgs().asArray(),
4610 P: IsSameTemplateArg)) {
4611 Diag(Loc: TemplateNameLoc,
4612 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4613 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4614 << Partial->getType();
4615 return true;
4616 }
4617
4618 return DeclResult();
4619 }
4620
4621 // Find the variable template specialization declaration that
4622 // corresponds to these arguments.
4623 void *InsertPos = nullptr;
4624 if (VarTemplateSpecializationDecl *Spec =
4625 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4626 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4627 if (Spec->getType()->isUndeducedType()) {
4628 if (ParsingInitForAutoVars.count(Ptr: Spec))
4629 Diag(Loc: TemplateNameLoc,
4630 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4631 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4632 << Spec->getType();
4633 else
4634 // We are substituting the initializer of this variable template
4635 // specialization.
4636 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4637 << Spec << Spec->getType();
4638
4639 return true;
4640 }
4641 // If we already have a variable template specialization, return it.
4642 return Spec;
4643 }
4644
4645 // This is the first time we have referenced this variable template
4646 // specialization. Create the canonical declaration and add it to
4647 // the set of specializations, based on the closest partial specialization
4648 // that it represents. That is,
4649 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4650 const TemplateArgumentList *PartialSpecArgs = nullptr;
4651 bool AmbiguousPartialSpec = false;
4652 typedef PartialSpecMatchResult MatchResult;
4653 SmallVector<MatchResult, 4> Matched;
4654 SourceLocation PointOfInstantiation = TemplateNameLoc;
4655 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4656 /*ForTakingAddress=*/false);
4657
4658 // 1. Attempt to find the closest partial specialization that this
4659 // specializes, if any.
4660 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4661 // Perhaps better after unification of DeduceTemplateArguments() and
4662 // getMoreSpecializedPartialSpecialization().
4663 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4664 Template->getPartialSpecializations(PS&: PartialSpecs);
4665
4666 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4667 // C++ [temp.spec.partial.member]p2:
4668 // If the primary member template is explicitly specialized for a given
4669 // (implicit) specialization of the enclosing class template, the partial
4670 // specializations of the member template are ignored for this
4671 // specialization of the enclosing class template. If a partial
4672 // specialization of the member template is explicitly specialized for a
4673 // given (implicit) specialization of the enclosing class template, the
4674 // primary member template and its other partial specializations are still
4675 // considered for this specialization of the enclosing class template.
4676 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4677 !Partial->getMostRecentDecl()->isMemberSpecialization())
4678 continue;
4679
4680 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4681
4682 if (TemplateDeductionResult Result =
4683 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4684 Result != TemplateDeductionResult::Success) {
4685 // Store the failed-deduction information for use in diagnostics, later.
4686 // TODO: Actually use the failed-deduction info?
4687 FailedCandidates.addCandidate().set(
4688 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4689 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4690 (void)Result;
4691 } else {
4692 Matched.push_back(Elt: PartialSpecMatchResult());
4693 Matched.back().Partial = Partial;
4694 Matched.back().Args = Info.takeSugared();
4695 }
4696 }
4697
4698 if (Matched.size() >= 1) {
4699 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4700 if (Matched.size() == 1) {
4701 // -- If exactly one matching specialization is found, the
4702 // instantiation is generated from that specialization.
4703 // We don't need to do anything for this.
4704 } else {
4705 // -- If more than one matching specialization is found, the
4706 // partial order rules (14.5.4.2) are used to determine
4707 // whether one of the specializations is more specialized
4708 // than the others. If none of the specializations is more
4709 // specialized than all of the other matching
4710 // specializations, then the use of the variable template is
4711 // ambiguous and the program is ill-formed.
4712 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4713 PEnd = Matched.end();
4714 P != PEnd; ++P) {
4715 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4716 Loc: PointOfInstantiation) ==
4717 P->Partial)
4718 Best = P;
4719 }
4720
4721 // Determine if the best partial specialization is more specialized than
4722 // the others.
4723 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4724 PEnd = Matched.end();
4725 P != PEnd; ++P) {
4726 if (P != Best && getMoreSpecializedPartialSpecialization(
4727 PS1: P->Partial, PS2: Best->Partial,
4728 Loc: PointOfInstantiation) != Best->Partial) {
4729 AmbiguousPartialSpec = true;
4730 break;
4731 }
4732 }
4733 }
4734
4735 // Instantiate using the best variable template partial specialization.
4736 InstantiationPattern = Best->Partial;
4737 PartialSpecArgs = Best->Args;
4738 } else {
4739 // -- If no match is found, the instantiation is generated
4740 // from the primary template.
4741 // InstantiationPattern = Template->getTemplatedDecl();
4742 }
4743
4744 // 2. Create the canonical declaration.
4745 // Note that we do not instantiate a definition until we see an odr-use
4746 // in DoMarkVarDeclReferenced().
4747 // FIXME: LateAttrs et al.?
4748 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4749 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4750 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4751 if (!Decl)
4752 return true;
4753 if (SetWrittenArgs)
4754 Decl->setTemplateArgsAsWritten(TemplateArgs);
4755
4756 if (AmbiguousPartialSpec) {
4757 // Partial ordering did not produce a clear winner. Complain.
4758 Decl->setInvalidDecl();
4759 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4760 << Decl;
4761
4762 // Print the matching partial specializations.
4763 for (MatchResult P : Matched)
4764 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4765 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4766 Args: *P.Args);
4767 return true;
4768 }
4769
4770 if (VarTemplatePartialSpecializationDecl *D =
4771 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4772 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4773
4774 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4775
4776 assert(Decl && "No variable template specialization?");
4777 return Decl;
4778}
4779
4780ExprResult Sema::CheckVarTemplateId(
4781 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4782 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4783 const TemplateArgumentListInfo *TemplateArgs) {
4784
4785 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4786 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4787 if (Decl.isInvalid())
4788 return ExprError();
4789
4790 if (!Decl.get())
4791 return ExprResult();
4792
4793 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4794 if (!Var->getTemplateSpecializationKind())
4795 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4796 PointOfInstantiation: NameInfo.getLoc());
4797
4798 // Build an ordinary singleton decl ref.
4799 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4800}
4801
4802ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4803 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4804 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
4805 const TemplateArgumentListInfo *TemplateArgs) {
4806 assert(Template && "A variable template id without template?");
4807
4808 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4809 Template->templateParameterKind() !=
4810 TemplateNameKind::TNK_Concept_template)
4811 return ExprResult();
4812
4813 // Check that the template argument list is well-formed for this template.
4814 CheckTemplateArgumentInfo CTAI;
4815 if (CheckTemplateArgumentList(
4816 Template, TemplateLoc,
4817 // FIXME: TemplateArgs will not be modified because
4818 // UpdateArgsWithConversions is false, however, we should
4819 // CheckTemplateArgumentList to be const-correct.
4820 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4821 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4822 /*UpdateArgsWithConversions=*/false))
4823 return true;
4824
4825 UnresolvedSet<1> R;
4826 R.addDecl(D: Template);
4827
4828 // FIXME: We model references to variable template and concept parameters
4829 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4830 // data, can generally be used in the same places and work the same way.
4831 // However, it might be cleaner to use a dedicated AST node in the long run.
4832 return UnresolvedLookupExpr::Create(
4833 Context: getASTContext(), NamingClass: nullptr, QualifierLoc: SS.getWithLocInContext(Context&: getASTContext()),
4834 TemplateKWLoc: SourceLocation(), NameInfo, RequiresADL: false, Args: TemplateArgs, Begin: R.begin(), End: R.end(),
4835 /*KnownDependent=*/false,
4836 /*KnownInstantiationDependent=*/false);
4837}
4838
4839void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4840 SourceLocation Loc) {
4841 Diag(Loc, DiagID: diag::err_template_missing_args)
4842 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4843 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4844 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4845 }
4846}
4847
4848void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4849 bool TemplateKeyword,
4850 TemplateDecl *TD,
4851 SourceLocation Loc) {
4852 TemplateName Name = Context.getQualifiedTemplateName(
4853 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4854 diagnoseMissingTemplateArguments(Name, Loc);
4855}
4856
4857ExprResult Sema::CheckConceptTemplateId(
4858 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4859 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4860 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4861 bool DoCheckConstraintSatisfaction) {
4862 assert(NamedConcept && "A concept template id without a template?");
4863
4864 if (NamedConcept->isInvalidDecl())
4865 return ExprError();
4866
4867 CheckTemplateArgumentInfo CTAI;
4868 if (CheckTemplateArgumentList(
4869 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4870 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4871 /*DefaultArgs=*/{},
4872 /*PartialTemplateArgs=*/false, CTAI,
4873 /*UpdateArgsWithConversions=*/false))
4874 return ExprError();
4875
4876 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4877
4878 // There's a bug with CTAI.CanonicalConverted.
4879 // If the template argument contains a DependentDecltypeType that includes a
4880 // TypeAliasType, and the same written type had occurred previously in the
4881 // source, then the DependentDecltypeType would be canonicalized to that
4882 // previous type which would mess up the substitution.
4883 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4884 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4885 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4886 ConvertedArgs: CTAI.SugaredConverted);
4887 ConstraintSatisfaction Satisfaction;
4888 bool AreArgsDependent =
4889 TemplateSpecializationType::anyDependentTemplateArguments(
4890 *TemplateArgs, Converted: CTAI.SugaredConverted);
4891 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4892 /*Final=*/false);
4893 auto *CL = ConceptReference::Create(
4894 C: Context,
4895 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4896 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4897 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4898
4899 bool Error = false;
4900 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4901 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4902 DoCheckConstraintSatisfaction) {
4903
4904 LocalInstantiationScope Scope(*this);
4905
4906 EnterExpressionEvaluationContext EECtx{
4907 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4908
4909 Error = CheckConstraintSatisfaction(
4910 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4911 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4912 TemplateArgs->getRAngleLoc()),
4913 Satisfaction, TopLevelConceptId: CL);
4914 Satisfaction.ContainsErrors = Error;
4915 }
4916
4917 if (Error)
4918 return ExprError();
4919
4920 return ConceptSpecializationExpr::Create(
4921 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4922}
4923
4924ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4925 SourceLocation TemplateKWLoc,
4926 LookupResult &R,
4927 bool RequiresADL,
4928 const TemplateArgumentListInfo *TemplateArgs) {
4929 // FIXME: Can we do any checking at this point? I guess we could check the
4930 // template arguments that we have against the template name, if the template
4931 // name refers to a single template. That's not a terribly common case,
4932 // though.
4933 // foo<int> could identify a single function unambiguously
4934 // This approach does NOT work, since f<int>(1);
4935 // gets resolved prior to resorting to overload resolution
4936 // i.e., template<class T> void f(double);
4937 // vs template<class T, class U> void f(U);
4938
4939 // These should be filtered out by our callers.
4940 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4941
4942 // Non-function templates require a template argument list.
4943 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4944 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4945 diagnoseMissingTemplateArguments(
4946 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4947 return ExprError();
4948 }
4949 }
4950 bool KnownDependent = false;
4951 // In C++1y, check variable template ids.
4952 if (R.getAsSingle<VarTemplateDecl>()) {
4953 ExprResult Res = CheckVarTemplateId(
4954 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4955 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4956 if (Res.isInvalid() || Res.isUsable())
4957 return Res;
4958 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4959 KnownDependent = true;
4960 }
4961
4962 // We don't want lookup warnings at this point.
4963 R.suppressDiagnostics();
4964
4965 if (R.getAsSingle<ConceptDecl>()) {
4966 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4967 FoundDecl: R.getRepresentativeDecl(),
4968 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4969 }
4970
4971 // Check variable template ids (C++17) and concept template parameters
4972 // (C++26).
4973 UnresolvedLookupExpr *ULE;
4974 if (R.getAsSingle<TemplateTemplateParmDecl>())
4975 return CheckVarOrConceptTemplateTemplateId(
4976 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<TemplateTemplateParmDecl>(),
4977 TemplateLoc: TemplateKWLoc, TemplateArgs);
4978
4979 // Function templates
4980 ULE = UnresolvedLookupExpr::Create(
4981 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
4982 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
4983 Begin: R.begin(), End: R.end(), KnownDependent,
4984 /*KnownInstantiationDependent=*/false);
4985 // Model the templates with UnresolvedTemplateTy. The expression should then
4986 // either be transformed in an instantiation or be diagnosed in
4987 // CheckPlaceholderExpr.
4988 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4989 !R.getFoundDecl()->getAsFunction())
4990 ULE->setType(Context.UnresolvedTemplateTy);
4991
4992 return ULE;
4993}
4994
4995ExprResult Sema::BuildQualifiedTemplateIdExpr(
4996 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4997 const DeclarationNameInfo &NameInfo,
4998 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4999 assert(TemplateArgs || TemplateKWLoc.isValid());
5000
5001 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5002 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5003 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5004 return ExprError();
5005
5006 if (R.isAmbiguous())
5007 return ExprError();
5008
5009 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5010 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5011
5012 if (R.empty()) {
5013 DeclContext *DC = computeDeclContext(SS);
5014 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5015 << NameInfo.getName() << DC << SS.getRange();
5016 return ExprError();
5017 }
5018
5019 // If necessary, build an implicit class member access.
5020 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5021 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5022 /*S=*/nullptr);
5023
5024 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5025}
5026
5027TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5028 CXXScopeSpec &SS,
5029 SourceLocation TemplateKWLoc,
5030 const UnqualifiedId &Name,
5031 ParsedType ObjectType,
5032 bool EnteringContext,
5033 TemplateTy &Result,
5034 bool AllowInjectedClassName) {
5035 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5036 Diag(Loc: TemplateKWLoc,
5037 DiagID: getLangOpts().CPlusPlus11 ?
5038 diag::warn_cxx98_compat_template_outside_of_template :
5039 diag::ext_template_outside_of_template)
5040 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5041
5042 if (SS.isInvalid())
5043 return TNK_Non_template;
5044
5045 // Figure out where isTemplateName is going to look.
5046 DeclContext *LookupCtx = nullptr;
5047 if (SS.isNotEmpty())
5048 LookupCtx = computeDeclContext(SS, EnteringContext);
5049 else if (ObjectType)
5050 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5051
5052 // C++0x [temp.names]p5:
5053 // If a name prefixed by the keyword template is not the name of
5054 // a template, the program is ill-formed. [Note: the keyword
5055 // template may not be applied to non-template members of class
5056 // templates. -end note ] [ Note: as is the case with the
5057 // typename prefix, the template prefix is allowed in cases
5058 // where it is not strictly necessary; i.e., when the
5059 // nested-name-specifier or the expression on the left of the ->
5060 // or . is not dependent on a template-parameter, or the use
5061 // does not appear in the scope of a template. -end note]
5062 //
5063 // Note: C++03 was more strict here, because it banned the use of
5064 // the "template" keyword prior to a template-name that was not a
5065 // dependent name. C++ DR468 relaxed this requirement (the
5066 // "template" keyword is now permitted). We follow the C++0x
5067 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5068 bool MemberOfUnknownSpecialization;
5069 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5070 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5071 MemberOfUnknownSpecialization);
5072 if (TNK != TNK_Non_template) {
5073 // We resolved this to a (non-dependent) template name. Return it.
5074 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5075 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5076 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5077 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5078 // C++14 [class.qual]p2:
5079 // In a lookup in which function names are not ignored and the
5080 // nested-name-specifier nominates a class C, if the name specified
5081 // [...] is the injected-class-name of C, [...] the name is instead
5082 // considered to name the constructor
5083 //
5084 // We don't get here if naming the constructor would be valid, so we
5085 // just reject immediately and recover by treating the
5086 // injected-class-name as naming the template.
5087 Diag(Loc: Name.getBeginLoc(),
5088 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5089 << Name.Identifier
5090 << 0 /*injected-class-name used as template name*/
5091 << TemplateKWLoc.isValid();
5092 }
5093 return TNK;
5094 }
5095
5096 if (!MemberOfUnknownSpecialization) {
5097 // Didn't find a template name, and the lookup wasn't dependent.
5098 // Do the lookup again to determine if this is a "nothing found" case or
5099 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5100 // need to do this.
5101 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5102 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5103 LookupOrdinaryName);
5104 // Tell LookupTemplateName that we require a template so that it diagnoses
5105 // cases where it finds a non-template.
5106 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5107 ? RequiredTemplateKind(TemplateKWLoc)
5108 : TemplateNameIsRequired;
5109 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5110 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5111 !R.isAmbiguous()) {
5112 if (LookupCtx)
5113 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5114 << DNI.getName() << LookupCtx << SS.getRange();
5115 else
5116 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5117 << DNI.getName() << SS.getRange();
5118 }
5119 return TNK_Non_template;
5120 }
5121
5122 NestedNameSpecifier Qualifier = SS.getScopeRep();
5123
5124 switch (Name.getKind()) {
5125 case UnqualifiedIdKind::IK_Identifier:
5126 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5127 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5128 return TNK_Dependent_template_name;
5129
5130 case UnqualifiedIdKind::IK_OperatorFunctionId:
5131 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5132 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5133 TemplateKWLoc.isValid()}));
5134 return TNK_Function_template;
5135
5136 case UnqualifiedIdKind::IK_LiteralOperatorId:
5137 // This is a kind of template name, but can never occur in a dependent
5138 // scope (literal operators can only be declared at namespace scope).
5139 break;
5140
5141 default:
5142 break;
5143 }
5144
5145 // This name cannot possibly name a dependent template. Diagnose this now
5146 // rather than building a dependent template name that can never be valid.
5147 Diag(Loc: Name.getBeginLoc(),
5148 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5149 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5150 << TemplateKWLoc.isValid() << TemplateKWLoc;
5151 return TNK_Non_template;
5152}
5153
5154bool Sema::CheckTemplateTypeArgument(
5155 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5156 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5157 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5158 const TemplateArgument &Arg = AL.getArgument();
5159 QualType ArgType;
5160 TypeSourceInfo *TSI = nullptr;
5161
5162 // Check template type parameter.
5163 switch(Arg.getKind()) {
5164 case TemplateArgument::Type:
5165 // C++ [temp.arg.type]p1:
5166 // A template-argument for a template-parameter which is a
5167 // type shall be a type-id.
5168 ArgType = Arg.getAsType();
5169 TSI = AL.getTypeSourceInfo();
5170 break;
5171 case TemplateArgument::Template:
5172 case TemplateArgument::TemplateExpansion: {
5173 // We have a template type parameter but the template argument
5174 // is a template without any arguments.
5175 SourceRange SR = AL.getSourceRange();
5176 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5177 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5178 return true;
5179 }
5180 case TemplateArgument::Expression: {
5181 // We have a template type parameter but the template argument is an
5182 // expression; see if maybe it is missing the "typename" keyword.
5183 CXXScopeSpec SS;
5184 DeclarationNameInfo NameInfo;
5185
5186 if (DependentScopeDeclRefExpr *ArgExpr =
5187 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5188 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5189 NameInfo = ArgExpr->getNameInfo();
5190 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5191 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5192 if (ArgExpr->isImplicitAccess()) {
5193 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5194 NameInfo = ArgExpr->getMemberNameInfo();
5195 }
5196 }
5197
5198 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5199 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5200 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5201
5202 if (Result.getAsSingle<TypeDecl>() ||
5203 Result.wasNotFoundInCurrentInstantiation()) {
5204 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5205 // Suggest that the user add 'typename' before the NNS.
5206 SourceLocation Loc = AL.getSourceRange().getBegin();
5207 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5208 ? diag::ext_ms_template_type_arg_missing_typename
5209 : diag::err_template_arg_must_be_type_suggest)
5210 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5211 NoteTemplateParameterLocation(Decl: *Param);
5212
5213 // Recover by synthesizing a type using the location information that we
5214 // already have.
5215 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5216 NNS: SS.getScopeRep(), Name: II);
5217 TypeLocBuilder TLB;
5218 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5219 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5220 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5221 TL.setNameLoc(NameInfo.getLoc());
5222 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5223
5224 // Overwrite our input TemplateArgumentLoc so that we can recover
5225 // properly.
5226 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5227 TemplateArgumentLocInfo(TSI));
5228
5229 break;
5230 }
5231 }
5232 // fallthrough
5233 [[fallthrough]];
5234 }
5235 default: {
5236 // We allow instantiating a template with template argument packs when
5237 // building deduction guides or mapping constraint template parameters.
5238 if (Arg.getKind() == TemplateArgument::Pack &&
5239 (CodeSynthesisContexts.back().Kind ==
5240 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5241 inParameterMappingSubstitution())) {
5242 SugaredConverted.push_back(Elt: Arg);
5243 CanonicalConverted.push_back(Elt: Arg);
5244 return false;
5245 }
5246 // We have a template type parameter but the template argument
5247 // is not a type.
5248 SourceRange SR = AL.getSourceRange();
5249 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5250 NoteTemplateParameterLocation(Decl: *Param);
5251
5252 return true;
5253 }
5254 }
5255
5256 if (CheckTemplateArgument(Arg: TSI))
5257 return true;
5258
5259 // Objective-C ARC:
5260 // If an explicitly-specified template argument type is a lifetime type
5261 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5262 if (getLangOpts().ObjCAutoRefCount &&
5263 ArgType->isObjCLifetimeType() &&
5264 !ArgType.getObjCLifetime()) {
5265 Qualifiers Qs;
5266 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5267 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5268 }
5269
5270 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5271 CanonicalConverted.push_back(
5272 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5273 return false;
5274}
5275
5276/// Substitute template arguments into the default template argument for
5277/// the given template type parameter.
5278///
5279/// \param SemaRef the semantic analysis object for which we are performing
5280/// the substitution.
5281///
5282/// \param Template the template that we are synthesizing template arguments
5283/// for.
5284///
5285/// \param TemplateLoc the location of the template name that started the
5286/// template-id we are checking.
5287///
5288/// \param RAngleLoc the location of the right angle bracket ('>') that
5289/// terminates the template-id.
5290///
5291/// \param Param the template template parameter whose default we are
5292/// substituting into.
5293///
5294/// \param Converted the list of template arguments provided for template
5295/// parameters that precede \p Param in the template parameter list.
5296///
5297/// \param Output the resulting substituted template argument.
5298///
5299/// \returns true if an error occurred.
5300static bool SubstDefaultTemplateArgument(
5301 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5302 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5303 ArrayRef<TemplateArgument> SugaredConverted,
5304 ArrayRef<TemplateArgument> CanonicalConverted,
5305 TemplateArgumentLoc &Output) {
5306 Output = Param->getDefaultArgument();
5307
5308 // If the argument type is dependent, instantiate it now based
5309 // on the previously-computed template arguments.
5310 if (Output.getArgument().isInstantiationDependent()) {
5311 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5312 SugaredConverted,
5313 SourceRange(TemplateLoc, RAngleLoc));
5314 if (Inst.isInvalid())
5315 return true;
5316
5317 // Only substitute for the innermost template argument list.
5318 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5319 /*Final=*/true);
5320 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5321 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5322
5323 bool ForLambdaCallOperator = false;
5324 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5325 ForLambdaCallOperator = Rec->isLambda();
5326 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5327 !ForLambdaCallOperator);
5328
5329 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5330 Loc: Param->getDefaultArgumentLoc(),
5331 Entity: Param->getDeclName()))
5332 return true;
5333 }
5334
5335 return false;
5336}
5337
5338/// Substitute template arguments into the default template argument for
5339/// the given non-type template parameter.
5340///
5341/// \param SemaRef the semantic analysis object for which we are performing
5342/// the substitution.
5343///
5344/// \param Template the template that we are synthesizing template arguments
5345/// for.
5346///
5347/// \param TemplateLoc the location of the template name that started the
5348/// template-id we are checking.
5349///
5350/// \param RAngleLoc the location of the right angle bracket ('>') that
5351/// terminates the template-id.
5352///
5353/// \param Param the non-type template parameter whose default we are
5354/// substituting into.
5355///
5356/// \param Converted the list of template arguments provided for template
5357/// parameters that precede \p Param in the template parameter list.
5358///
5359/// \returns the substituted template argument, or NULL if an error occurred.
5360static bool SubstDefaultTemplateArgument(
5361 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5362 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5363 ArrayRef<TemplateArgument> SugaredConverted,
5364 ArrayRef<TemplateArgument> CanonicalConverted,
5365 TemplateArgumentLoc &Output) {
5366 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5367 SugaredConverted,
5368 SourceRange(TemplateLoc, RAngleLoc));
5369 if (Inst.isInvalid())
5370 return true;
5371
5372 // Only substitute for the innermost template argument list.
5373 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5374 /*Final=*/true);
5375 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5376 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5377
5378 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5379 EnterExpressionEvaluationContext ConstantEvaluated(
5380 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5381 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5382 TemplateArgs: TemplateArgLists, Output);
5383}
5384
5385/// Substitute template arguments into the default template argument for
5386/// the given template template parameter.
5387///
5388/// \param SemaRef the semantic analysis object for which we are performing
5389/// the substitution.
5390///
5391/// \param Template the template that we are synthesizing template arguments
5392/// for.
5393///
5394/// \param TemplateLoc the location of the template name that started the
5395/// template-id we are checking.
5396///
5397/// \param RAngleLoc the location of the right angle bracket ('>') that
5398/// terminates the template-id.
5399///
5400/// \param Param the template template parameter whose default we are
5401/// substituting into.
5402///
5403/// \param Converted the list of template arguments provided for template
5404/// parameters that precede \p Param in the template parameter list.
5405///
5406/// \param QualifierLoc Will be set to the nested-name-specifier (with
5407/// source-location information) that precedes the template name.
5408///
5409/// \returns the substituted template argument, or NULL if an error occurred.
5410static TemplateName SubstDefaultTemplateArgument(
5411 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5412 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5413 TemplateTemplateParmDecl *Param,
5414 ArrayRef<TemplateArgument> SugaredConverted,
5415 ArrayRef<TemplateArgument> CanonicalConverted,
5416 NestedNameSpecifierLoc &QualifierLoc) {
5417 Sema::InstantiatingTemplate Inst(
5418 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5419 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5420 if (Inst.isInvalid())
5421 return TemplateName();
5422
5423 // Only substitute for the innermost template argument list.
5424 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5425 /*Final=*/true);
5426 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5427 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5428
5429 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5430
5431 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5432 QualifierLoc = A.getTemplateQualifierLoc();
5433 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5434 Name: A.getArgument().getAsTemplate(),
5435 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5436}
5437
5438TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5439 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5440 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5441 ArrayRef<TemplateArgument> SugaredConverted,
5442 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5443 HasDefaultArg = false;
5444
5445 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5446 if (!hasReachableDefaultArgument(D: TypeParm))
5447 return TemplateArgumentLoc();
5448
5449 HasDefaultArg = true;
5450 TemplateArgumentLoc Output;
5451 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5452 RAngleLoc, Param: TypeParm, SugaredConverted,
5453 CanonicalConverted, Output))
5454 return TemplateArgumentLoc();
5455 return Output;
5456 }
5457
5458 if (NonTypeTemplateParmDecl *NonTypeParm
5459 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5460 if (!hasReachableDefaultArgument(D: NonTypeParm))
5461 return TemplateArgumentLoc();
5462
5463 HasDefaultArg = true;
5464 TemplateArgumentLoc Output;
5465 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5466 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5467 CanonicalConverted, Output))
5468 return TemplateArgumentLoc();
5469 return Output;
5470 }
5471
5472 TemplateTemplateParmDecl *TempTempParm
5473 = cast<TemplateTemplateParmDecl>(Val: Param);
5474 if (!hasReachableDefaultArgument(D: TempTempParm))
5475 return TemplateArgumentLoc();
5476
5477 HasDefaultArg = true;
5478 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5479 NestedNameSpecifierLoc QualifierLoc;
5480 TemplateName TName = SubstDefaultTemplateArgument(
5481 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5482 SugaredConverted, CanonicalConverted, QualifierLoc);
5483 if (TName.isNull())
5484 return TemplateArgumentLoc();
5485
5486 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5487 QualifierLoc, A.getTemplateNameLoc());
5488}
5489
5490/// Convert a template-argument that we parsed as a type into a template, if
5491/// possible. C++ permits injected-class-names to perform dual service as
5492/// template template arguments and as template type arguments.
5493static TemplateArgumentLoc
5494convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5495 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5496 if (!TagLoc)
5497 return TemplateArgumentLoc();
5498
5499 // If this type was written as an injected-class-name, it can be used as a
5500 // template template argument.
5501 // If this type was written as an injected-class-name, it may have been
5502 // converted to a RecordType during instantiation. If the RecordType is
5503 // *not* wrapped in a TemplateSpecializationType and denotes a class
5504 // template specialization, it must have come from an injected-class-name.
5505
5506 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5507 if (Name.isNull())
5508 return TemplateArgumentLoc();
5509
5510 return TemplateArgumentLoc(Context, Name,
5511 /*TemplateKWLoc=*/SourceLocation(),
5512 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5513}
5514
5515bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5516 NamedDecl *Template,
5517 SourceLocation TemplateLoc,
5518 SourceLocation RAngleLoc,
5519 unsigned ArgumentPackIndex,
5520 CheckTemplateArgumentInfo &CTAI,
5521 CheckTemplateArgumentKind CTAK) {
5522 // Check template type parameters.
5523 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5524 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5525 CanonicalConverted&: CTAI.CanonicalConverted);
5526
5527 const TemplateArgument &Arg = ArgLoc.getArgument();
5528 // Check non-type template parameters.
5529 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5530 // Do substitution on the type of the non-type template parameter
5531 // with the template arguments we've seen thus far. But if the
5532 // template has a dependent context then we cannot substitute yet.
5533 QualType NTTPType = NTTP->getType();
5534 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5535 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5536
5537 if (NTTPType->isInstantiationDependentType()) {
5538 // Do substitution on the type of the non-type template parameter.
5539 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5540 CTAI.SugaredConverted,
5541 SourceRange(TemplateLoc, RAngleLoc));
5542 if (Inst.isInvalid())
5543 return true;
5544
5545 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5546 /*Final=*/true);
5547 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5548 // If the parameter is a pack expansion, expand this slice of the pack.
5549 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5550 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5551 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5552 Entity: NTTP->getDeclName());
5553 } else {
5554 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5555 Entity: NTTP->getDeclName());
5556 }
5557
5558 // If that worked, check the non-type template parameter type
5559 // for validity.
5560 if (!NTTPType.isNull())
5561 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5562 Loc: NTTP->getLocation());
5563 if (NTTPType.isNull())
5564 return true;
5565 }
5566
5567 auto checkExpr = [&](Expr *E) -> Expr * {
5568 TemplateArgument SugaredResult, CanonicalResult;
5569 ExprResult Res = CheckTemplateArgument(
5570 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5571 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5572 // If the current template argument causes an error, give up now.
5573 if (Res.isInvalid())
5574 return nullptr;
5575 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5576 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5577 return Res.get();
5578 };
5579
5580 switch (Arg.getKind()) {
5581 case TemplateArgument::Null:
5582 llvm_unreachable("Should never see a NULL template argument here");
5583
5584 case TemplateArgument::Expression: {
5585 Expr *E = Arg.getAsExpr();
5586 Expr *R = checkExpr(E);
5587 if (!R)
5588 return true;
5589 // If the resulting expression is new, then use it in place of the
5590 // old expression in the template argument.
5591 if (R != E) {
5592 TemplateArgument TA(R, /*IsCanonical=*/false);
5593 ArgLoc = TemplateArgumentLoc(TA, R);
5594 }
5595 break;
5596 }
5597
5598 // As for the converted NTTP kinds, they still might need another
5599 // conversion, as the new corresponding parameter might be different.
5600 // Ideally, we would always perform substitution starting with sugared types
5601 // and never need these, as we would still have expressions. Since these are
5602 // needed so rarely, it's probably a better tradeoff to just convert them
5603 // back to expressions.
5604 case TemplateArgument::Integral:
5605 case TemplateArgument::Declaration:
5606 case TemplateArgument::NullPtr:
5607 case TemplateArgument::StructuralValue: {
5608 // FIXME: StructuralValue is untested here.
5609 ExprResult R =
5610 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5611 assert(R.isUsable());
5612 if (!checkExpr(R.get()))
5613 return true;
5614 break;
5615 }
5616
5617 case TemplateArgument::Template:
5618 case TemplateArgument::TemplateExpansion:
5619 // We were given a template template argument. It may not be ill-formed;
5620 // see below.
5621 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5622 .getAsDependentTemplateName()) {
5623 // We have a template argument such as \c T::template X, which we
5624 // parsed as a template template argument. However, since we now
5625 // know that we need a non-type template argument, convert this
5626 // template name into an expression.
5627
5628 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5629 ArgLoc.getTemplateNameLoc());
5630
5631 CXXScopeSpec SS;
5632 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5633 // FIXME: the template-template arg was a DependentTemplateName,
5634 // so it was provided with a template keyword. However, its source
5635 // location is not stored in the template argument structure.
5636 SourceLocation TemplateKWLoc;
5637 ExprResult E = DependentScopeDeclRefExpr::Create(
5638 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5639 TemplateArgs: nullptr);
5640
5641 // If we parsed the template argument as a pack expansion, create a
5642 // pack expansion expression.
5643 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5644 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5645 if (E.isInvalid())
5646 return true;
5647 }
5648
5649 TemplateArgument SugaredResult, CanonicalResult;
5650 E = CheckTemplateArgument(
5651 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5652 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5653 if (E.isInvalid())
5654 return true;
5655
5656 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5657 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5658 break;
5659 }
5660
5661 // We have a template argument that actually does refer to a class
5662 // template, alias template, or template template parameter, and
5663 // therefore cannot be a non-type template argument.
5664 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5665 << ArgLoc.getSourceRange();
5666 NoteTemplateParameterLocation(Decl: *Param);
5667
5668 return true;
5669
5670 case TemplateArgument::Type: {
5671 // We have a non-type template parameter but the template
5672 // argument is a type.
5673
5674 // C++ [temp.arg]p2:
5675 // In a template-argument, an ambiguity between a type-id and
5676 // an expression is resolved to a type-id, regardless of the
5677 // form of the corresponding template-parameter.
5678 //
5679 // We warn specifically about this case, since it can be rather
5680 // confusing for users.
5681 QualType T = Arg.getAsType();
5682 SourceRange SR = ArgLoc.getSourceRange();
5683 if (T->isFunctionType())
5684 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5685 else
5686 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5687 NoteTemplateParameterLocation(Decl: *Param);
5688 return true;
5689 }
5690
5691 case TemplateArgument::Pack:
5692 llvm_unreachable("Caller must expand template argument packs");
5693 }
5694
5695 return false;
5696 }
5697
5698
5699 // Check template template parameters.
5700 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5701
5702 TemplateParameterList *Params = TempParm->getTemplateParameters();
5703 if (TempParm->isExpandedParameterPack())
5704 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5705
5706 // Substitute into the template parameter list of the template
5707 // template parameter, since previously-supplied template arguments
5708 // may appear within the template template parameter.
5709 //
5710 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5711 {
5712 // Set up a template instantiation context.
5713 LocalInstantiationScope Scope(*this);
5714 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5715 CTAI.SugaredConverted,
5716 SourceRange(TemplateLoc, RAngleLoc));
5717 if (Inst.isInvalid())
5718 return true;
5719
5720 Params = SubstTemplateParams(
5721 Params, Owner: CurContext,
5722 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5723 /*Final=*/true),
5724 /*EvaluateConstraints=*/false);
5725 if (!Params)
5726 return true;
5727 }
5728
5729 // C++1z [temp.local]p1: (DR1004)
5730 // When [the injected-class-name] is used [...] as a template-argument for
5731 // a template template-parameter [...] it refers to the class template
5732 // itself.
5733 if (Arg.getKind() == TemplateArgument::Type) {
5734 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5735 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5736 if (!ConvertedArg.getArgument().isNull())
5737 ArgLoc = ConvertedArg;
5738 }
5739
5740 switch (Arg.getKind()) {
5741 case TemplateArgument::Null:
5742 llvm_unreachable("Should never see a NULL template argument here");
5743
5744 case TemplateArgument::Template:
5745 case TemplateArgument::TemplateExpansion:
5746 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5747 PartialOrdering: CTAI.PartialOrdering,
5748 StrictPackMatch: &CTAI.StrictPackMatch))
5749 return true;
5750
5751 CTAI.SugaredConverted.push_back(Elt: Arg);
5752 CTAI.CanonicalConverted.push_back(
5753 Elt: Context.getCanonicalTemplateArgument(Arg));
5754 break;
5755
5756 case TemplateArgument::Expression:
5757 case TemplateArgument::Type: {
5758 auto Kind = 0;
5759 switch (TempParm->templateParameterKind()) {
5760 case TemplateNameKind::TNK_Var_template:
5761 Kind = 1;
5762 break;
5763 case TemplateNameKind::TNK_Concept_template:
5764 Kind = 2;
5765 break;
5766 default:
5767 break;
5768 }
5769
5770 // We have a template template parameter but the template
5771 // argument does not refer to a template.
5772 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5773 << Kind << getLangOpts().CPlusPlus11;
5774 return true;
5775 }
5776
5777 case TemplateArgument::Declaration:
5778 case TemplateArgument::Integral:
5779 case TemplateArgument::StructuralValue:
5780 case TemplateArgument::NullPtr:
5781 llvm_unreachable("non-type argument with template template parameter");
5782
5783 case TemplateArgument::Pack:
5784 llvm_unreachable("Caller must expand template argument packs");
5785 }
5786
5787 return false;
5788}
5789
5790/// Diagnose a missing template argument.
5791template<typename TemplateParmDecl>
5792static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5793 TemplateDecl *TD,
5794 const TemplateParmDecl *D,
5795 TemplateArgumentListInfo &Args) {
5796 // Dig out the most recent declaration of the template parameter; there may be
5797 // declarations of the template that are more recent than TD.
5798 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5799 ->getTemplateParameters()
5800 ->getParam(D->getIndex()));
5801
5802 // If there's a default argument that's not reachable, diagnose that we're
5803 // missing a module import.
5804 llvm::SmallVector<Module*, 8> Modules;
5805 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5806 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5807 D->getDefaultArgumentLoc(), Modules,
5808 Sema::MissingImportKind::DefaultArgument,
5809 /*Recover*/true);
5810 return true;
5811 }
5812
5813 // FIXME: If there's a more recent default argument that *is* visible,
5814 // diagnose that it was declared too late.
5815
5816 TemplateParameterList *Params = TD->getTemplateParameters();
5817
5818 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5819 << /*not enough args*/0
5820 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5821 << TD;
5822 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5823 return true;
5824}
5825
5826/// Check that the given template argument list is well-formed
5827/// for specializing the given template.
5828bool Sema::CheckTemplateArgumentList(
5829 TemplateDecl *Template, SourceLocation TemplateLoc,
5830 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5831 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5832 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5833 return CheckTemplateArgumentList(
5834 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5835 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5836 ConstraintsNotSatisfied);
5837}
5838
5839/// Check that the given template argument list is well-formed
5840/// for specializing the given template.
5841bool Sema::CheckTemplateArgumentList(
5842 TemplateDecl *Template, TemplateParameterList *Params,
5843 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5844 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5845 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5846 bool *ConstraintsNotSatisfied) {
5847
5848 if (ConstraintsNotSatisfied)
5849 *ConstraintsNotSatisfied = false;
5850
5851 // Make a copy of the template arguments for processing. Only make the
5852 // changes at the end when successful in matching the arguments to the
5853 // template.
5854 TemplateArgumentListInfo NewArgs = TemplateArgs;
5855
5856 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5857
5858 // C++23 [temp.arg.general]p1:
5859 // [...] The type and form of each template-argument specified in
5860 // a template-id shall match the type and form specified for the
5861 // corresponding parameter declared by the template in its
5862 // template-parameter-list.
5863 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5864 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5865 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5866 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5867 LocalInstantiationScope InstScope(*this, true);
5868 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5869 ParamEnd = Params->end(),
5870 Param = ParamBegin;
5871 Param != ParamEnd;
5872 /* increment in loop */) {
5873 if (size_t ParamIdx = Param - ParamBegin;
5874 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5875 // All written arguments should have been consumed by this point.
5876 assert(ArgIdx == NumArgs && "bad default argument deduction");
5877 if (ParamIdx == DefaultArgs.StartPos) {
5878 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5879 // Default arguments from a DeducedTemplateName are already converted.
5880 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5881 CTAI.SugaredConverted.push_back(Elt: DefArg);
5882 CTAI.CanonicalConverted.push_back(
5883 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5884 ++Param;
5885 }
5886 continue;
5887 }
5888 }
5889
5890 // If we have an expanded parameter pack, make sure we don't have too
5891 // many arguments.
5892 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5893 if (*Expansions == SugaredArgumentPack.size()) {
5894 // We're done with this parameter pack. Pack up its arguments and add
5895 // them to the list.
5896 CTAI.SugaredConverted.push_back(
5897 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5898 SugaredArgumentPack.clear();
5899
5900 CTAI.CanonicalConverted.push_back(
5901 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5902 CanonicalArgumentPack.clear();
5903
5904 // This argument is assigned to the next parameter.
5905 ++Param;
5906 continue;
5907 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5908 // Not enough arguments for this parameter pack.
5909 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5910 << /*not enough args*/0
5911 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5912 << Template;
5913 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5914 return true;
5915 }
5916 }
5917
5918 // Check for builtins producing template packs in this context, we do not
5919 // support them yet.
5920 if (const NonTypeTemplateParmDecl *NTTP =
5921 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5922 NTTP && NTTP->isPackExpansion()) {
5923 auto TL = NTTP->getTypeSourceInfo()
5924 ->getTypeLoc()
5925 .castAs<PackExpansionTypeLoc>();
5926 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5927 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5928 for (const auto &UPP : Unexpanded) {
5929 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5930 if (!TST)
5931 continue;
5932 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5933 // Expanding a built-in pack in this context is not yet supported.
5934 Diag(Loc: TL.getEllipsisLoc(),
5935 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5936 << TST->getTemplateName();
5937 return true;
5938 }
5939 }
5940
5941 if (ArgIdx < NumArgs) {
5942 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5943 bool NonPackParameter =
5944 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5945 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5946
5947 if (ArgIsExpansion && CTAI.MatchingTTP) {
5948 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5949 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5950 ++Param) {
5951 TemplateArgument &Arg = Args[Param - First];
5952 Arg = ArgLoc.getArgument();
5953 if (!(*Param)->isTemplateParameterPack() ||
5954 getExpandedPackSize(Param: *Param))
5955 Arg = Arg.getPackExpansionPattern();
5956 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5957 SaveAndRestore _1(CTAI.PartialOrdering, false);
5958 SaveAndRestore _2(CTAI.MatchingTTP, true);
5959 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5960 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5961 CTAK: CTAK_Specified))
5962 return true;
5963 Arg = NewArgLoc.getArgument();
5964 CTAI.CanonicalConverted.back().setIsDefaulted(
5965 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5966 Args: CTAI.CanonicalConverted,
5967 Depth: Params->getDepth()));
5968 }
5969 ArgLoc =
5970 TemplateArgumentLoc(TemplateArgument::CreatePackCopy(Context, Args),
5971 ArgLoc.getLocInfo());
5972 } else {
5973 SaveAndRestore _1(CTAI.PartialOrdering, false);
5974 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
5975 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5976 CTAK: CTAK_Specified))
5977 return true;
5978 CTAI.CanonicalConverted.back().setIsDefaulted(
5979 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
5980 Param: *Param, Args: CTAI.CanonicalConverted,
5981 Depth: Params->getDepth()));
5982 if (ArgIsExpansion && NonPackParameter) {
5983 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5984 // alias template or concept, and it's not part of a parameter pack.
5985 // This can't be canonicalized, so reject it now.
5986 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Val: Template)) {
5987 Diag(Loc: ArgLoc.getLocation(),
5988 DiagID: diag::err_template_expansion_into_fixed_list)
5989 << (isa<ConceptDecl>(Val: Template) ? 1 : 0)
5990 << ArgLoc.getSourceRange();
5991 NoteTemplateParameterLocation(Decl: **Param);
5992 return true;
5993 }
5994 }
5995 }
5996
5997 // We're now done with this argument.
5998 ++ArgIdx;
5999
6000 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6001 // Directly convert the remaining arguments, because we don't know what
6002 // parameters they'll match up with.
6003
6004 if (!SugaredArgumentPack.empty()) {
6005 // If we were part way through filling in an expanded parameter pack,
6006 // fall back to just producing individual arguments.
6007 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6008 From: SugaredArgumentPack.begin(),
6009 To: SugaredArgumentPack.end());
6010 SugaredArgumentPack.clear();
6011
6012 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6013 From: CanonicalArgumentPack.begin(),
6014 To: CanonicalArgumentPack.end());
6015 CanonicalArgumentPack.clear();
6016 }
6017
6018 while (ArgIdx < NumArgs) {
6019 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6020 CTAI.SugaredConverted.push_back(Elt: Arg);
6021 CTAI.CanonicalConverted.push_back(
6022 Elt: Context.getCanonicalTemplateArgument(Arg));
6023 ++ArgIdx;
6024 }
6025
6026 return false;
6027 }
6028
6029 if ((*Param)->isTemplateParameterPack()) {
6030 // The template parameter was a template parameter pack, so take the
6031 // deduced argument and place it on the argument pack. Note that we
6032 // stay on the same template parameter so that we can deduce more
6033 // arguments.
6034 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6035 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6036 } else {
6037 // Move to the next template parameter.
6038 ++Param;
6039 }
6040 continue;
6041 }
6042
6043 // If we're checking a partial template argument list, we're done.
6044 if (PartialTemplateArgs) {
6045 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6046 CTAI.SugaredConverted.push_back(
6047 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6048 CTAI.CanonicalConverted.push_back(
6049 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6050 }
6051 return false;
6052 }
6053
6054 // If we have a template parameter pack with no more corresponding
6055 // arguments, just break out now and we'll fill in the argument pack below.
6056 if ((*Param)->isTemplateParameterPack()) {
6057 assert(!getExpandedPackSize(*Param) &&
6058 "Should have dealt with this already");
6059
6060 // A non-expanded parameter pack before the end of the parameter list
6061 // only occurs for an ill-formed template parameter list, unless we've
6062 // got a partial argument list for a function template, so just bail out.
6063 if (Param + 1 != ParamEnd) {
6064 assert(
6065 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6066 "Concept templates must have parameter packs at the end.");
6067 return true;
6068 }
6069
6070 CTAI.SugaredConverted.push_back(
6071 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6072 SugaredArgumentPack.clear();
6073
6074 CTAI.CanonicalConverted.push_back(
6075 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6076 CanonicalArgumentPack.clear();
6077
6078 ++Param;
6079 continue;
6080 }
6081
6082 // Check whether we have a default argument.
6083 bool HasDefaultArg;
6084
6085 // Retrieve the default template argument from the template
6086 // parameter. For each kind of template parameter, we substitute the
6087 // template arguments provided thus far and any "outer" template arguments
6088 // (when the template parameter was part of a nested template) into
6089 // the default argument.
6090 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6091 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6092 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6093
6094 if (Arg.getArgument().isNull()) {
6095 if (!HasDefaultArg) {
6096 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6097 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6098 Args&: NewArgs);
6099 if (NonTypeTemplateParmDecl *NTTP =
6100 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6101 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6102 Args&: NewArgs);
6103 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6104 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6105 Args&: NewArgs);
6106 }
6107 return true;
6108 }
6109
6110 // Introduce an instantiation record that describes where we are using
6111 // the default template argument. We're not actually instantiating a
6112 // template here, we just create this object to put a note into the
6113 // context stack.
6114 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6115 CTAI.SugaredConverted,
6116 SourceRange(TemplateLoc, RAngleLoc));
6117 if (Inst.isInvalid())
6118 return true;
6119
6120 SaveAndRestore _1(CTAI.PartialOrdering, false);
6121 SaveAndRestore _2(CTAI.MatchingTTP, false);
6122 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6123 // Check the default template argument.
6124 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6125 CTAI, CTAK: CTAK_Specified))
6126 return true;
6127
6128 CTAI.SugaredConverted.back().setIsDefaulted(true);
6129 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6130
6131 // Core issue 150 (assumed resolution): if this is a template template
6132 // parameter, keep track of the default template arguments from the
6133 // template definition.
6134 if (isTemplateTemplateParameter)
6135 NewArgs.addArgument(Loc: Arg);
6136
6137 // Move to the next template parameter and argument.
6138 ++Param;
6139 ++ArgIdx;
6140 }
6141
6142 // If we're performing a partial argument substitution, allow any trailing
6143 // pack expansions; they might be empty. This can happen even if
6144 // PartialTemplateArgs is false (the list of arguments is complete but
6145 // still dependent).
6146 if (CTAI.MatchingTTP ||
6147 (CurrentInstantiationScope &&
6148 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6149 while (ArgIdx < NumArgs &&
6150 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6151 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6152 CTAI.SugaredConverted.push_back(Elt: Arg);
6153 CTAI.CanonicalConverted.push_back(
6154 Elt: Context.getCanonicalTemplateArgument(Arg));
6155 }
6156 }
6157
6158 // If we have any leftover arguments, then there were too many arguments.
6159 // Complain and fail.
6160 if (ArgIdx < NumArgs) {
6161 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6162 << /*too many args*/1
6163 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6164 << Template
6165 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6166 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6167 return true;
6168 }
6169
6170 // No problems found with the new argument list, propagate changes back
6171 // to caller.
6172 if (UpdateArgsWithConversions)
6173 TemplateArgs = std::move(NewArgs);
6174
6175 if (!PartialTemplateArgs) {
6176 // Setup the context/ThisScope for the case where we are needing to
6177 // re-instantiate constraints outside of normal instantiation.
6178 DeclContext *NewContext = Template->getDeclContext();
6179
6180 // If this template is in a template, make sure we extract the templated
6181 // decl.
6182 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6183 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6184 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6185
6186 Qualifiers ThisQuals;
6187 if (const auto *Method =
6188 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6189 ThisQuals = Method->getMethodQualifiers();
6190
6191 ContextRAII Context(*this, NewContext);
6192 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6193
6194 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6195 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6196 /*RelativeToPrimary=*/true,
6197 /*Pattern=*/nullptr,
6198 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6199 if (!isa<ConceptDecl>(Val: Template) &&
6200 EnsureTemplateArgumentListConstraints(
6201 Template, TemplateArgs: MLTAL,
6202 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6203 if (ConstraintsNotSatisfied)
6204 *ConstraintsNotSatisfied = true;
6205 return true;
6206 }
6207 }
6208
6209 return false;
6210}
6211
6212namespace {
6213 class UnnamedLocalNoLinkageFinder
6214 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6215 {
6216 Sema &S;
6217 SourceRange SR;
6218
6219 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6220
6221 public:
6222 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6223
6224 bool Visit(QualType T) {
6225 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6226 }
6227
6228#define TYPE(Class, Parent) \
6229 bool Visit##Class##Type(const Class##Type *);
6230#define ABSTRACT_TYPE(Class, Parent) \
6231 bool Visit##Class##Type(const Class##Type *) { return false; }
6232#define NON_CANONICAL_TYPE(Class, Parent) \
6233 bool Visit##Class##Type(const Class##Type *) { return false; }
6234#include "clang/AST/TypeNodes.inc"
6235
6236 bool VisitTagDecl(const TagDecl *Tag);
6237 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6238 };
6239} // end anonymous namespace
6240
6241bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6242 return false;
6243}
6244
6245bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6246 return Visit(T: T->getElementType());
6247}
6248
6249bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6250 return Visit(T: T->getPointeeType());
6251}
6252
6253bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6254 const BlockPointerType* T) {
6255 return Visit(T: T->getPointeeType());
6256}
6257
6258bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6259 const LValueReferenceType* T) {
6260 return Visit(T: T->getPointeeType());
6261}
6262
6263bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6264 const RValueReferenceType* T) {
6265 return Visit(T: T->getPointeeType());
6266}
6267
6268bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6269 const MemberPointerType *T) {
6270 if (Visit(T: T->getPointeeType()))
6271 return true;
6272 if (auto *RD = T->getMostRecentCXXRecordDecl())
6273 return VisitTagDecl(Tag: RD);
6274 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6275}
6276
6277bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6278 const ConstantArrayType* T) {
6279 return Visit(T: T->getElementType());
6280}
6281
6282bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6283 const IncompleteArrayType* T) {
6284 return Visit(T: T->getElementType());
6285}
6286
6287bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6288 const VariableArrayType* T) {
6289 return Visit(T: T->getElementType());
6290}
6291
6292bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6293 const DependentSizedArrayType* T) {
6294 return Visit(T: T->getElementType());
6295}
6296
6297bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6298 const DependentSizedExtVectorType* T) {
6299 return Visit(T: T->getElementType());
6300}
6301
6302bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6303 const DependentSizedMatrixType *T) {
6304 return Visit(T: T->getElementType());
6305}
6306
6307bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6308 const DependentAddressSpaceType *T) {
6309 return Visit(T: T->getPointeeType());
6310}
6311
6312bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6313 return Visit(T: T->getElementType());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6317 const DependentVectorType *T) {
6318 return Visit(T: T->getElementType());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6322 return Visit(T: T->getElementType());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6326 const ConstantMatrixType *T) {
6327 return Visit(T: T->getElementType());
6328}
6329
6330bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6331 const FunctionProtoType* T) {
6332 for (const auto &A : T->param_types()) {
6333 if (Visit(T: A))
6334 return true;
6335 }
6336
6337 return Visit(T: T->getReturnType());
6338}
6339
6340bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6341 const FunctionNoProtoType* T) {
6342 return Visit(T: T->getReturnType());
6343}
6344
6345bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6346 const UnresolvedUsingType*) {
6347 return false;
6348}
6349
6350bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6351 return false;
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6355 return Visit(T: T->getUnmodifiedType());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6359 return false;
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6363 const PackIndexingType *) {
6364 return false;
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6368 const UnaryTransformType*) {
6369 return false;
6370}
6371
6372bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6373 return Visit(T: T->getDeducedType());
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6377 const DeducedTemplateSpecializationType *T) {
6378 return Visit(T: T->getDeducedType());
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6382 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6386 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6390 const TemplateTypeParmType*) {
6391 return false;
6392}
6393
6394bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6395 const SubstTemplateTypeParmPackType *) {
6396 return false;
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6400 const SubstBuiltinTemplatePackType *) {
6401 return false;
6402}
6403
6404bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6405 const TemplateSpecializationType*) {
6406 return false;
6407}
6408
6409bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6410 const InjectedClassNameType* T) {
6411 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6412}
6413
6414bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6415 const DependentNameType* T) {
6416 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6417}
6418
6419bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6420 const PackExpansionType* T) {
6421 return Visit(T: T->getPattern());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6429 const ObjCInterfaceType *) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6434 const ObjCObjectPointerType *) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6439 return Visit(T: T->getValueType());
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6443 return false;
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6447 return false;
6448}
6449
6450bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6451 const ArrayParameterType *T) {
6452 return VisitConstantArrayType(T);
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6456 const DependentBitIntType *T) {
6457 return false;
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6461 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6462 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6463 ? diag::warn_cxx98_compat_template_arg_local_type
6464 : diag::ext_template_arg_local_type)
6465 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6466 return true;
6467 }
6468
6469 if (!Tag->hasNameForLinkage()) {
6470 S.Diag(Loc: SR.getBegin(),
6471 DiagID: S.getLangOpts().CPlusPlus11 ?
6472 diag::warn_cxx98_compat_template_arg_unnamed_type :
6473 diag::ext_template_arg_unnamed_type) << SR;
6474 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6475 return true;
6476 }
6477
6478 return false;
6479}
6480
6481bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6482 NestedNameSpecifier NNS) {
6483 switch (NNS.getKind()) {
6484 case NestedNameSpecifier::Kind::Null:
6485 case NestedNameSpecifier::Kind::Namespace:
6486 case NestedNameSpecifier::Kind::Global:
6487 case NestedNameSpecifier::Kind::MicrosoftSuper:
6488 return false;
6489 case NestedNameSpecifier::Kind::Type:
6490 return Visit(T: QualType(NNS.getAsType(), 0));
6491 }
6492 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6493}
6494
6495bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6496 const HLSLAttributedResourceType *T) {
6497 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6498 return true;
6499 return Visit(T: T->getWrappedType());
6500}
6501
6502bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6503 const HLSLInlineSpirvType *T) {
6504 for (auto &Operand : T->getOperands())
6505 if (Operand.isConstant() && Operand.isLiteral())
6506 if (Visit(T: Operand.getResultType()))
6507 return true;
6508 return false;
6509}
6510
6511bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6512 assert(ArgInfo && "invalid TypeSourceInfo");
6513 QualType Arg = ArgInfo->getType();
6514 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6515 QualType CanonArg = Context.getCanonicalType(T: Arg);
6516
6517 if (CanonArg->isVariablyModifiedType()) {
6518 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6519 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6520 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6521 }
6522
6523 // C++03 [temp.arg.type]p2:
6524 // A local type, a type with no linkage, an unnamed type or a type
6525 // compounded from any of these types shall not be used as a
6526 // template-argument for a template type-parameter.
6527 //
6528 // C++11 allows these, and even in C++03 we allow them as an extension with
6529 // a warning.
6530 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6531 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6532 (void)Finder.Visit(T: CanonArg);
6533 }
6534
6535 return false;
6536}
6537
6538enum NullPointerValueKind {
6539 NPV_NotNullPointer,
6540 NPV_NullPointer,
6541 NPV_Error
6542};
6543
6544/// Determine whether the given template argument is a null pointer
6545/// value of the appropriate type.
6546static NullPointerValueKind
6547isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6548 QualType ParamType, Expr *Arg,
6549 Decl *Entity = nullptr) {
6550 if (Arg->isValueDependent() || Arg->isTypeDependent())
6551 return NPV_NotNullPointer;
6552
6553 // dllimport'd entities aren't constant but are available inside of template
6554 // arguments.
6555 if (Entity && Entity->hasAttr<DLLImportAttr>())
6556 return NPV_NotNullPointer;
6557
6558 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6559 llvm_unreachable(
6560 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6561
6562 if (!S.getLangOpts().CPlusPlus11)
6563 return NPV_NotNullPointer;
6564
6565 // Determine whether we have a constant expression.
6566 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6567 if (ArgRV.isInvalid())
6568 return NPV_Error;
6569 Arg = ArgRV.get();
6570
6571 Expr::EvalResult EvalResult;
6572 SmallVector<PartialDiagnosticAt, 8> Notes;
6573 EvalResult.Diag = &Notes;
6574 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6575 EvalResult.HasSideEffects) {
6576 SourceLocation DiagLoc = Arg->getExprLoc();
6577
6578 // If our only note is the usual "invalid subexpression" note, just point
6579 // the caret at its location rather than producing an essentially
6580 // redundant note.
6581 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6582 diag::note_invalid_subexpr_in_const_expr) {
6583 DiagLoc = Notes[0].first;
6584 Notes.clear();
6585 }
6586
6587 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6588 << Arg->getType() << Arg->getSourceRange();
6589 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6590 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6591
6592 S.NoteTemplateParameterLocation(Decl: *Param);
6593 return NPV_Error;
6594 }
6595
6596 // C++11 [temp.arg.nontype]p1:
6597 // - an address constant expression of type std::nullptr_t
6598 if (Arg->getType()->isNullPtrType())
6599 return NPV_NullPointer;
6600
6601 // - a constant expression that evaluates to a null pointer value (4.10); or
6602 // - a constant expression that evaluates to a null member pointer value
6603 // (4.11); or
6604 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6605 (EvalResult.Val.isMemberPointer() &&
6606 !EvalResult.Val.getMemberPointerDecl())) {
6607 // If our expression has an appropriate type, we've succeeded.
6608 bool ObjCLifetimeConversion;
6609 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6610 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6611 ObjCLifetimeConversion))
6612 return NPV_NullPointer;
6613
6614 // The types didn't match, but we know we got a null pointer; complain,
6615 // then recover as if the types were correct.
6616 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6617 << Arg->getType() << ParamType << Arg->getSourceRange();
6618 S.NoteTemplateParameterLocation(Decl: *Param);
6619 return NPV_NullPointer;
6620 }
6621
6622 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6623 // We found a pointer that isn't null, but doesn't refer to an object.
6624 // We could just return NPV_NotNullPointer, but we can print a better
6625 // message with the information we have here.
6626 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6627 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6628 S.NoteTemplateParameterLocation(Decl: *Param);
6629 return NPV_Error;
6630 }
6631
6632 // If we don't have a null pointer value, but we do have a NULL pointer
6633 // constant, suggest a cast to the appropriate type.
6634 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6635 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6636 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6637 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6638 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6639 Code: ")");
6640 S.NoteTemplateParameterLocation(Decl: *Param);
6641 return NPV_NullPointer;
6642 }
6643
6644 // FIXME: If we ever want to support general, address-constant expressions
6645 // as non-type template arguments, we should return the ExprResult here to
6646 // be interpreted by the caller.
6647 return NPV_NotNullPointer;
6648}
6649
6650/// Checks whether the given template argument is compatible with its
6651/// template parameter.
6652static bool
6653CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6654 QualType ParamType, Expr *ArgIn,
6655 Expr *Arg, QualType ArgType) {
6656 bool ObjCLifetimeConversion;
6657 if (ParamType->isPointerType() &&
6658 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6659 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6660 ObjCLifetimeConversion)) {
6661 // For pointer-to-object types, qualification conversions are
6662 // permitted.
6663 } else {
6664 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6665 if (!ParamRef->getPointeeType()->isFunctionType()) {
6666 // C++ [temp.arg.nontype]p5b3:
6667 // For a non-type template-parameter of type reference to
6668 // object, no conversions apply. The type referred to by the
6669 // reference may be more cv-qualified than the (otherwise
6670 // identical) type of the template- argument. The
6671 // template-parameter is bound directly to the
6672 // template-argument, which shall be an lvalue.
6673
6674 // FIXME: Other qualifiers?
6675 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6676 unsigned ArgQuals = ArgType.getCVRQualifiers();
6677
6678 if ((ParamQuals | ArgQuals) != ParamQuals) {
6679 S.Diag(Loc: Arg->getBeginLoc(),
6680 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6681 << ParamType << Arg->getType() << Arg->getSourceRange();
6682 S.NoteTemplateParameterLocation(Decl: *Param);
6683 return true;
6684 }
6685 }
6686 }
6687
6688 // At this point, the template argument refers to an object or
6689 // function with external linkage. We now need to check whether the
6690 // argument and parameter types are compatible.
6691 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6692 T2: ParamType.getNonReferenceType())) {
6693 // We can't perform this conversion or binding.
6694 if (ParamType->isReferenceType())
6695 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6696 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6697 else
6698 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6699 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6700 S.NoteTemplateParameterLocation(Decl: *Param);
6701 return true;
6702 }
6703 }
6704
6705 return false;
6706}
6707
6708/// Checks whether the given template argument is the address
6709/// of an object or function according to C++ [temp.arg.nontype]p1.
6710static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6711 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6712 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6713 bool Invalid = false;
6714 Expr *Arg = ArgIn;
6715 QualType ArgType = Arg->getType();
6716
6717 bool AddressTaken = false;
6718 SourceLocation AddrOpLoc;
6719 if (S.getLangOpts().MicrosoftExt) {
6720 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6721 // dereference and address-of operators.
6722 Arg = Arg->IgnoreParenCasts();
6723
6724 bool ExtWarnMSTemplateArg = false;
6725 UnaryOperatorKind FirstOpKind;
6726 SourceLocation FirstOpLoc;
6727 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6728 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6729 if (UnOpKind == UO_Deref)
6730 ExtWarnMSTemplateArg = true;
6731 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6732 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6733 if (!AddrOpLoc.isValid()) {
6734 FirstOpKind = UnOpKind;
6735 FirstOpLoc = UnOp->getOperatorLoc();
6736 }
6737 } else
6738 break;
6739 }
6740 if (FirstOpLoc.isValid()) {
6741 if (ExtWarnMSTemplateArg)
6742 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6743 << ArgIn->getSourceRange();
6744
6745 if (FirstOpKind == UO_AddrOf)
6746 AddressTaken = true;
6747 else if (Arg->getType()->isPointerType()) {
6748 // We cannot let pointers get dereferenced here, that is obviously not a
6749 // constant expression.
6750 assert(FirstOpKind == UO_Deref);
6751 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6752 << Arg->getSourceRange();
6753 }
6754 }
6755 } else {
6756 // See through any implicit casts we added to fix the type.
6757 Arg = Arg->IgnoreImpCasts();
6758
6759 // C++ [temp.arg.nontype]p1:
6760 //
6761 // A template-argument for a non-type, non-template
6762 // template-parameter shall be one of: [...]
6763 //
6764 // -- the address of an object or function with external
6765 // linkage, including function templates and function
6766 // template-ids but excluding non-static class members,
6767 // expressed as & id-expression where the & is optional if
6768 // the name refers to a function or array, or if the
6769 // corresponding template-parameter is a reference; or
6770
6771 // In C++98/03 mode, give an extension warning on any extra parentheses.
6772 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6773 bool ExtraParens = false;
6774 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6775 if (!Invalid && !ExtraParens) {
6776 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6777 << Arg->getSourceRange();
6778 ExtraParens = true;
6779 }
6780
6781 Arg = Parens->getSubExpr();
6782 }
6783
6784 while (SubstNonTypeTemplateParmExpr *subst =
6785 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6786 Arg = subst->getReplacement()->IgnoreImpCasts();
6787
6788 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6789 if (UnOp->getOpcode() == UO_AddrOf) {
6790 Arg = UnOp->getSubExpr();
6791 AddressTaken = true;
6792 AddrOpLoc = UnOp->getOperatorLoc();
6793 }
6794 }
6795
6796 while (SubstNonTypeTemplateParmExpr *subst =
6797 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6798 Arg = subst->getReplacement()->IgnoreImpCasts();
6799 }
6800
6801 ValueDecl *Entity = nullptr;
6802 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6803 Entity = DRE->getDecl();
6804 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6805 Entity = CUE->getGuidDecl();
6806
6807 // If our parameter has pointer type, check for a null template value.
6808 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6809 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6810 Entity)) {
6811 case NPV_NullPointer:
6812 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6813 SugaredConverted = TemplateArgument(ParamType,
6814 /*isNullPtr=*/true);
6815 CanonicalConverted =
6816 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6817 /*isNullPtr=*/true);
6818 return false;
6819
6820 case NPV_Error:
6821 return true;
6822
6823 case NPV_NotNullPointer:
6824 break;
6825 }
6826 }
6827
6828 // Stop checking the precise nature of the argument if it is value dependent,
6829 // it should be checked when instantiated.
6830 if (Arg->isValueDependent()) {
6831 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6832 CanonicalConverted =
6833 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6834 return false;
6835 }
6836
6837 if (!Entity) {
6838 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6839 << Arg->getSourceRange();
6840 S.NoteTemplateParameterLocation(Decl: *Param);
6841 return true;
6842 }
6843
6844 // Cannot refer to non-static data members
6845 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6846 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6847 << Entity << Arg->getSourceRange();
6848 S.NoteTemplateParameterLocation(Decl: *Param);
6849 return true;
6850 }
6851
6852 // Cannot refer to non-static member functions
6853 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6854 if (!Method->isStatic()) {
6855 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6856 << Method << Arg->getSourceRange();
6857 S.NoteTemplateParameterLocation(Decl: *Param);
6858 return true;
6859 }
6860 }
6861
6862 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6863 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6864 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6865
6866 // A non-type template argument must refer to an object or function.
6867 if (!Func && !Var && !Guid) {
6868 // We found something, but we don't know specifically what it is.
6869 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6870 << Arg->getSourceRange();
6871 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6872 return true;
6873 }
6874
6875 // Address / reference template args must have external linkage in C++98.
6876 if (Entity->getFormalLinkage() == Linkage::Internal) {
6877 S.Diag(Loc: Arg->getBeginLoc(),
6878 DiagID: S.getLangOpts().CPlusPlus11
6879 ? diag::warn_cxx98_compat_template_arg_object_internal
6880 : diag::ext_template_arg_object_internal)
6881 << !Func << Entity << Arg->getSourceRange();
6882 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6883 << !Func;
6884 } else if (!Entity->hasLinkage()) {
6885 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6886 << !Func << Entity << Arg->getSourceRange();
6887 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6888 << !Func;
6889 return true;
6890 }
6891
6892 if (Var) {
6893 // A value of reference type is not an object.
6894 if (Var->getType()->isReferenceType()) {
6895 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6896 << Var->getType() << Arg->getSourceRange();
6897 S.NoteTemplateParameterLocation(Decl: *Param);
6898 return true;
6899 }
6900
6901 // A template argument must have static storage duration.
6902 if (Var->getTLSKind()) {
6903 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6904 << Arg->getSourceRange();
6905 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6906 return true;
6907 }
6908 }
6909
6910 if (AddressTaken && ParamType->isReferenceType()) {
6911 // If we originally had an address-of operator, but the
6912 // parameter has reference type, complain and (if things look
6913 // like they will work) drop the address-of operator.
6914 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6915 T2: ParamType.getNonReferenceType())) {
6916 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6917 << ParamType;
6918 S.NoteTemplateParameterLocation(Decl: *Param);
6919 return true;
6920 }
6921
6922 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6923 << ParamType
6924 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6925 S.NoteTemplateParameterLocation(Decl: *Param);
6926
6927 ArgType = Entity->getType();
6928 }
6929
6930 // If the template parameter has pointer type, either we must have taken the
6931 // address or the argument must decay to a pointer.
6932 if (!AddressTaken && ParamType->isPointerType()) {
6933 if (Func) {
6934 // Function-to-pointer decay.
6935 ArgType = S.Context.getPointerType(T: Func->getType());
6936 } else if (Entity->getType()->isArrayType()) {
6937 // Array-to-pointer decay.
6938 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6939 } else {
6940 // If the template parameter has pointer type but the address of
6941 // this object was not taken, complain and (possibly) recover by
6942 // taking the address of the entity.
6943 ArgType = S.Context.getPointerType(T: Entity->getType());
6944 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6945 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6946 << ParamType;
6947 S.NoteTemplateParameterLocation(Decl: *Param);
6948 return true;
6949 }
6950
6951 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6952 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6953
6954 S.NoteTemplateParameterLocation(Decl: *Param);
6955 }
6956 }
6957
6958 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6959 Arg, ArgType))
6960 return true;
6961
6962 // Create the template argument.
6963 SugaredConverted = TemplateArgument(Entity, ParamType);
6964 CanonicalConverted =
6965 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6966 S.Context.getCanonicalType(T: ParamType));
6967 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6968 return false;
6969}
6970
6971/// Checks whether the given template argument is a pointer to
6972/// member constant according to C++ [temp.arg.nontype]p1.
6973static bool CheckTemplateArgumentPointerToMember(
6974 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6975 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6976 bool Invalid = false;
6977
6978 Expr *Arg = ResultArg;
6979 bool ObjCLifetimeConversion;
6980
6981 // C++ [temp.arg.nontype]p1:
6982 //
6983 // A template-argument for a non-type, non-template
6984 // template-parameter shall be one of: [...]
6985 //
6986 // -- a pointer to member expressed as described in 5.3.1.
6987 DeclRefExpr *DRE = nullptr;
6988
6989 // In C++98/03 mode, give an extension warning on any extra parentheses.
6990 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6991 bool ExtraParens = false;
6992 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6993 if (!Invalid && !ExtraParens) {
6994 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6995 << Arg->getSourceRange();
6996 ExtraParens = true;
6997 }
6998
6999 Arg = Parens->getSubExpr();
7000 }
7001
7002 while (SubstNonTypeTemplateParmExpr *subst =
7003 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7004 Arg = subst->getReplacement()->IgnoreImpCasts();
7005
7006 // A pointer-to-member constant written &Class::member.
7007 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7008 if (UnOp->getOpcode() == UO_AddrOf) {
7009 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7010 if (DRE && !DRE->getQualifier())
7011 DRE = nullptr;
7012 }
7013 }
7014 // A constant of pointer-to-member type.
7015 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7016 ValueDecl *VD = DRE->getDecl();
7017 if (VD->getType()->isMemberPointerType()) {
7018 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7019 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7020 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7021 CanonicalConverted =
7022 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7023 } else {
7024 SugaredConverted = TemplateArgument(VD, ParamType);
7025 CanonicalConverted =
7026 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7027 S.Context.getCanonicalType(T: ParamType));
7028 }
7029 return Invalid;
7030 }
7031 }
7032
7033 DRE = nullptr;
7034 }
7035
7036 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7037
7038 // Check for a null pointer value.
7039 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7040 Entity)) {
7041 case NPV_Error:
7042 return true;
7043 case NPV_NullPointer:
7044 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7045 SugaredConverted = TemplateArgument(ParamType,
7046 /*isNullPtr*/ true);
7047 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7048 /*isNullPtr*/ true);
7049 return false;
7050 case NPV_NotNullPointer:
7051 break;
7052 }
7053
7054 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7055 ToType: ParamType.getNonReferenceType(), CStyle: false,
7056 ObjCLifetimeConversion)) {
7057 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7058 VK: ResultArg->getValueKind())
7059 .get();
7060 } else if (!S.Context.hasSameUnqualifiedType(
7061 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7062 // We can't perform this conversion.
7063 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7064 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7065 S.NoteTemplateParameterLocation(Decl: *Param);
7066 return true;
7067 }
7068
7069 if (!DRE)
7070 return S.Diag(Loc: Arg->getBeginLoc(),
7071 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7072 << Arg->getSourceRange();
7073
7074 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7075 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7076 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7077 assert((isa<FieldDecl>(DRE->getDecl()) ||
7078 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7079 cast<CXXMethodDecl>(DRE->getDecl())
7080 ->isImplicitObjectMemberFunction()) &&
7081 "Only non-static member pointers can make it here");
7082
7083 // Okay: this is the address of a non-static member, and therefore
7084 // a member pointer constant.
7085 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7086 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7087 CanonicalConverted =
7088 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7089 } else {
7090 ValueDecl *D = DRE->getDecl();
7091 SugaredConverted = TemplateArgument(D, ParamType);
7092 CanonicalConverted =
7093 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7094 S.Context.getCanonicalType(T: ParamType));
7095 }
7096 return Invalid;
7097 }
7098
7099 // We found something else, but we don't know specifically what it is.
7100 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7101 << Arg->getSourceRange();
7102 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7103 return true;
7104}
7105
7106/// Check a template argument against its corresponding
7107/// non-type template parameter.
7108///
7109/// This routine implements the semantics of C++ [temp.arg.nontype].
7110/// If an error occurred, it returns ExprError(); otherwise, it
7111/// returns the converted template argument. \p ParamType is the
7112/// type of the non-type template parameter after it has been instantiated.
7113ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7114 Expr *Arg,
7115 TemplateArgument &SugaredConverted,
7116 TemplateArgument &CanonicalConverted,
7117 bool StrictCheck,
7118 CheckTemplateArgumentKind CTAK) {
7119 SourceLocation StartLoc = Arg->getBeginLoc();
7120 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7121 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7122 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7123 DeductionArg = NewDeductionArg;
7124 if (ArgPE) {
7125 // Recreate a pack expansion if we unwrapped one.
7126 Arg = new (Context) PackExpansionExpr(
7127 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7128 } else {
7129 Arg = DeductionArg;
7130 }
7131 };
7132
7133 // If the parameter type somehow involves auto, deduce the type now.
7134 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7135 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7136 if (IsDeduced) {
7137 // When checking a deduced template argument, deduce from its type even if
7138 // the type is dependent, in order to check the types of non-type template
7139 // arguments line up properly in partial ordering.
7140 TypeSourceInfo *TSI =
7141 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7142 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7143 InitializedEntity Entity =
7144 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7145 InitializationKind Kind = InitializationKind::CreateForInit(
7146 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7147 Expr *Inits[1] = {DeductionArg};
7148 ParamType =
7149 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7150 if (ParamType.isNull())
7151 return ExprError();
7152 } else {
7153 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7154 Param->getTemplateDepth() + 1);
7155 ParamType = QualType();
7156 TemplateDeductionResult Result =
7157 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7158 /*DependentDeduction=*/true,
7159 // We do not check constraints right now because the
7160 // immediately-declared constraint of the auto type is
7161 // also an associated constraint, and will be checked
7162 // along with the other associated constraints after
7163 // checking the template argument list.
7164 /*IgnoreConstraints=*/true);
7165 if (Result != TemplateDeductionResult::Success) {
7166 ParamType = TSI->getType();
7167 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7168 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7169 return ExprError();
7170 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7171 Diag(Loc: Arg->getExprLoc(),
7172 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7173 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7174 << Arg->getSourceRange();
7175 NoteTemplateParameterLocation(Decl: *Param);
7176 return ExprError();
7177 }
7178 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7179 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7180 }
7181 }
7182 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7183 // an error. The error message normally references the parameter
7184 // declaration, but here we'll pass the argument location because that's
7185 // where the parameter type is deduced.
7186 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7187 if (ParamType.isNull()) {
7188 NoteTemplateParameterLocation(Decl: *Param);
7189 return ExprError();
7190 }
7191 }
7192
7193 // We should have already dropped all cv-qualifiers by now.
7194 assert(!ParamType.hasQualifiers() &&
7195 "non-type template parameter type cannot be qualified");
7196
7197 // If either the parameter has a dependent type or the argument is
7198 // type-dependent, there's nothing we can check now.
7199 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7200 // Force the argument to the type of the parameter to maintain invariants.
7201 if (!IsDeduced) {
7202 ExprResult E = ImpCastExprToType(
7203 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7204 VK: ParamType->isLValueReferenceType() ? VK_LValue
7205 : ParamType->isRValueReferenceType() ? VK_XValue
7206 : VK_PRValue);
7207 if (E.isInvalid())
7208 return ExprError();
7209 setDeductionArg(E.get());
7210 }
7211 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7212 CanonicalConverted = TemplateArgument(
7213 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7214 return Arg;
7215 }
7216
7217 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7218 if (CTAK == CTAK_Deduced && !StrictCheck &&
7219 (ParamType->isReferenceType()
7220 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7221 T2: DeductionArg->getType())
7222 : !Context.hasSameUnqualifiedType(T1: ParamType,
7223 T2: DeductionArg->getType()))) {
7224 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7225 // we should actually be checking the type of the template argument in P,
7226 // not the type of the template argument deduced from A, against the
7227 // template parameter type.
7228 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7229 << Arg->getType() << ParamType.getUnqualifiedType();
7230 NoteTemplateParameterLocation(Decl: *Param);
7231 return ExprError();
7232 }
7233
7234 // If the argument is a pack expansion, we don't know how many times it would
7235 // expand. If we continue checking the argument, this will make the template
7236 // definition ill-formed if it would be ill-formed for any number of
7237 // expansions during instantiation time. When partial ordering or matching
7238 // template template parameters, this is exactly what we want. Otherwise, the
7239 // normal template rules apply: we accept the template if it would be valid
7240 // for any number of expansions (i.e. none).
7241 if (ArgPE && !StrictCheck) {
7242 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7243 CanonicalConverted = TemplateArgument(
7244 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7245 return Arg;
7246 }
7247
7248 // Avoid making a copy when initializing a template parameter of class type
7249 // from a template parameter object of the same type. This is going beyond
7250 // the standard, but is required for soundness: in
7251 // template<A a> struct X { X *p; X<a> *q; };
7252 // ... we need p and q to have the same type.
7253 //
7254 // Similarly, don't inject a call to a copy constructor when initializing
7255 // from a template parameter of the same type.
7256 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7257 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7258 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7259 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7260 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7261
7262 SugaredConverted = TemplateArgument(TPO, ParamType);
7263 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7264 ParamType.getCanonicalType());
7265 return Arg;
7266 }
7267 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7268 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7269 CanonicalConverted =
7270 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7271 return Arg;
7272 }
7273 }
7274
7275 // The initialization of the parameter from the argument is
7276 // a constant-evaluated context.
7277 EnterExpressionEvaluationContext ConstantEvaluated(
7278 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7279
7280 bool IsConvertedConstantExpression = true;
7281 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7282 InitializationKind Kind = InitializationKind::CreateForInit(
7283 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7284 Expr *Inits[1] = {DeductionArg};
7285 InitializedEntity Entity =
7286 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7287 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7288 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7289 if (Result.isInvalid() || !Result.get())
7290 return ExprError();
7291 Result = ActOnConstantExpression(Res: Result.get());
7292 if (Result.isInvalid() || !Result.get())
7293 return ExprError();
7294 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7295 /*DiscardedValue=*/false,
7296 /*IsConstexpr=*/true,
7297 /*IsTemplateArgument=*/true)
7298 .get());
7299 IsConvertedConstantExpression = false;
7300 }
7301
7302 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7303 // C++17 [temp.arg.nontype]p1:
7304 // A template-argument for a non-type template parameter shall be
7305 // a converted constant expression of the type of the template-parameter.
7306 APValue Value;
7307 ExprResult ArgResult;
7308 if (IsConvertedConstantExpression) {
7309 ArgResult = BuildConvertedConstantExpression(
7310 From: DeductionArg, T: ParamType,
7311 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7312 assert(!ArgResult.isUnset());
7313 if (ArgResult.isInvalid()) {
7314 NoteTemplateParameterLocation(Decl: *Param);
7315 return ExprError();
7316 }
7317 } else {
7318 ArgResult = DeductionArg;
7319 }
7320
7321 // For a value-dependent argument, CheckConvertedConstantExpression is
7322 // permitted (and expected) to be unable to determine a value.
7323 if (ArgResult.get()->isValueDependent()) {
7324 setDeductionArg(ArgResult.get());
7325 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7326 CanonicalConverted =
7327 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7328 return Arg;
7329 }
7330
7331 APValue PreNarrowingValue;
7332 ArgResult = EvaluateConvertedConstantExpression(
7333 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7334 false, PreNarrowingValue);
7335 if (ArgResult.isInvalid())
7336 return ExprError();
7337 setDeductionArg(ArgResult.get());
7338
7339 if (Value.isLValue()) {
7340 APValue::LValueBase Base = Value.getLValueBase();
7341 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7342 // For a non-type template-parameter of pointer or reference type,
7343 // the value of the constant expression shall not refer to
7344 assert(ParamType->isPointerOrReferenceType() ||
7345 ParamType->isNullPtrType());
7346 // -- a temporary object
7347 // -- a string literal
7348 // -- the result of a typeid expression, or
7349 // -- a predefined __func__ variable
7350 if (Base &&
7351 (!VD ||
7352 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7353 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7354 << Arg->getSourceRange();
7355 return ExprError();
7356 }
7357
7358 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7359 VD->getType()->isArrayType() &&
7360 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7361 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7362 if (ArgPE) {
7363 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7364 CanonicalConverted =
7365 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7366 } else {
7367 SugaredConverted = TemplateArgument(VD, ParamType);
7368 CanonicalConverted =
7369 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7370 ParamType.getCanonicalType());
7371 }
7372 return Arg;
7373 }
7374
7375 // -- a subobject [until C++20]
7376 if (!getLangOpts().CPlusPlus20) {
7377 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7378 Value.isLValueOnePastTheEnd()) {
7379 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7380 << Value.getAsString(Ctx: Context, Ty: ParamType);
7381 return ExprError();
7382 }
7383 assert((VD || !ParamType->isReferenceType()) &&
7384 "null reference should not be a constant expression");
7385 assert((!VD || !ParamType->isNullPtrType()) &&
7386 "non-null value of type nullptr_t?");
7387 }
7388 }
7389
7390 if (Value.isAddrLabelDiff())
7391 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7392
7393 if (ArgPE) {
7394 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7395 CanonicalConverted =
7396 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7397 } else {
7398 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7399 CanonicalConverted =
7400 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7401 }
7402 return Arg;
7403 }
7404
7405 // These should have all been handled above using the C++17 rules.
7406 assert(!ArgPE && !StrictCheck);
7407
7408 // C++ [temp.arg.nontype]p5:
7409 // The following conversions are performed on each expression used
7410 // as a non-type template-argument. If a non-type
7411 // template-argument cannot be converted to the type of the
7412 // corresponding template-parameter then the program is
7413 // ill-formed.
7414 if (ParamType->isIntegralOrEnumerationType()) {
7415 // C++11:
7416 // -- for a non-type template-parameter of integral or
7417 // enumeration type, conversions permitted in a converted
7418 // constant expression are applied.
7419 //
7420 // C++98:
7421 // -- for a non-type template-parameter of integral or
7422 // enumeration type, integral promotions (4.5) and integral
7423 // conversions (4.7) are applied.
7424
7425 if (getLangOpts().CPlusPlus11) {
7426 // C++ [temp.arg.nontype]p1:
7427 // A template-argument for a non-type, non-template template-parameter
7428 // shall be one of:
7429 //
7430 // -- for a non-type template-parameter of integral or enumeration
7431 // type, a converted constant expression of the type of the
7432 // template-parameter; or
7433 llvm::APSInt Value;
7434 ExprResult ArgResult = CheckConvertedConstantExpression(
7435 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7436 if (ArgResult.isInvalid())
7437 return ExprError();
7438 Arg = ArgResult.get();
7439
7440 // We can't check arbitrary value-dependent arguments.
7441 if (Arg->isValueDependent()) {
7442 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7443 CanonicalConverted =
7444 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7445 return Arg;
7446 }
7447
7448 // Widen the argument value to sizeof(parameter type). This is almost
7449 // always a no-op, except when the parameter type is bool. In
7450 // that case, this may extend the argument from 1 bit to 8 bits.
7451 QualType IntegerType = ParamType;
7452 if (const auto *ED = IntegerType->getAsEnumDecl())
7453 IntegerType = ED->getIntegerType();
7454 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7455 ? Context.getIntWidth(T: IntegerType)
7456 : Context.getTypeSize(T: IntegerType));
7457
7458 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7459 CanonicalConverted =
7460 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7461 return Arg;
7462 }
7463
7464 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7465 if (ArgResult.isInvalid())
7466 return ExprError();
7467 Arg = ArgResult.get();
7468
7469 QualType ArgType = Arg->getType();
7470
7471 // C++ [temp.arg.nontype]p1:
7472 // A template-argument for a non-type, non-template
7473 // template-parameter shall be one of:
7474 //
7475 // -- an integral constant-expression of integral or enumeration
7476 // type; or
7477 // -- the name of a non-type template-parameter; or
7478 llvm::APSInt Value;
7479 if (!ArgType->isIntegralOrEnumerationType()) {
7480 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7481 << ArgType << Arg->getSourceRange();
7482 NoteTemplateParameterLocation(Decl: *Param);
7483 return ExprError();
7484 }
7485 if (!Arg->isValueDependent()) {
7486 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7487 QualType T;
7488
7489 public:
7490 TmplArgICEDiagnoser(QualType T) : T(T) { }
7491
7492 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7493 SourceLocation Loc) override {
7494 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7495 }
7496 } Diagnoser(ArgType);
7497
7498 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7499 if (!Arg)
7500 return ExprError();
7501 }
7502
7503 // From here on out, all we care about is the unqualified form
7504 // of the argument type.
7505 ArgType = ArgType.getUnqualifiedType();
7506
7507 // Try to convert the argument to the parameter's type.
7508 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7509 // Okay: no conversion necessary
7510 } else if (ParamType->isBooleanType()) {
7511 // This is an integral-to-boolean conversion.
7512 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7513 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7514 !ParamType->isEnumeralType()) {
7515 // This is an integral promotion or conversion.
7516 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7517 } else {
7518 // We can't perform this conversion.
7519 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7520 << Arg->getType() << ParamType << Arg->getSourceRange();
7521 NoteTemplateParameterLocation(Decl: *Param);
7522 return ExprError();
7523 }
7524
7525 // Add the value of this argument to the list of converted
7526 // arguments. We use the bitwidth and signedness of the template
7527 // parameter.
7528 if (Arg->isValueDependent()) {
7529 // The argument is value-dependent. Create a new
7530 // TemplateArgument with the converted expression.
7531 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7532 CanonicalConverted =
7533 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7534 return Arg;
7535 }
7536
7537 QualType IntegerType = ParamType;
7538 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7539 IntegerType = ED->getIntegerType();
7540 }
7541
7542 if (ParamType->isBooleanType()) {
7543 // Value must be zero or one.
7544 Value = Value != 0;
7545 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7546 if (Value.getBitWidth() != AllowedBits)
7547 Value = Value.extOrTrunc(width: AllowedBits);
7548 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7549 } else {
7550 llvm::APSInt OldValue = Value;
7551
7552 // Coerce the template argument's value to the value it will have
7553 // based on the template parameter's type.
7554 unsigned AllowedBits = IntegerType->isBitIntType()
7555 ? Context.getIntWidth(T: IntegerType)
7556 : Context.getTypeSize(T: IntegerType);
7557 if (Value.getBitWidth() != AllowedBits)
7558 Value = Value.extOrTrunc(width: AllowedBits);
7559 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7560
7561 // Complain if an unsigned parameter received a negative value.
7562 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7563 (OldValue.isSigned() && OldValue.isNegative())) {
7564 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7565 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7566 << Arg->getSourceRange();
7567 NoteTemplateParameterLocation(Decl: *Param);
7568 }
7569
7570 // Complain if we overflowed the template parameter's type.
7571 unsigned RequiredBits;
7572 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7573 RequiredBits = OldValue.getActiveBits();
7574 else if (OldValue.isUnsigned())
7575 RequiredBits = OldValue.getActiveBits() + 1;
7576 else
7577 RequiredBits = OldValue.getSignificantBits();
7578 if (RequiredBits > AllowedBits) {
7579 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7580 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7581 << Arg->getSourceRange();
7582 NoteTemplateParameterLocation(Decl: *Param);
7583 }
7584 }
7585
7586 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7587 SugaredConverted = TemplateArgument(Context, Value, T);
7588 CanonicalConverted =
7589 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7590 return Arg;
7591 }
7592
7593 QualType ArgType = Arg->getType();
7594 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7595
7596 // Handle pointer-to-function, reference-to-function, and
7597 // pointer-to-member-function all in (roughly) the same way.
7598 if (// -- For a non-type template-parameter of type pointer to
7599 // function, only the function-to-pointer conversion (4.3) is
7600 // applied. If the template-argument represents a set of
7601 // overloaded functions (or a pointer to such), the matching
7602 // function is selected from the set (13.4).
7603 (ParamType->isPointerType() &&
7604 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7605 // -- For a non-type template-parameter of type reference to
7606 // function, no conversions apply. If the template-argument
7607 // represents a set of overloaded functions, the matching
7608 // function is selected from the set (13.4).
7609 (ParamType->isReferenceType() &&
7610 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7611 // -- For a non-type template-parameter of type pointer to
7612 // member function, no conversions apply. If the
7613 // template-argument represents a set of overloaded member
7614 // functions, the matching member function is selected from
7615 // the set (13.4).
7616 (ParamType->isMemberPointerType() &&
7617 ParamType->castAs<MemberPointerType>()->getPointeeType()
7618 ->isFunctionType())) {
7619
7620 if (Arg->getType() == Context.OverloadTy) {
7621 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7622 Complain: true,
7623 Found&: FoundResult)) {
7624 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7625 return ExprError();
7626
7627 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7628 if (Res.isInvalid())
7629 return ExprError();
7630 Arg = Res.get();
7631 ArgType = Arg->getType();
7632 } else
7633 return ExprError();
7634 }
7635
7636 if (!ParamType->isMemberPointerType()) {
7637 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7638 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7639 CanonicalConverted))
7640 return ExprError();
7641 return Arg;
7642 }
7643
7644 if (CheckTemplateArgumentPointerToMember(
7645 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7646 return ExprError();
7647 return Arg;
7648 }
7649
7650 if (ParamType->isPointerType()) {
7651 // -- for a non-type template-parameter of type pointer to
7652 // object, qualification conversions (4.4) and the
7653 // array-to-pointer conversion (4.2) are applied.
7654 // C++0x also allows a value of std::nullptr_t.
7655 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7656 "Only object pointers allowed here");
7657
7658 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7659 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7660 return ExprError();
7661 return Arg;
7662 }
7663
7664 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7665 // -- For a non-type template-parameter of type reference to
7666 // object, no conversions apply. The type referred to by the
7667 // reference may be more cv-qualified than the (otherwise
7668 // identical) type of the template-argument. The
7669 // template-parameter is bound directly to the
7670 // template-argument, which must be an lvalue.
7671 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7672 "Only object references allowed here");
7673
7674 if (Arg->getType() == Context.OverloadTy) {
7675 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7676 TargetType: ParamRefType->getPointeeType(),
7677 Complain: true,
7678 Found&: FoundResult)) {
7679 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7680 return ExprError();
7681 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7682 if (Res.isInvalid())
7683 return ExprError();
7684 Arg = Res.get();
7685 ArgType = Arg->getType();
7686 } else
7687 return ExprError();
7688 }
7689
7690 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7691 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7692 return ExprError();
7693 return Arg;
7694 }
7695
7696 // Deal with parameters of type std::nullptr_t.
7697 if (ParamType->isNullPtrType()) {
7698 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7699 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7700 CanonicalConverted =
7701 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7702 return Arg;
7703 }
7704
7705 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7706 case NPV_NotNullPointer:
7707 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7708 << Arg->getType() << ParamType;
7709 NoteTemplateParameterLocation(Decl: *Param);
7710 return ExprError();
7711
7712 case NPV_Error:
7713 return ExprError();
7714
7715 case NPV_NullPointer:
7716 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7717 SugaredConverted = TemplateArgument(ParamType,
7718 /*isNullPtr=*/true);
7719 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7720 /*isNullPtr=*/true);
7721 return Arg;
7722 }
7723 }
7724
7725 // -- For a non-type template-parameter of type pointer to data
7726 // member, qualification conversions (4.4) are applied.
7727 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7728
7729 if (CheckTemplateArgumentPointerToMember(
7730 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7731 return ExprError();
7732 return Arg;
7733}
7734
7735static void DiagnoseTemplateParameterListArityMismatch(
7736 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7737 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7738
7739bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7740 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7741 const TemplateArgumentLoc &Arg) {
7742 // C++0x [temp.arg.template]p1:
7743 // A template-argument for a template template-parameter shall be
7744 // the name of a class template or an alias template, expressed as an
7745 // id-expression. When the template-argument names a class template, only
7746 // primary class templates are considered when matching the
7747 // template template argument with the corresponding parameter;
7748 // partial specializations are not considered even if their
7749 // parameter lists match that of the template template parameter.
7750 //
7751
7752 TemplateNameKind Kind = TNK_Non_template;
7753 unsigned DiagFoundKind = 0;
7754
7755 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7756 switch (TTP->templateParameterKind()) {
7757 case TemplateNameKind::TNK_Concept_template:
7758 DiagFoundKind = 3;
7759 break;
7760 case TemplateNameKind::TNK_Var_template:
7761 DiagFoundKind = 2;
7762 break;
7763 default:
7764 DiagFoundKind = 1;
7765 break;
7766 }
7767 Kind = TTP->templateParameterKind();
7768 } else if (isa<ConceptDecl>(Val: Template)) {
7769 Kind = TemplateNameKind::TNK_Concept_template;
7770 DiagFoundKind = 3;
7771 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7772 Kind = TemplateNameKind::TNK_Function_template;
7773 DiagFoundKind = 0;
7774 } else if (isa<VarTemplateDecl>(Val: Template)) {
7775 Kind = TemplateNameKind::TNK_Var_template;
7776 DiagFoundKind = 2;
7777 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7778 isa<TypeAliasTemplateDecl>(Val: Template) ||
7779 isa<BuiltinTemplateDecl>(Val: Template)) {
7780 Kind = TemplateNameKind::TNK_Type_template;
7781 DiagFoundKind = 1;
7782 } else {
7783 assert(false && "Unexpected Decl");
7784 }
7785
7786 if (Kind == Param->templateParameterKind()) {
7787 return true;
7788 }
7789
7790 unsigned DiagKind = 0;
7791 switch (Param->templateParameterKind()) {
7792 case TemplateNameKind::TNK_Concept_template:
7793 DiagKind = 2;
7794 break;
7795 case TemplateNameKind::TNK_Var_template:
7796 DiagKind = 1;
7797 break;
7798 default:
7799 DiagKind = 0;
7800 break;
7801 }
7802 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7803 << DiagKind;
7804 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7805 << DiagFoundKind << Template;
7806 return false;
7807}
7808
7809/// Check a template argument against its corresponding
7810/// template template parameter.
7811///
7812/// This routine implements the semantics of C++ [temp.arg.template].
7813/// It returns true if an error occurred, and false otherwise.
7814bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7815 TemplateParameterList *Params,
7816 TemplateArgumentLoc &Arg,
7817 bool PartialOrdering,
7818 bool *StrictPackMatch) {
7819 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7820 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7821 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7822 if (!Template) {
7823 // FIXME: Handle AssumedTemplateNames
7824 // Any dependent template name is fine.
7825 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7826 return false;
7827 }
7828
7829 if (Template->isInvalidDecl())
7830 return true;
7831
7832 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7833 return true;
7834 }
7835
7836 // C++1z [temp.arg.template]p3: (DR 150)
7837 // A template-argument matches a template template-parameter P when P
7838 // is at least as specialized as the template-argument A.
7839 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7840 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7841 PartialOrdering, StrictPackMatch))
7842 return true;
7843 // P2113
7844 // C++20[temp.func.order]p2
7845 // [...] If both deductions succeed, the partial ordering selects the
7846 // more constrained template (if one exists) as determined below.
7847 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7848 Params->getAssociatedConstraints(AC&: ParamsAC);
7849 // C++20[temp.arg.template]p3
7850 // [...] In this comparison, if P is unconstrained, the constraints on A
7851 // are not considered.
7852 if (ParamsAC.empty())
7853 return false;
7854
7855 Template->getAssociatedConstraints(AC&: TemplateAC);
7856
7857 bool IsParamAtLeastAsConstrained;
7858 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7859 Result&: IsParamAtLeastAsConstrained))
7860 return true;
7861 if (!IsParamAtLeastAsConstrained) {
7862 Diag(Loc: Arg.getLocation(),
7863 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7864 << Template << Param << Arg.getSourceRange();
7865 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7866 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7867 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7868 AC2: TemplateAC);
7869 return true;
7870 }
7871 return false;
7872}
7873
7874static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7875 unsigned HereDiagID,
7876 unsigned ExternalDiagID) {
7877 if (Decl.getLocation().isValid())
7878 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7879
7880 SmallString<128> Str;
7881 llvm::raw_svector_ostream Out(Str);
7882 PrintingPolicy PP = S.getPrintingPolicy();
7883 PP.TerseOutput = 1;
7884 Decl.print(Out, Policy: PP);
7885 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7886}
7887
7888void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7889 std::optional<SourceRange> ParamRange) {
7890 SemaDiagnosticBuilder DB =
7891 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7892 ExternalDiagID: diag::note_template_decl_external);
7893 if (ParamRange && ParamRange->isValid()) {
7894 assert(Decl.getLocation().isValid() &&
7895 "Parameter range has location when Decl does not");
7896 DB << *ParamRange;
7897 }
7898}
7899
7900void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7901 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7902 ExternalDiagID: diag::note_template_param_external);
7903}
7904
7905/// Given a non-type template argument that refers to a
7906/// declaration and the type of its corresponding non-type template
7907/// parameter, produce an expression that properly refers to that
7908/// declaration.
7909ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7910 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7911 NamedDecl *TemplateParam) {
7912 // C++ [temp.param]p8:
7913 //
7914 // A non-type template-parameter of type "array of T" or
7915 // "function returning T" is adjusted to be of type "pointer to
7916 // T" or "pointer to function returning T", respectively.
7917 if (ParamType->isArrayType())
7918 ParamType = Context.getArrayDecayedType(T: ParamType);
7919 else if (ParamType->isFunctionType())
7920 ParamType = Context.getPointerType(T: ParamType);
7921
7922 // For a NULL non-type template argument, return nullptr casted to the
7923 // parameter's type.
7924 if (Arg.getKind() == TemplateArgument::NullPtr) {
7925 return ImpCastExprToType(
7926 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7927 Type: ParamType,
7928 CK: ParamType->getAs<MemberPointerType>()
7929 ? CK_NullToMemberPointer
7930 : CK_NullToPointer);
7931 }
7932 assert(Arg.getKind() == TemplateArgument::Declaration &&
7933 "Only declaration template arguments permitted here");
7934
7935 ValueDecl *VD = Arg.getAsDecl();
7936
7937 CXXScopeSpec SS;
7938 if (ParamType->isMemberPointerType()) {
7939 // If this is a pointer to member, we need to use a qualified name to
7940 // form a suitable pointer-to-member constant.
7941 assert(VD->getDeclContext()->isRecord() &&
7942 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7943 isa<IndirectFieldDecl>(VD)));
7944 CanQualType ClassType =
7945 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7946 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7947 SS.MakeTrivial(Context, Qualifier, R: Loc);
7948 }
7949
7950 ExprResult RefExpr = BuildDeclarationNameExpr(
7951 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7952 if (RefExpr.isInvalid())
7953 return ExprError();
7954
7955 // For a pointer, the argument declaration is the pointee. Take its address.
7956 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7957 if (ParamType->isPointerType() && !ElemT.isNull() &&
7958 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7959 // Decay an array argument if we want a pointer to its first element.
7960 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7961 if (RefExpr.isInvalid())
7962 return ExprError();
7963 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7964 // For any other pointer, take the address (or form a pointer-to-member).
7965 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7966 if (RefExpr.isInvalid())
7967 return ExprError();
7968 } else if (ParamType->isRecordType()) {
7969 assert(isa<TemplateParamObjectDecl>(VD) &&
7970 "arg for class template param not a template parameter object");
7971 // No conversions apply in this case.
7972 return RefExpr;
7973 } else {
7974 assert(ParamType->isReferenceType() &&
7975 "unexpected type for decl template argument");
7976 if (NonTypeTemplateParmDecl *NTTP =
7977 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7978 QualType TemplateParamType = NTTP->getType();
7979 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7980 if (AT && AT->isDecltypeAuto()) {
7981 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7982 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7983 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7984 /*PackIndex=*/std::nullopt,
7985 /*RefParam=*/true, /*Final=*/true);
7986 }
7987 }
7988 }
7989
7990 // At this point we should have the right value category.
7991 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7992 "value kind mismatch for non-type template argument");
7993
7994 // The type of the template parameter can differ from the type of the
7995 // argument in various ways; convert it now if necessary.
7996 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7997 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
7998 CastKind CK;
7999 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
8000 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
8001 CK = CK_NoOp;
8002 } else if (ParamType->isVoidPointerType() &&
8003 RefExpr.get()->getType()->isPointerType()) {
8004 CK = CK_BitCast;
8005 } else {
8006 // FIXME: Pointers to members can need conversion derived-to-base or
8007 // base-to-derived conversions. We currently don't retain enough
8008 // information to convert properly (we need to track a cast path or
8009 // subobject number in the template argument).
8010 llvm_unreachable(
8011 "unexpected conversion required for non-type template argument");
8012 }
8013 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8014 VK: RefExpr.get()->getValueKind());
8015 }
8016
8017 return RefExpr;
8018}
8019
8020/// Construct a new expression that refers to the given
8021/// integral template argument with the given source-location
8022/// information.
8023///
8024/// This routine takes care of the mapping from an integral template
8025/// argument (which may have any integral type) to the appropriate
8026/// literal value.
8027static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8028 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8029 assert(OrigT->isIntegralOrEnumerationType());
8030
8031 // If this is an enum type that we're instantiating, we need to use an integer
8032 // type the same size as the enumerator. We don't want to build an
8033 // IntegerLiteral with enum type. The integer type of an enum type can be of
8034 // any integral type with C++11 enum classes, make sure we create the right
8035 // type of literal for it.
8036 QualType T = OrigT;
8037 if (const auto *ED = OrigT->getAsEnumDecl())
8038 T = ED->getIntegerType();
8039
8040 Expr *E;
8041 if (T->isAnyCharacterType()) {
8042 CharacterLiteralKind Kind;
8043 if (T->isWideCharType())
8044 Kind = CharacterLiteralKind::Wide;
8045 else if (T->isChar8Type() && S.getLangOpts().Char8)
8046 Kind = CharacterLiteralKind::UTF8;
8047 else if (T->isChar16Type())
8048 Kind = CharacterLiteralKind::UTF16;
8049 else if (T->isChar32Type())
8050 Kind = CharacterLiteralKind::UTF32;
8051 else
8052 Kind = CharacterLiteralKind::Ascii;
8053
8054 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8055 } else if (T->isBooleanType()) {
8056 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8057 } else {
8058 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8059 }
8060
8061 if (OrigT->isEnumeralType()) {
8062 // FIXME: This is a hack. We need a better way to handle substituted
8063 // non-type template parameters.
8064 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8065 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8066 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8067 L: Loc, R: Loc);
8068 }
8069
8070 return E;
8071}
8072
8073static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8074 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8075 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8076 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8077 ILE->setType(T);
8078 return ILE;
8079 };
8080
8081 switch (Val.getKind()) {
8082 case APValue::AddrLabelDiff:
8083 // This cannot occur in a template argument at all.
8084 case APValue::Array:
8085 case APValue::Struct:
8086 case APValue::Union:
8087 // These can only occur within a template parameter object, which is
8088 // represented as a TemplateArgument::Declaration.
8089 llvm_unreachable("unexpected template argument value");
8090
8091 case APValue::Int:
8092 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8093 Loc);
8094
8095 case APValue::Float:
8096 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8097 Type: T, L: Loc);
8098
8099 case APValue::FixedPoint:
8100 return FixedPointLiteral::CreateFromRawInt(
8101 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8102 Scale: Val.getFixedPoint().getScale());
8103
8104 case APValue::ComplexInt: {
8105 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8106 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8107 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8108 BuildExpressionFromIntegralTemplateArgumentValue(
8109 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8110 }
8111
8112 case APValue::ComplexFloat: {
8113 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8114 return MakeInitList(
8115 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8116 Type: ElemT, L: Loc),
8117 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8118 Type: ElemT, L: Loc)});
8119 }
8120
8121 case APValue::Vector: {
8122 QualType ElemT = T->castAs<VectorType>()->getElementType();
8123 llvm::SmallVector<Expr *, 8> Elts;
8124 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8125 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8126 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8127 return MakeInitList(Elts);
8128 }
8129
8130 case APValue::None:
8131 case APValue::Indeterminate:
8132 llvm_unreachable("Unexpected APValue kind.");
8133 case APValue::LValue:
8134 case APValue::MemberPointer:
8135 // There isn't necessarily a valid equivalent source-level syntax for
8136 // these; in particular, a naive lowering might violate access control.
8137 // So for now we lower to a ConstantExpr holding the value, wrapped around
8138 // an OpaqueValueExpr.
8139 // FIXME: We should have a better representation for this.
8140 ExprValueKind VK = VK_PRValue;
8141 if (T->isReferenceType()) {
8142 T = T->getPointeeType();
8143 VK = VK_LValue;
8144 }
8145 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8146 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8147 }
8148 llvm_unreachable("Unhandled APValue::ValueKind enum");
8149}
8150
8151ExprResult
8152Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8153 SourceLocation Loc) {
8154 switch (Arg.getKind()) {
8155 case TemplateArgument::Null:
8156 case TemplateArgument::Type:
8157 case TemplateArgument::Template:
8158 case TemplateArgument::TemplateExpansion:
8159 case TemplateArgument::Pack:
8160 llvm_unreachable("not a non-type template argument");
8161
8162 case TemplateArgument::Expression:
8163 return Arg.getAsExpr();
8164
8165 case TemplateArgument::NullPtr:
8166 case TemplateArgument::Declaration:
8167 return BuildExpressionFromDeclTemplateArgument(
8168 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8169
8170 case TemplateArgument::Integral:
8171 return BuildExpressionFromIntegralTemplateArgumentValue(
8172 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8173
8174 case TemplateArgument::StructuralValue:
8175 return BuildExpressionFromNonTypeTemplateArgumentValue(
8176 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8177 }
8178 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8179}
8180
8181/// Match two template parameters within template parameter lists.
8182static bool MatchTemplateParameterKind(
8183 Sema &S, NamedDecl *New,
8184 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8185 const NamedDecl *OldInstFrom, bool Complain,
8186 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8187 // Check the actual kind (type, non-type, template).
8188 if (Old->getKind() != New->getKind()) {
8189 if (Complain) {
8190 unsigned NextDiag = diag::err_template_param_different_kind;
8191 if (TemplateArgLoc.isValid()) {
8192 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8193 NextDiag = diag::note_template_param_different_kind;
8194 }
8195 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8196 << (Kind != Sema::TPL_TemplateMatch);
8197 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8198 << (Kind != Sema::TPL_TemplateMatch);
8199 }
8200
8201 return false;
8202 }
8203
8204 // Check that both are parameter packs or neither are parameter packs.
8205 // However, if we are matching a template template argument to a
8206 // template template parameter, the template template parameter can have
8207 // a parameter pack where the template template argument does not.
8208 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8209 if (Complain) {
8210 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8211 if (TemplateArgLoc.isValid()) {
8212 S.Diag(Loc: TemplateArgLoc,
8213 DiagID: diag::err_template_arg_template_params_mismatch);
8214 NextDiag = diag::note_template_parameter_pack_non_pack;
8215 }
8216
8217 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8218 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8219 : 2;
8220 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8221 << ParamKind << New->isParameterPack();
8222 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8223 << ParamKind << Old->isParameterPack();
8224 }
8225
8226 return false;
8227 }
8228 // For non-type template parameters, check the type of the parameter.
8229 if (NonTypeTemplateParmDecl *OldNTTP =
8230 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8231 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8232
8233 // If we are matching a template template argument to a template
8234 // template parameter and one of the non-type template parameter types
8235 // is dependent, then we must wait until template instantiation time
8236 // to actually compare the arguments.
8237 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8238 (!OldNTTP->getType()->isDependentType() &&
8239 !NewNTTP->getType()->isDependentType())) {
8240 // C++20 [temp.over.link]p6:
8241 // Two [non-type] template-parameters are equivalent [if] they have
8242 // equivalent types ignoring the use of type-constraints for
8243 // placeholder types
8244 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8245 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8246 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8247 if (Complain) {
8248 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8249 if (TemplateArgLoc.isValid()) {
8250 S.Diag(Loc: TemplateArgLoc,
8251 DiagID: diag::err_template_arg_template_params_mismatch);
8252 NextDiag = diag::note_template_nontype_parm_different_type;
8253 }
8254 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8255 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8256 S.Diag(Loc: OldNTTP->getLocation(),
8257 DiagID: diag::note_template_nontype_parm_prev_declaration)
8258 << OldNTTP->getType();
8259 }
8260 return false;
8261 }
8262 }
8263 }
8264 // For template template parameters, check the template parameter types.
8265 // The template parameter lists of template template
8266 // parameters must agree.
8267 else if (TemplateTemplateParmDecl *OldTTP =
8268 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8269 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8270 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8271 return false;
8272 if (!S.TemplateParameterListsAreEqual(
8273 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8274 Old: OldTTP->getTemplateParameters(), Complain,
8275 Kind: (Kind == Sema::TPL_TemplateMatch
8276 ? Sema::TPL_TemplateTemplateParmMatch
8277 : Kind),
8278 TemplateArgLoc))
8279 return false;
8280 }
8281
8282 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8283 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8284 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8285 const Expr *NewC = nullptr, *OldC = nullptr;
8286
8287 if (isa<TemplateTypeParmDecl>(Val: New)) {
8288 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8289 NewC = TC->getImmediatelyDeclaredConstraint();
8290 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8291 OldC = TC->getImmediatelyDeclaredConstraint();
8292 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8293 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8294 ->getPlaceholderTypeConstraint())
8295 NewC = E;
8296 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8297 ->getPlaceholderTypeConstraint())
8298 OldC = E;
8299 } else
8300 llvm_unreachable("unexpected template parameter type");
8301
8302 auto Diagnose = [&] {
8303 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8304 DiagID: diag::err_template_different_type_constraint);
8305 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8306 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8307 };
8308
8309 if (!NewC != !OldC) {
8310 if (Complain)
8311 Diagnose();
8312 return false;
8313 }
8314
8315 if (NewC) {
8316 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8317 NewConstr: NewC)) {
8318 if (Complain)
8319 Diagnose();
8320 return false;
8321 }
8322 }
8323 }
8324
8325 return true;
8326}
8327
8328/// Diagnose a known arity mismatch when comparing template argument
8329/// lists.
8330static
8331void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8332 TemplateParameterList *New,
8333 TemplateParameterList *Old,
8334 Sema::TemplateParameterListEqualKind Kind,
8335 SourceLocation TemplateArgLoc) {
8336 unsigned NextDiag = diag::err_template_param_list_different_arity;
8337 if (TemplateArgLoc.isValid()) {
8338 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8339 NextDiag = diag::note_template_param_list_different_arity;
8340 }
8341 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8342 << (New->size() > Old->size())
8343 << (Kind != Sema::TPL_TemplateMatch)
8344 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8345 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8346 << (Kind != Sema::TPL_TemplateMatch)
8347 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8348}
8349
8350bool Sema::TemplateParameterListsAreEqual(
8351 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8352 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8353 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8354 if (Old->size() != New->size()) {
8355 if (Complain)
8356 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8357 TemplateArgLoc);
8358
8359 return false;
8360 }
8361
8362 // C++0x [temp.arg.template]p3:
8363 // A template-argument matches a template template-parameter (call it P)
8364 // when each of the template parameters in the template-parameter-list of
8365 // the template-argument's corresponding class template or alias template
8366 // (call it A) matches the corresponding template parameter in the
8367 // template-parameter-list of P. [...]
8368 TemplateParameterList::iterator NewParm = New->begin();
8369 TemplateParameterList::iterator NewParmEnd = New->end();
8370 for (TemplateParameterList::iterator OldParm = Old->begin(),
8371 OldParmEnd = Old->end();
8372 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8373 if (NewParm == NewParmEnd) {
8374 if (Complain)
8375 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8376 TemplateArgLoc);
8377 return false;
8378 }
8379 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8380 OldInstFrom, Complain, Kind,
8381 TemplateArgLoc))
8382 return false;
8383 }
8384
8385 // Make sure we exhausted all of the arguments.
8386 if (NewParm != NewParmEnd) {
8387 if (Complain)
8388 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8389 TemplateArgLoc);
8390
8391 return false;
8392 }
8393
8394 if (Kind != TPL_TemplateParamsEquivalent) {
8395 const Expr *NewRC = New->getRequiresClause();
8396 const Expr *OldRC = Old->getRequiresClause();
8397
8398 auto Diagnose = [&] {
8399 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8400 DiagID: diag::err_template_different_requires_clause);
8401 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8402 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8403 };
8404
8405 if (!NewRC != !OldRC) {
8406 if (Complain)
8407 Diagnose();
8408 return false;
8409 }
8410
8411 if (NewRC) {
8412 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8413 NewConstr: NewRC)) {
8414 if (Complain)
8415 Diagnose();
8416 return false;
8417 }
8418 }
8419 }
8420
8421 return true;
8422}
8423
8424bool
8425Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8426 if (!S)
8427 return false;
8428
8429 // Find the nearest enclosing declaration scope.
8430 S = S->getDeclParent();
8431
8432 // C++ [temp.pre]p6: [P2096]
8433 // A template, explicit specialization, or partial specialization shall not
8434 // have C linkage.
8435 DeclContext *Ctx = S->getEntity();
8436 if (Ctx && Ctx->isExternCContext()) {
8437 SourceRange Range =
8438 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8439 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8440 : TemplateParams->getSourceRange();
8441 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8442 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8443 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8444 return true;
8445 }
8446 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8447
8448 // C++ [temp]p2:
8449 // A template-declaration can appear only as a namespace scope or
8450 // class scope declaration.
8451 // C++ [temp.expl.spec]p3:
8452 // An explicit specialization may be declared in any scope in which the
8453 // corresponding primary template may be defined.
8454 // C++ [temp.class.spec]p6: [P2096]
8455 // A partial specialization may be declared in any scope in which the
8456 // corresponding primary template may be defined.
8457 if (Ctx) {
8458 if (Ctx->isFileContext())
8459 return false;
8460 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8461 // C++ [temp.mem]p2:
8462 // A local class shall not have member templates.
8463 if (RD->isLocalClass())
8464 return Diag(Loc: TemplateParams->getTemplateLoc(),
8465 DiagID: diag::err_template_inside_local_class)
8466 << TemplateParams->getSourceRange();
8467 else
8468 return false;
8469 }
8470 }
8471
8472 return Diag(Loc: TemplateParams->getTemplateLoc(),
8473 DiagID: diag::err_template_outside_namespace_or_class_scope)
8474 << TemplateParams->getSourceRange();
8475}
8476
8477/// Determine what kind of template specialization the given declaration
8478/// is.
8479static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8480 if (!D)
8481 return TSK_Undeclared;
8482
8483 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8484 return Record->getTemplateSpecializationKind();
8485 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8486 return Function->getTemplateSpecializationKind();
8487 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8488 return Var->getTemplateSpecializationKind();
8489
8490 return TSK_Undeclared;
8491}
8492
8493/// Check whether a specialization is well-formed in the current
8494/// context.
8495///
8496/// This routine determines whether a template specialization can be declared
8497/// in the current context (C++ [temp.expl.spec]p2).
8498///
8499/// \param S the semantic analysis object for which this check is being
8500/// performed.
8501///
8502/// \param Specialized the entity being specialized or instantiated, which
8503/// may be a kind of template (class template, function template, etc.) or
8504/// a member of a class template (member function, static data member,
8505/// member class).
8506///
8507/// \param PrevDecl the previous declaration of this entity, if any.
8508///
8509/// \param Loc the location of the explicit specialization or instantiation of
8510/// this entity.
8511///
8512/// \param IsPartialSpecialization whether this is a partial specialization of
8513/// a class template.
8514///
8515/// \returns true if there was an error that we cannot recover from, false
8516/// otherwise.
8517static bool CheckTemplateSpecializationScope(Sema &S,
8518 NamedDecl *Specialized,
8519 NamedDecl *PrevDecl,
8520 SourceLocation Loc,
8521 bool IsPartialSpecialization) {
8522 // Keep these "kind" numbers in sync with the %select statements in the
8523 // various diagnostics emitted by this routine.
8524 int EntityKind = 0;
8525 if (isa<ClassTemplateDecl>(Val: Specialized))
8526 EntityKind = IsPartialSpecialization? 1 : 0;
8527 else if (isa<VarTemplateDecl>(Val: Specialized))
8528 EntityKind = IsPartialSpecialization ? 3 : 2;
8529 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8530 EntityKind = 4;
8531 else if (isa<CXXMethodDecl>(Val: Specialized))
8532 EntityKind = 5;
8533 else if (isa<VarDecl>(Val: Specialized))
8534 EntityKind = 6;
8535 else if (isa<RecordDecl>(Val: Specialized))
8536 EntityKind = 7;
8537 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8538 EntityKind = 8;
8539 else {
8540 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8541 << S.getLangOpts().CPlusPlus11;
8542 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8543 return true;
8544 }
8545
8546 // C++ [temp.expl.spec]p2:
8547 // An explicit specialization may be declared in any scope in which
8548 // the corresponding primary template may be defined.
8549 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8550 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8551 << Specialized;
8552 return true;
8553 }
8554
8555 // C++ [temp.class.spec]p6:
8556 // A class template partial specialization may be declared in any
8557 // scope in which the primary template may be defined.
8558 DeclContext *SpecializedContext =
8559 Specialized->getDeclContext()->getRedeclContext();
8560 DeclContext *DC = S.CurContext->getRedeclContext();
8561
8562 // Make sure that this redeclaration (or definition) occurs in the same
8563 // scope or an enclosing namespace.
8564 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8565 : DC->Equals(DC: SpecializedContext))) {
8566 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8567 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8568 << EntityKind << Specialized;
8569 else {
8570 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8571 int Diag = diag::err_template_spec_redecl_out_of_scope;
8572 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8573 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8574 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8575 << ND << isa<CXXRecordDecl>(Val: ND);
8576 }
8577
8578 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8579
8580 // Don't allow specializing in the wrong class during error recovery.
8581 // Otherwise, things can go horribly wrong.
8582 if (DC->isRecord())
8583 return true;
8584 }
8585
8586 return false;
8587}
8588
8589static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8590 if (!E->isTypeDependent())
8591 return SourceLocation();
8592 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8593 Checker.TraverseStmt(S: E);
8594 if (Checker.MatchLoc.isInvalid())
8595 return E->getSourceRange();
8596 return Checker.MatchLoc;
8597}
8598
8599static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8600 if (!TL.getType()->isDependentType())
8601 return SourceLocation();
8602 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8603 Checker.TraverseTypeLoc(TL);
8604 if (Checker.MatchLoc.isInvalid())
8605 return TL.getSourceRange();
8606 return Checker.MatchLoc;
8607}
8608
8609/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8610/// that checks non-type template partial specialization arguments.
8611static bool CheckNonTypeTemplatePartialSpecializationArgs(
8612 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8613 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8614 bool HasError = false;
8615 for (unsigned I = 0; I != NumArgs; ++I) {
8616 if (Args[I].getKind() == TemplateArgument::Pack) {
8617 if (CheckNonTypeTemplatePartialSpecializationArgs(
8618 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8619 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8620 return true;
8621
8622 continue;
8623 }
8624
8625 if (Args[I].getKind() != TemplateArgument::Expression)
8626 continue;
8627
8628 Expr *ArgExpr = Args[I].getAsExpr();
8629 if (ArgExpr->containsErrors()) {
8630 HasError = true;
8631 continue;
8632 }
8633
8634 // We can have a pack expansion of any of the bullets below.
8635 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8636 ArgExpr = Expansion->getPattern();
8637
8638 // Strip off any implicit casts we added as part of type checking.
8639 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8640 ArgExpr = ICE->getSubExpr();
8641
8642 // C++ [temp.class.spec]p8:
8643 // A non-type argument is non-specialized if it is the name of a
8644 // non-type parameter. All other non-type arguments are
8645 // specialized.
8646 //
8647 // Below, we check the two conditions that only apply to
8648 // specialized non-type arguments, so skip any non-specialized
8649 // arguments.
8650 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8651 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8652 continue;
8653
8654 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8655 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8656 continue;
8657 }
8658
8659 // C++ [temp.class.spec]p9:
8660 // Within the argument list of a class template partial
8661 // specialization, the following restrictions apply:
8662 // -- A partially specialized non-type argument expression
8663 // shall not involve a template parameter of the partial
8664 // specialization except when the argument expression is a
8665 // simple identifier.
8666 // -- The type of a template parameter corresponding to a
8667 // specialized non-type argument shall not be dependent on a
8668 // parameter of the specialization.
8669 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8670 // We implement a compromise between the original rules and DR1315:
8671 // -- A specialized non-type template argument shall not be
8672 // type-dependent and the corresponding template parameter
8673 // shall have a non-dependent type.
8674 SourceRange ParamUseRange =
8675 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8676 if (ParamUseRange.isValid()) {
8677 if (IsDefaultArgument) {
8678 S.Diag(Loc: TemplateNameLoc,
8679 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8680 S.Diag(Loc: ParamUseRange.getBegin(),
8681 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8682 << ParamUseRange;
8683 } else {
8684 S.Diag(Loc: ParamUseRange.getBegin(),
8685 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8686 << ParamUseRange;
8687 }
8688 return true;
8689 }
8690
8691 ParamUseRange = findTemplateParameter(
8692 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8693 if (ParamUseRange.isValid()) {
8694 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8695 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8696 << Param->getType();
8697 S.NoteTemplateParameterLocation(Decl: *Param);
8698 return true;
8699 }
8700 }
8701
8702 return HasError;
8703}
8704
8705bool Sema::CheckTemplatePartialSpecializationArgs(
8706 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8707 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8708 // We have to be conservative when checking a template in a dependent
8709 // context.
8710 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8711 return false;
8712
8713 TemplateParameterList *TemplateParams =
8714 PrimaryTemplate->getTemplateParameters();
8715 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8716 NonTypeTemplateParmDecl *Param
8717 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8718 if (!Param)
8719 continue;
8720
8721 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8722 Param, Args: &TemplateArgs[I],
8723 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8724 return true;
8725 }
8726
8727 return false;
8728}
8729
8730DeclResult Sema::ActOnClassTemplateSpecialization(
8731 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8732 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8733 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8734 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8735 assert(TUK != TagUseKind::Reference && "References are not specializations");
8736
8737 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8738 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8739 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8740
8741 // Find the class template we're specializing
8742 TemplateName Name = TemplateId.Template.get();
8743 ClassTemplateDecl *ClassTemplate
8744 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8745
8746 if (!ClassTemplate) {
8747 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8748 << (Name.getAsTemplateDecl() &&
8749 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8750 return true;
8751 }
8752
8753 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8754 auto Message = DSA->getMessage();
8755 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8756 << ClassTemplate << !Message.empty() << Message;
8757 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8758 }
8759
8760 if (S->isTemplateParamScope())
8761 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8762
8763 DeclContext *DC = ClassTemplate->getDeclContext();
8764
8765 bool isMemberSpecialization = false;
8766 bool isPartialSpecialization = false;
8767
8768 if (SS.isSet()) {
8769 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8770 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8771 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8772 /*IsMemberSpecialization=*/false))
8773 return true;
8774 }
8775
8776 // Check the validity of the template headers that introduce this
8777 // template.
8778 // FIXME: We probably shouldn't complain about these headers for
8779 // friend declarations.
8780 bool Invalid = false;
8781 TemplateParameterList *TemplateParams =
8782 MatchTemplateParametersToScopeSpecifier(
8783 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8784 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8785 if (Invalid)
8786 return true;
8787
8788 // Check that we can declare a template specialization here.
8789 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8790 return true;
8791
8792 if (TemplateParams && DC->isDependentContext()) {
8793 ContextRAII SavedContext(*this, DC);
8794 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8795 return true;
8796 }
8797
8798 if (TemplateParams && TemplateParams->size() > 0) {
8799 isPartialSpecialization = true;
8800
8801 if (TUK == TagUseKind::Friend) {
8802 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8803 << SourceRange(LAngleLoc, RAngleLoc);
8804 return true;
8805 }
8806
8807 // C++ [temp.class.spec]p10:
8808 // The template parameter list of a specialization shall not
8809 // contain default template argument values.
8810 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8811 Decl *Param = TemplateParams->getParam(Idx: I);
8812 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8813 if (TTP->hasDefaultArgument()) {
8814 Diag(Loc: TTP->getDefaultArgumentLoc(),
8815 DiagID: diag::err_default_arg_in_partial_spec);
8816 TTP->removeDefaultArgument();
8817 }
8818 } else if (NonTypeTemplateParmDecl *NTTP
8819 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8820 if (NTTP->hasDefaultArgument()) {
8821 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8822 DiagID: diag::err_default_arg_in_partial_spec)
8823 << NTTP->getDefaultArgument().getSourceRange();
8824 NTTP->removeDefaultArgument();
8825 }
8826 } else {
8827 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8828 if (TTP->hasDefaultArgument()) {
8829 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8830 DiagID: diag::err_default_arg_in_partial_spec)
8831 << TTP->getDefaultArgument().getSourceRange();
8832 TTP->removeDefaultArgument();
8833 }
8834 }
8835 }
8836 } else if (TemplateParams) {
8837 if (TUK == TagUseKind::Friend)
8838 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8839 << FixItHint::CreateRemoval(
8840 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8841 TemplateParams->getRAngleLoc()))
8842 << SourceRange(LAngleLoc, RAngleLoc);
8843 } else {
8844 assert(TUK == TagUseKind::Friend &&
8845 "should have a 'template<>' for this decl");
8846 }
8847
8848 // Check that the specialization uses the same tag kind as the
8849 // original template.
8850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8851 assert(Kind != TagTypeKind::Enum &&
8852 "Invalid enum tag in class template spec!");
8853 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8854 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8855 Name: ClassTemplate->getIdentifier())) {
8856 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8857 << ClassTemplate
8858 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8859 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8860 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8861 DiagID: diag::note_previous_use);
8862 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8863 }
8864
8865 // Translate the parser's template argument list in our AST format.
8866 TemplateArgumentListInfo TemplateArgs =
8867 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8868
8869 // Check for unexpanded parameter packs in any of the template arguments.
8870 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8871 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8872 UPPC: isPartialSpecialization
8873 ? UPPC_PartialSpecialization
8874 : UPPC_ExplicitSpecialization))
8875 return true;
8876
8877 // Check that the template argument list is well-formed for this
8878 // template.
8879 CheckTemplateArgumentInfo CTAI;
8880 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8881 /*DefaultArgs=*/{},
8882 /*PartialTemplateArgs=*/false, CTAI,
8883 /*UpdateArgsWithConversions=*/true))
8884 return true;
8885
8886 // Find the class template (partial) specialization declaration that
8887 // corresponds to these arguments.
8888 if (isPartialSpecialization) {
8889 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8890 NumExplicit: TemplateArgs.size(),
8891 TemplateArgs: CTAI.CanonicalConverted))
8892 return true;
8893
8894 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8895 // also do it during instantiation.
8896 if (!Name.isDependent() &&
8897 !TemplateSpecializationType::anyDependentTemplateArguments(
8898 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8899 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8900 << ClassTemplate->getDeclName();
8901 isPartialSpecialization = false;
8902 Invalid = true;
8903 }
8904 }
8905
8906 void *InsertPos = nullptr;
8907 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8908
8909 if (isPartialSpecialization)
8910 PrevDecl = ClassTemplate->findPartialSpecialization(
8911 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8912 else
8913 PrevDecl =
8914 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8915
8916 ClassTemplateSpecializationDecl *Specialization = nullptr;
8917
8918 // Check whether we can declare a class template specialization in
8919 // the current scope.
8920 if (TUK != TagUseKind::Friend &&
8921 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8922 Loc: TemplateNameLoc,
8923 IsPartialSpecialization: isPartialSpecialization))
8924 return true;
8925
8926 if (!isPartialSpecialization) {
8927 // Create a new class template specialization declaration node for
8928 // this explicit specialization or friend declaration.
8929 Specialization = ClassTemplateSpecializationDecl::Create(
8930 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8931 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8932 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8933 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8934 if (TemplateParameterLists.size() > 0) {
8935 Specialization->setTemplateParameterListsInfo(Context,
8936 TPLists: TemplateParameterLists);
8937 }
8938
8939 if (!PrevDecl)
8940 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8941 } else {
8942 CanQualType CanonType = CanQualType::CreateUnsafe(
8943 Other: Context.getCanonicalTemplateSpecializationType(
8944 Keyword: ElaboratedTypeKeyword::None,
8945 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8946 CanonicalArgs: CTAI.CanonicalConverted));
8947 if (Context.hasSameType(
8948 T1: CanonType,
8949 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8950 (!Context.getLangOpts().CPlusPlus20 ||
8951 !TemplateParams->hasAssociatedConstraints())) {
8952 // C++ [temp.class.spec]p9b3:
8953 //
8954 // -- The argument list of the specialization shall not be identical
8955 // to the implicit argument list of the primary template.
8956 //
8957 // This rule has since been removed, because it's redundant given DR1495,
8958 // but we keep it because it produces better diagnostics and recovery.
8959 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8960 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8961 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8962 return CheckClassTemplate(
8963 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8964 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8965 /*ModulePrivateLoc=*/SourceLocation(),
8966 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8967 OuterTemplateParamLists: TemplateParameterLists.data());
8968 }
8969
8970 // Create a new class template partial specialization declaration node.
8971 ClassTemplatePartialSpecializationDecl *PrevPartial =
8972 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8973 ClassTemplatePartialSpecializationDecl *Partial =
8974 ClassTemplatePartialSpecializationDecl::Create(
8975 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8976 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
8977 Partial->setTemplateArgsAsWritten(TemplateArgs);
8978 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
8979 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8980 Partial->setTemplateParameterListsInfo(
8981 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
8982 }
8983
8984 if (!PrevPartial)
8985 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
8986 Specialization = Partial;
8987
8988 // If we are providing an explicit specialization of a member class
8989 // template specialization, make a note of that.
8990 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8991 PrevPartial->setMemberSpecialization();
8992
8993 CheckTemplatePartialSpecialization(Partial);
8994 }
8995
8996 // C++ [temp.expl.spec]p6:
8997 // If a template, a member template or the member of a class template is
8998 // explicitly specialized then that specialization shall be declared
8999 // before the first use of that specialization that would cause an implicit
9000 // instantiation to take place, in every translation unit in which such a
9001 // use occurs; no diagnostic is required.
9002 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9003 bool Okay = false;
9004 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9005 // Is there any previous explicit specialization declaration?
9006 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9007 Okay = true;
9008 break;
9009 }
9010 }
9011
9012 if (!Okay) {
9013 SourceRange Range(TemplateNameLoc, RAngleLoc);
9014 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9015 << Context.getCanonicalTagType(TD: Specialization) << Range;
9016
9017 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9018 DiagID: diag::note_instantiation_required_here)
9019 << (PrevDecl->getTemplateSpecializationKind()
9020 != TSK_ImplicitInstantiation);
9021 return true;
9022 }
9023 }
9024
9025 // If this is not a friend, note that this is an explicit specialization.
9026 if (TUK != TagUseKind::Friend)
9027 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9028
9029 // Check that this isn't a redefinition of this specialization.
9030 if (TUK == TagUseKind::Definition) {
9031 RecordDecl *Def = Specialization->getDefinition();
9032 NamedDecl *Hidden = nullptr;
9033 bool HiddenDefVisible = false;
9034 if (Def && SkipBody &&
9035 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9036 SkipBody->ShouldSkip = true;
9037 SkipBody->Previous = Def;
9038 if (!HiddenDefVisible && Hidden)
9039 makeMergedDefinitionVisible(ND: Hidden);
9040 } else if (Def) {
9041 SourceRange Range(TemplateNameLoc, RAngleLoc);
9042 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9043 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9044 Specialization->setInvalidDecl();
9045 return true;
9046 }
9047 }
9048
9049 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9050 ProcessAPINotes(D: Specialization);
9051
9052 // Add alignment attributes if necessary; these attributes are checked when
9053 // the ASTContext lays out the structure.
9054 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9055 if (LangOpts.HLSL)
9056 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9057 AddAlignmentAttributesForRecord(RD: Specialization);
9058 AddMsStructLayoutForRecord(RD: Specialization);
9059 }
9060
9061 if (ModulePrivateLoc.isValid())
9062 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9063 << (isPartialSpecialization? 1 : 0)
9064 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9065
9066 // C++ [temp.expl.spec]p9:
9067 // A template explicit specialization is in the scope of the
9068 // namespace in which the template was defined.
9069 //
9070 // We actually implement this paragraph where we set the semantic
9071 // context (in the creation of the ClassTemplateSpecializationDecl),
9072 // but we also maintain the lexical context where the actual
9073 // definition occurs.
9074 Specialization->setLexicalDeclContext(CurContext);
9075
9076 // We may be starting the definition of this specialization.
9077 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9078 Specialization->startDefinition();
9079
9080 if (TUK == TagUseKind::Friend) {
9081 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9082 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9083 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9084 QualifierLoc: SS.getWithLocInContext(Context),
9085 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9086 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9087
9088 // Build the fully-sugared type for this class template
9089 // specialization as the user wrote in the specialization
9090 // itself. This means that we'll pretty-print the type retrieved
9091 // from the specialization's declaration the way that the user
9092 // actually wrote the specialization, rather than formatting the
9093 // name based on the "canonical" representation used to store the
9094 // template arguments in the specialization.
9095 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9096 L: TemplateNameLoc,
9097 Friend_: WrittenTy,
9098 /*FIXME:*/FriendL: KWLoc);
9099 Friend->setAccess(AS_public);
9100 CurContext->addDecl(D: Friend);
9101 } else {
9102 // Add the specialization into its lexical context, so that it can
9103 // be seen when iterating through the list of declarations in that
9104 // context. However, specializations are not found by name lookup.
9105 CurContext->addDecl(D: Specialization);
9106 }
9107
9108 if (SkipBody && SkipBody->ShouldSkip)
9109 return SkipBody->Previous;
9110
9111 Specialization->setInvalidDecl(Invalid);
9112 inferGslOwnerPointerAttribute(Record: Specialization);
9113 return Specialization;
9114}
9115
9116Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9117 MultiTemplateParamsArg TemplateParameterLists,
9118 Declarator &D) {
9119 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9120 ActOnDocumentableDecl(D: NewDecl);
9121 return NewDecl;
9122}
9123
9124ConceptDecl *Sema::ActOnStartConceptDefinition(
9125 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9126 const IdentifierInfo *Name, SourceLocation NameLoc) {
9127 DeclContext *DC = CurContext;
9128
9129 if (!DC->getRedeclContext()->isFileContext()) {
9130 Diag(Loc: NameLoc,
9131 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9132 return nullptr;
9133 }
9134
9135 if (TemplateParameterLists.size() > 1) {
9136 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9137 return nullptr;
9138 }
9139
9140 TemplateParameterList *Params = TemplateParameterLists.front();
9141
9142 if (Params->size() == 0) {
9143 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9144 return nullptr;
9145 }
9146
9147 // Ensure that the parameter pack, if present, is the last parameter in the
9148 // template.
9149 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9150 ParamEnd = Params->end();
9151 ParamIt != ParamEnd; ++ParamIt) {
9152 Decl const *Param = *ParamIt;
9153 if (Param->isParameterPack()) {
9154 if (++ParamIt == ParamEnd)
9155 break;
9156 Diag(Loc: Param->getLocation(),
9157 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9158 return nullptr;
9159 }
9160 }
9161
9162 ConceptDecl *NewDecl =
9163 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9164
9165 if (NewDecl->hasAssociatedConstraints()) {
9166 // C++2a [temp.concept]p4:
9167 // A concept shall not have associated constraints.
9168 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9169 NewDecl->setInvalidDecl();
9170 }
9171
9172 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9173 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9174 forRedeclarationInCurContext());
9175 LookupName(R&: Previous, S);
9176 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9177 /*AllowInlineNamespace*/ false);
9178
9179 // We cannot properly handle redeclarations until we parse the constraint
9180 // expression, so only inject the name if we are sure we are not redeclaring a
9181 // symbol
9182 if (Previous.empty())
9183 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9184
9185 return NewDecl;
9186}
9187
9188static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9189 bool Found = false;
9190 LookupResult::Filter F = R.makeFilter();
9191 while (F.hasNext()) {
9192 NamedDecl *D = F.next();
9193 if (D == C) {
9194 F.erase();
9195 Found = true;
9196 break;
9197 }
9198 }
9199 F.done();
9200 return Found;
9201}
9202
9203ConceptDecl *
9204Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9205 Expr *ConstraintExpr,
9206 const ParsedAttributesView &Attrs) {
9207 assert(!C->hasDefinition() && "Concept already defined");
9208 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9209 C->setInvalidDecl();
9210 return nullptr;
9211 }
9212 C->setDefinition(ConstraintExpr);
9213 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9214
9215 // Check for conflicting previous declaration.
9216 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9217 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9218 forRedeclarationInCurContext());
9219 LookupName(R&: Previous, S);
9220 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9221 /*AllowInlineNamespace*/ false);
9222 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9223 bool AddToScope = true;
9224 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9225
9226 ActOnDocumentableDecl(D: C);
9227 if (!WasAlreadyAdded && AddToScope)
9228 PushOnScopeChains(D: C, S);
9229
9230 return C;
9231}
9232
9233void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9234 LookupResult &Previous, bool &AddToScope) {
9235 AddToScope = true;
9236
9237 if (Previous.empty())
9238 return;
9239
9240 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9241 if (!OldConcept) {
9242 auto *Old = Previous.getRepresentativeDecl();
9243 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9244 << NewDecl->getDeclName();
9245 notePreviousDefinition(Old, New: NewDecl->getLocation());
9246 AddToScope = false;
9247 return;
9248 }
9249 // Check if we can merge with a concept declaration.
9250 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9251 if (!IsSame) {
9252 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9253 << NewDecl->getDeclName();
9254 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9255 AddToScope = false;
9256 return;
9257 }
9258 if (hasReachableDefinition(D: OldConcept) &&
9259 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9260 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9261 << NewDecl->getDeclName();
9262 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9263 AddToScope = false;
9264 return;
9265 }
9266 if (!Previous.isSingleResult()) {
9267 // FIXME: we should produce an error in case of ambig and failed lookups.
9268 // Other decls (e.g. namespaces) also have this shortcoming.
9269 return;
9270 }
9271 // We unwrap canonical decl late to check for module visibility.
9272 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9273}
9274
9275bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9276 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9277 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9278 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9279 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9280 return true;
9281 }
9282 // Concept template parameters don't have a definition and can't
9283 // be defined recursively.
9284 return false;
9285}
9286
9287/// \brief Strips various properties off an implicit instantiation
9288/// that has just been explicitly specialized.
9289static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9290 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9291 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9292 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9293
9294 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9295 FD->setInlineSpecified(false);
9296}
9297
9298/// Compute the diagnostic location for an explicit instantiation
9299// declaration or definition.
9300static SourceLocation DiagLocForExplicitInstantiation(
9301 NamedDecl* D, SourceLocation PointOfInstantiation) {
9302 // Explicit instantiations following a specialization have no effect and
9303 // hence no PointOfInstantiation. In that case, walk decl backwards
9304 // until a valid name loc is found.
9305 SourceLocation PrevDiagLoc = PointOfInstantiation;
9306 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9307 Prev = Prev->getPreviousDecl()) {
9308 PrevDiagLoc = Prev->getLocation();
9309 }
9310 assert(PrevDiagLoc.isValid() &&
9311 "Explicit instantiation without point of instantiation?");
9312 return PrevDiagLoc;
9313}
9314
9315bool
9316Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9317 TemplateSpecializationKind NewTSK,
9318 NamedDecl *PrevDecl,
9319 TemplateSpecializationKind PrevTSK,
9320 SourceLocation PrevPointOfInstantiation,
9321 bool &HasNoEffect) {
9322 HasNoEffect = false;
9323
9324 switch (NewTSK) {
9325 case TSK_Undeclared:
9326 case TSK_ImplicitInstantiation:
9327 assert(
9328 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9329 "previous declaration must be implicit!");
9330 return false;
9331
9332 case TSK_ExplicitSpecialization:
9333 switch (PrevTSK) {
9334 case TSK_Undeclared:
9335 case TSK_ExplicitSpecialization:
9336 // Okay, we're just specializing something that is either already
9337 // explicitly specialized or has merely been mentioned without any
9338 // instantiation.
9339 return false;
9340
9341 case TSK_ImplicitInstantiation:
9342 if (PrevPointOfInstantiation.isInvalid()) {
9343 // The declaration itself has not actually been instantiated, so it is
9344 // still okay to specialize it.
9345 StripImplicitInstantiation(
9346 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9347 return false;
9348 }
9349 // Fall through
9350 [[fallthrough]];
9351
9352 case TSK_ExplicitInstantiationDeclaration:
9353 case TSK_ExplicitInstantiationDefinition:
9354 assert((PrevTSK == TSK_ImplicitInstantiation ||
9355 PrevPointOfInstantiation.isValid()) &&
9356 "Explicit instantiation without point of instantiation?");
9357
9358 // C++ [temp.expl.spec]p6:
9359 // If a template, a member template or the member of a class template
9360 // is explicitly specialized then that specialization shall be declared
9361 // before the first use of that specialization that would cause an
9362 // implicit instantiation to take place, in every translation unit in
9363 // which such a use occurs; no diagnostic is required.
9364 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9365 // Is there any previous explicit specialization declaration?
9366 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9367 return false;
9368 }
9369
9370 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9371 << PrevDecl;
9372 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9373 << (PrevTSK != TSK_ImplicitInstantiation);
9374
9375 return true;
9376 }
9377 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9378
9379 case TSK_ExplicitInstantiationDeclaration:
9380 switch (PrevTSK) {
9381 case TSK_ExplicitInstantiationDeclaration:
9382 // This explicit instantiation declaration is redundant (that's okay).
9383 HasNoEffect = true;
9384 return false;
9385
9386 case TSK_Undeclared:
9387 case TSK_ImplicitInstantiation:
9388 // We're explicitly instantiating something that may have already been
9389 // implicitly instantiated; that's fine.
9390 return false;
9391
9392 case TSK_ExplicitSpecialization:
9393 // C++0x [temp.explicit]p4:
9394 // For a given set of template parameters, if an explicit instantiation
9395 // of a template appears after a declaration of an explicit
9396 // specialization for that template, the explicit instantiation has no
9397 // effect.
9398 HasNoEffect = true;
9399 return false;
9400
9401 case TSK_ExplicitInstantiationDefinition:
9402 // C++0x [temp.explicit]p10:
9403 // If an entity is the subject of both an explicit instantiation
9404 // declaration and an explicit instantiation definition in the same
9405 // translation unit, the definition shall follow the declaration.
9406 Diag(Loc: NewLoc,
9407 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9408
9409 // Explicit instantiations following a specialization have no effect and
9410 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9411 // until a valid name loc is found.
9412 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9413 DiagID: diag::note_explicit_instantiation_definition_here);
9414 HasNoEffect = true;
9415 return false;
9416 }
9417 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9418
9419 case TSK_ExplicitInstantiationDefinition:
9420 switch (PrevTSK) {
9421 case TSK_Undeclared:
9422 case TSK_ImplicitInstantiation:
9423 // We're explicitly instantiating something that may have already been
9424 // implicitly instantiated; that's fine.
9425 return false;
9426
9427 case TSK_ExplicitSpecialization:
9428 // C++ DR 259, C++0x [temp.explicit]p4:
9429 // For a given set of template parameters, if an explicit
9430 // instantiation of a template appears after a declaration of
9431 // an explicit specialization for that template, the explicit
9432 // instantiation has no effect.
9433 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9434 << PrevDecl;
9435 Diag(Loc: PrevDecl->getLocation(),
9436 DiagID: diag::note_previous_template_specialization);
9437 HasNoEffect = true;
9438 return false;
9439
9440 case TSK_ExplicitInstantiationDeclaration:
9441 // We're explicitly instantiating a definition for something for which we
9442 // were previously asked to suppress instantiations. That's fine.
9443
9444 // C++0x [temp.explicit]p4:
9445 // For a given set of template parameters, if an explicit instantiation
9446 // of a template appears after a declaration of an explicit
9447 // specialization for that template, the explicit instantiation has no
9448 // effect.
9449 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9450 // Is there any previous explicit specialization declaration?
9451 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9452 HasNoEffect = true;
9453 break;
9454 }
9455 }
9456
9457 return false;
9458
9459 case TSK_ExplicitInstantiationDefinition:
9460 // C++0x [temp.spec]p5:
9461 // For a given template and a given set of template-arguments,
9462 // - an explicit instantiation definition shall appear at most once
9463 // in a program,
9464
9465 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9466 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9467 ? diag::ext_explicit_instantiation_duplicate
9468 : diag::err_explicit_instantiation_duplicate)
9469 << PrevDecl;
9470 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9471 DiagID: diag::note_previous_explicit_instantiation);
9472 HasNoEffect = true;
9473 return false;
9474 }
9475 }
9476
9477 llvm_unreachable("Missing specialization/instantiation case?");
9478}
9479
9480bool Sema::CheckDependentFunctionTemplateSpecialization(
9481 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9482 LookupResult &Previous) {
9483 // Remove anything from Previous that isn't a function template in
9484 // the correct context.
9485 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9486 LookupResult::Filter F = Previous.makeFilter();
9487 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9488 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9489 while (F.hasNext()) {
9490 NamedDecl *D = F.next()->getUnderlyingDecl();
9491 if (!isa<FunctionTemplateDecl>(Val: D)) {
9492 F.erase();
9493 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9494 continue;
9495 }
9496
9497 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9498 NS: D->getDeclContext()->getRedeclContext())) {
9499 F.erase();
9500 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9501 continue;
9502 }
9503 }
9504 F.done();
9505
9506 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9507 if (Previous.empty()) {
9508 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9509 << IsFriend;
9510 for (auto &P : DiscardedCandidates)
9511 Diag(Loc: P.second->getLocation(),
9512 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9513 << P.first << IsFriend;
9514 return true;
9515 }
9516
9517 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9518 TemplateArgs: ExplicitTemplateArgs);
9519 return false;
9520}
9521
9522bool Sema::CheckFunctionTemplateSpecialization(
9523 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9524 LookupResult &Previous, bool QualifiedFriend) {
9525 // The set of function template specializations that could match this
9526 // explicit function template specialization.
9527 UnresolvedSet<8> Candidates;
9528 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9529 /*ForTakingAddress=*/false);
9530
9531 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9532 ConvertedTemplateArgs;
9533
9534 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9535 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9536 I != E; ++I) {
9537 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9538 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9539 // Only consider templates found within the same semantic lookup scope as
9540 // FD.
9541 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9542 NS: Ovl->getDeclContext()->getRedeclContext()))
9543 continue;
9544
9545 QualType FT = FD->getType();
9546 // C++11 [dcl.constexpr]p8:
9547 // A constexpr specifier for a non-static member function that is not
9548 // a constructor declares that member function to be const.
9549 //
9550 // When matching a constexpr member function template specialization
9551 // against the primary template, we don't yet know whether the
9552 // specialization has an implicit 'const' (because we don't know whether
9553 // it will be a static member function until we know which template it
9554 // specializes). This rule was removed in C++14.
9555 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9556 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9557 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9558 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9559 if (OldMD && OldMD->isConst()) {
9560 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9561 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9562 EPI.TypeQuals.addConst();
9563 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9564 Args: FPT->getParamTypes(), EPI);
9565 }
9566 }
9567
9568 TemplateArgumentListInfo Args;
9569 if (ExplicitTemplateArgs)
9570 Args = *ExplicitTemplateArgs;
9571
9572 // C++ [temp.expl.spec]p11:
9573 // A trailing template-argument can be left unspecified in the
9574 // template-id naming an explicit function template specialization
9575 // provided it can be deduced from the function argument type.
9576 // Perform template argument deduction to determine whether we may be
9577 // specializing this template.
9578 // FIXME: It is somewhat wasteful to build
9579 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9580 FunctionDecl *Specialization = nullptr;
9581 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9582 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9583 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9584 TDK != TemplateDeductionResult::Success) {
9585 // Template argument deduction failed; record why it failed, so
9586 // that we can provide nifty diagnostics.
9587 FailedCandidates.addCandidate().set(
9588 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9589 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9590 (void)TDK;
9591 continue;
9592 }
9593
9594 // Target attributes are part of the cuda function signature, so
9595 // the deduced template's cuda target must match that of the
9596 // specialization. Given that C++ template deduction does not
9597 // take target attributes into account, we reject candidates
9598 // here that have a different target.
9599 if (LangOpts.CUDA &&
9600 CUDA().IdentifyTarget(D: Specialization,
9601 /* IgnoreImplicitHDAttr = */ true) !=
9602 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9603 FailedCandidates.addCandidate().set(
9604 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9605 Info: MakeDeductionFailureInfo(
9606 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9607 continue;
9608 }
9609
9610 // Record this candidate.
9611 if (ExplicitTemplateArgs)
9612 ConvertedTemplateArgs[Specialization] = std::move(Args);
9613 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9614 }
9615 }
9616
9617 // For a qualified friend declaration (with no explicit marker to indicate
9618 // that a template specialization was intended), note all (template and
9619 // non-template) candidates.
9620 if (QualifiedFriend && Candidates.empty()) {
9621 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9622 << FD->getDeclName() << FDLookupContext;
9623 // FIXME: We should form a single candidate list and diagnose all
9624 // candidates at once, to get proper sorting and limiting.
9625 for (auto *OldND : Previous) {
9626 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9627 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9628 }
9629 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9630 return true;
9631 }
9632
9633 // Find the most specialized function template.
9634 UnresolvedSetIterator Result = getMostSpecialized(
9635 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9636 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9637 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9638 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9639 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9640
9641 if (Result == Candidates.end())
9642 return true;
9643
9644 // Ignore access information; it doesn't figure into redeclaration checking.
9645 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9646
9647 if (const auto *PT = Specialization->getPrimaryTemplate();
9648 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9649 auto Message = DSA->getMessage();
9650 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9651 << PT << !Message.empty() << Message;
9652 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9653 }
9654
9655 // C++23 [except.spec]p13:
9656 // An exception specification is considered to be needed when:
9657 // - [...]
9658 // - the exception specification is compared to that of another declaration
9659 // (e.g., an explicit specialization or an overriding virtual function);
9660 // - [...]
9661 //
9662 // The exception specification of a defaulted function is evaluated as
9663 // described above only when needed; similarly, the noexcept-specifier of a
9664 // specialization of a function template or member function of a class
9665 // template is instantiated only when needed.
9666 //
9667 // The standard doesn't specify what the "comparison with another declaration"
9668 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9669 // not state which properties of an explicit specialization must match the
9670 // primary template.
9671 //
9672 // We assume that an explicit specialization must correspond with (per
9673 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9674 // the declaration produced by substitution into the function template.
9675 //
9676 // Since the determination whether two function declarations correspond does
9677 // not consider exception specification, we only need to instantiate it once
9678 // we determine the primary template when comparing types per
9679 // [basic.link]p11.1.
9680 auto *SpecializationFPT =
9681 Specialization->getType()->castAs<FunctionProtoType>();
9682 // If the function has a dependent exception specification, resolve it after
9683 // we have selected the primary template so we can check whether it matches.
9684 if (getLangOpts().CPlusPlus17 &&
9685 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9686 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9687 return true;
9688
9689 FunctionTemplateSpecializationInfo *SpecInfo
9690 = Specialization->getTemplateSpecializationInfo();
9691 assert(SpecInfo && "Function template specialization info missing?");
9692
9693 // Note: do not overwrite location info if previous template
9694 // specialization kind was explicit.
9695 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9696 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9697 Specialization->setLocation(FD->getLocation());
9698 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9699 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9700 // function can differ from the template declaration with respect to
9701 // the constexpr specifier.
9702 // FIXME: We need an update record for this AST mutation.
9703 // FIXME: What if there are multiple such prior declarations (for instance,
9704 // from different modules)?
9705 Specialization->setConstexprKind(FD->getConstexprKind());
9706 }
9707
9708 // FIXME: Check if the prior specialization has a point of instantiation.
9709 // If so, we have run afoul of .
9710
9711 // If this is a friend declaration, then we're not really declaring
9712 // an explicit specialization.
9713 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9714
9715 // Check the scope of this explicit specialization.
9716 if (!isFriend &&
9717 CheckTemplateSpecializationScope(S&: *this,
9718 Specialized: Specialization->getPrimaryTemplate(),
9719 PrevDecl: Specialization, Loc: FD->getLocation(),
9720 IsPartialSpecialization: false))
9721 return true;
9722
9723 // C++ [temp.expl.spec]p6:
9724 // If a template, a member template or the member of a class template is
9725 // explicitly specialized then that specialization shall be declared
9726 // before the first use of that specialization that would cause an implicit
9727 // instantiation to take place, in every translation unit in which such a
9728 // use occurs; no diagnostic is required.
9729 bool HasNoEffect = false;
9730 if (!isFriend &&
9731 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9732 NewTSK: TSK_ExplicitSpecialization,
9733 PrevDecl: Specialization,
9734 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9735 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9736 HasNoEffect))
9737 return true;
9738
9739 // Mark the prior declaration as an explicit specialization, so that later
9740 // clients know that this is an explicit specialization.
9741 // A dependent friend specialization which has a definition should be treated
9742 // as explicit specialization, despite being invalid.
9743 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9744 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9745 // Since explicit specializations do not inherit '=delete' from their
9746 // primary function template - check if the 'specialization' that was
9747 // implicitly generated (during template argument deduction for partial
9748 // ordering) from the most specialized of all the function templates that
9749 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9750 // first check that it was implicitly generated during template argument
9751 // deduction by making sure it wasn't referenced, and then reset the deleted
9752 // flag to not-deleted, so that we can inherit that information from 'FD'.
9753 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9754 !Specialization->getCanonicalDecl()->isReferenced()) {
9755 // FIXME: This assert will not hold in the presence of modules.
9756 assert(
9757 Specialization->getCanonicalDecl() == Specialization &&
9758 "This must be the only existing declaration of this specialization");
9759 // FIXME: We need an update record for this AST mutation.
9760 Specialization->setDeletedAsWritten(D: false);
9761 }
9762 // FIXME: We need an update record for this AST mutation.
9763 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9764 MarkUnusedFileScopedDecl(D: Specialization);
9765 }
9766
9767 // Turn the given function declaration into a function template
9768 // specialization, with the template arguments from the previous
9769 // specialization.
9770 // Take copies of (semantic and syntactic) template argument lists.
9771 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9772 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9773 FD->setFunctionTemplateSpecialization(
9774 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9775 TSK: SpecInfo->getTemplateSpecializationKind(),
9776 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9777
9778 // A function template specialization inherits the target attributes
9779 // of its template. (We require the attributes explicitly in the
9780 // code to match, but a template may have implicit attributes by
9781 // virtue e.g. of being constexpr, and it passes these implicit
9782 // attributes on to its specializations.)
9783 if (LangOpts.CUDA)
9784 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9785
9786 // The "previous declaration" for this function template specialization is
9787 // the prior function template specialization.
9788 Previous.clear();
9789 Previous.addDecl(D: Specialization);
9790 return false;
9791}
9792
9793bool
9794Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9795 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9796 "Only for non-template members");
9797
9798 // Try to find the member we are instantiating.
9799 NamedDecl *FoundInstantiation = nullptr;
9800 NamedDecl *Instantiation = nullptr;
9801 NamedDecl *InstantiatedFrom = nullptr;
9802 MemberSpecializationInfo *MSInfo = nullptr;
9803
9804 if (Previous.empty()) {
9805 // Nowhere to look anyway.
9806 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9807 UnresolvedSet<8> Candidates;
9808 for (NamedDecl *Candidate : Previous) {
9809 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9810 // Ignore any candidates that aren't member functions.
9811 if (!Method)
9812 continue;
9813
9814 QualType Adjusted = Function->getType();
9815 if (!hasExplicitCallingConv(T: Adjusted))
9816 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9817 // Ignore any candidates with the wrong type.
9818 // This doesn't handle deduced return types, but both function
9819 // declarations should be undeduced at this point.
9820 // FIXME: The exception specification should probably be ignored when
9821 // comparing the types.
9822 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9823 continue;
9824
9825 // Ignore any candidates with unsatisfied constraints.
9826 if (ConstraintSatisfaction Satisfaction;
9827 Method->getTrailingRequiresClause() &&
9828 (CheckFunctionConstraints(FD: Method, Satisfaction,
9829 /*UsageLoc=*/Member->getLocation(),
9830 /*ForOverloadResolution=*/true) ||
9831 !Satisfaction.IsSatisfied))
9832 continue;
9833
9834 Candidates.addDecl(D: Candidate);
9835 }
9836
9837 // If we have no viable candidates left after filtering, we are done.
9838 if (Candidates.empty())
9839 return false;
9840
9841 // Find the function that is more constrained than every other function it
9842 // has been compared to.
9843 UnresolvedSetIterator Best = Candidates.begin();
9844 CXXMethodDecl *BestMethod = nullptr;
9845 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9846 I != E; ++I) {
9847 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9848 if (I == Best ||
9849 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9850 Best = I;
9851 BestMethod = Method;
9852 }
9853 }
9854
9855 FoundInstantiation = *Best;
9856 Instantiation = BestMethod;
9857 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9858 MSInfo = BestMethod->getMemberSpecializationInfo();
9859
9860 // Make sure the best candidate is more constrained than all of the others.
9861 bool Ambiguous = false;
9862 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9863 I != E; ++I) {
9864 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9865 if (I != Best &&
9866 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9867 Ambiguous = true;
9868 break;
9869 }
9870 }
9871
9872 if (Ambiguous) {
9873 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9874 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9875 for (NamedDecl *Candidate : Candidates) {
9876 Candidate = Candidate->getUnderlyingDecl();
9877 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9878 << Candidate;
9879 }
9880 return true;
9881 }
9882 } else if (isa<VarDecl>(Val: Member)) {
9883 VarDecl *PrevVar;
9884 if (Previous.isSingleResult() &&
9885 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9886 if (PrevVar->isStaticDataMember()) {
9887 FoundInstantiation = Previous.getRepresentativeDecl();
9888 Instantiation = PrevVar;
9889 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9890 MSInfo = PrevVar->getMemberSpecializationInfo();
9891 }
9892 } else if (isa<RecordDecl>(Val: Member)) {
9893 CXXRecordDecl *PrevRecord;
9894 if (Previous.isSingleResult() &&
9895 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9896 FoundInstantiation = Previous.getRepresentativeDecl();
9897 Instantiation = PrevRecord;
9898 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9899 MSInfo = PrevRecord->getMemberSpecializationInfo();
9900 }
9901 } else if (isa<EnumDecl>(Val: Member)) {
9902 EnumDecl *PrevEnum;
9903 if (Previous.isSingleResult() &&
9904 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9905 FoundInstantiation = Previous.getRepresentativeDecl();
9906 Instantiation = PrevEnum;
9907 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9908 MSInfo = PrevEnum->getMemberSpecializationInfo();
9909 }
9910 }
9911
9912 if (!Instantiation) {
9913 // There is no previous declaration that matches. Since member
9914 // specializations are always out-of-line, the caller will complain about
9915 // this mismatch later.
9916 return false;
9917 }
9918
9919 // A member specialization in a friend declaration isn't really declaring
9920 // an explicit specialization, just identifying a specific (possibly implicit)
9921 // specialization. Don't change the template specialization kind.
9922 //
9923 // FIXME: Is this really valid? Other compilers reject.
9924 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9925 // Preserve instantiation information.
9926 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9927 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9928 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9929 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9930 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9931 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9932 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9933 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9934 }
9935
9936 Previous.clear();
9937 Previous.addDecl(D: FoundInstantiation);
9938 return false;
9939 }
9940
9941 // Make sure that this is a specialization of a member.
9942 if (!InstantiatedFrom) {
9943 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
9944 << Member;
9945 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
9946 return true;
9947 }
9948
9949 // C++ [temp.expl.spec]p6:
9950 // If a template, a member template or the member of a class template is
9951 // explicitly specialized then that specialization shall be declared
9952 // before the first use of that specialization that would cause an implicit
9953 // instantiation to take place, in every translation unit in which such a
9954 // use occurs; no diagnostic is required.
9955 assert(MSInfo && "Member specialization info missing?");
9956
9957 bool HasNoEffect = false;
9958 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9959 NewTSK: TSK_ExplicitSpecialization,
9960 PrevDecl: Instantiation,
9961 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9962 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9963 HasNoEffect))
9964 return true;
9965
9966 // Check the scope of this explicit specialization.
9967 if (CheckTemplateSpecializationScope(S&: *this,
9968 Specialized: InstantiatedFrom,
9969 PrevDecl: Instantiation, Loc: Member->getLocation(),
9970 IsPartialSpecialization: false))
9971 return true;
9972
9973 // Note that this member specialization is an "instantiation of" the
9974 // corresponding member of the original template.
9975 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9976 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9977 if (InstantiationFunction->getTemplateSpecializationKind() ==
9978 TSK_ImplicitInstantiation) {
9979 // Explicit specializations of member functions of class templates do not
9980 // inherit '=delete' from the member function they are specializing.
9981 if (InstantiationFunction->isDeleted()) {
9982 // FIXME: This assert will not hold in the presence of modules.
9983 assert(InstantiationFunction->getCanonicalDecl() ==
9984 InstantiationFunction);
9985 // FIXME: We need an update record for this AST mutation.
9986 InstantiationFunction->setDeletedAsWritten(D: false);
9987 }
9988 }
9989
9990 MemberFunction->setInstantiationOfMemberFunction(
9991 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9992 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
9993 MemberVar->setInstantiationOfStaticDataMember(
9994 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9995 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
9996 MemberClass->setInstantiationOfMemberClass(
9997 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9998 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
9999 MemberEnum->setInstantiationOfMemberEnum(
10000 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10001 } else {
10002 llvm_unreachable("unknown member specialization kind");
10003 }
10004
10005 // Save the caller the trouble of having to figure out which declaration
10006 // this specialization matches.
10007 Previous.clear();
10008 Previous.addDecl(D: FoundInstantiation);
10009 return false;
10010}
10011
10012/// Complete the explicit specialization of a member of a class template by
10013/// updating the instantiated member to be marked as an explicit specialization.
10014///
10015/// \param OrigD The member declaration instantiated from the template.
10016/// \param Loc The location of the explicit specialization of the member.
10017template<typename DeclT>
10018static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10019 SourceLocation Loc) {
10020 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10021 return;
10022
10023 // FIXME: Inform AST mutation listeners of this AST mutation.
10024 // FIXME: If there are multiple in-class declarations of the member (from
10025 // multiple modules, or a declaration and later definition of a member type),
10026 // should we update all of them?
10027 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10028 OrigD->setLocation(Loc);
10029}
10030
10031void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10032 LookupResult &Previous) {
10033 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10034 if (Instantiation == Member)
10035 return;
10036
10037 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10038 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10039 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10040 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10041 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10042 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10043 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10044 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10045 else
10046 llvm_unreachable("unknown member specialization kind");
10047}
10048
10049/// Check the scope of an explicit instantiation.
10050///
10051/// \returns true if a serious error occurs, false otherwise.
10052static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10053 SourceLocation InstLoc,
10054 bool WasQualifiedName) {
10055 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10056 DeclContext *CurContext = S.CurContext->getRedeclContext();
10057
10058 if (CurContext->isRecord()) {
10059 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10060 << D;
10061 return true;
10062 }
10063
10064 // C++11 [temp.explicit]p3:
10065 // An explicit instantiation shall appear in an enclosing namespace of its
10066 // template. If the name declared in the explicit instantiation is an
10067 // unqualified name, the explicit instantiation shall appear in the
10068 // namespace where its template is declared or, if that namespace is inline
10069 // (7.3.1), any namespace from its enclosing namespace set.
10070 //
10071 // This is DR275, which we do not retroactively apply to C++98/03.
10072 if (WasQualifiedName) {
10073 if (CurContext->Encloses(DC: OrigContext))
10074 return false;
10075 } else {
10076 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10077 return false;
10078 }
10079
10080 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10081 if (WasQualifiedName)
10082 S.Diag(Loc: InstLoc,
10083 DiagID: S.getLangOpts().CPlusPlus11?
10084 diag::err_explicit_instantiation_out_of_scope :
10085 diag::warn_explicit_instantiation_out_of_scope_0x)
10086 << D << NS;
10087 else
10088 S.Diag(Loc: InstLoc,
10089 DiagID: S.getLangOpts().CPlusPlus11?
10090 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10091 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10092 << D << NS;
10093 } else
10094 S.Diag(Loc: InstLoc,
10095 DiagID: S.getLangOpts().CPlusPlus11?
10096 diag::err_explicit_instantiation_must_be_global :
10097 diag::warn_explicit_instantiation_must_be_global_0x)
10098 << D;
10099 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10100 return false;
10101}
10102
10103/// Common checks for whether an explicit instantiation of \p D is valid.
10104static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10105 SourceLocation InstLoc,
10106 bool WasQualifiedName,
10107 TemplateSpecializationKind TSK) {
10108 // C++ [temp.explicit]p13:
10109 // An explicit instantiation declaration shall not name a specialization of
10110 // a template with internal linkage.
10111 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10112 D->getFormalLinkage() == Linkage::Internal) {
10113 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10114 return true;
10115 }
10116
10117 // C++11 [temp.explicit]p3: [DR 275]
10118 // An explicit instantiation shall appear in an enclosing namespace of its
10119 // template.
10120 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10121 return true;
10122
10123 return false;
10124}
10125
10126/// Determine whether the given scope specifier has a template-id in it.
10127static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10128 // C++11 [temp.explicit]p3:
10129 // If the explicit instantiation is for a member function, a member class
10130 // or a static data member of a class template specialization, the name of
10131 // the class template specialization in the qualified-id for the member
10132 // name shall be a simple-template-id.
10133 //
10134 // C++98 has the same restriction, just worded differently.
10135 for (NestedNameSpecifier NNS = SS.getScopeRep();
10136 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10137 /**/) {
10138 const Type *T = NNS.getAsType();
10139 if (isa<TemplateSpecializationType>(Val: T))
10140 return true;
10141 NNS = T->getPrefix();
10142 }
10143 return false;
10144}
10145
10146/// Make a dllexport or dllimport attr on a class template specialization take
10147/// effect.
10148static void dllExportImportClassTemplateSpecialization(
10149 Sema &S, ClassTemplateSpecializationDecl *Def) {
10150 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10151 assert(A && "dllExportImportClassTemplateSpecialization called "
10152 "on Def without dllexport or dllimport");
10153
10154 // We reject explicit instantiations in class scope, so there should
10155 // never be any delayed exported classes to worry about.
10156 assert(S.DelayedDllExportClasses.empty() &&
10157 "delayed exports present at explicit instantiation");
10158 S.checkClassLevelDLLAttribute(Class: Def);
10159
10160 // Propagate attribute to base class templates.
10161 for (auto &B : Def->bases()) {
10162 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10163 Val: B.getType()->getAsCXXRecordDecl()))
10164 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10165 }
10166
10167 S.referenceDLLExportedClassMethods();
10168}
10169
10170DeclResult Sema::ActOnExplicitInstantiation(
10171 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10172 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10173 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10174 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10175 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10176 // Find the class template we're specializing
10177 TemplateName Name = TemplateD.get();
10178 TemplateDecl *TD = Name.getAsTemplateDecl();
10179 // Check that the specialization uses the same tag kind as the
10180 // original template.
10181 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10182 assert(Kind != TagTypeKind::Enum &&
10183 "Invalid enum tag in class template explicit instantiation!");
10184
10185 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10186
10187 if (!ClassTemplate) {
10188 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10189 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10190 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10191 return true;
10192 }
10193
10194 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10195 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10196 Name: ClassTemplate->getIdentifier())) {
10197 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10198 << ClassTemplate
10199 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10200 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10201 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10202 DiagID: diag::note_previous_use);
10203 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10204 }
10205
10206 // C++0x [temp.explicit]p2:
10207 // There are two forms of explicit instantiation: an explicit instantiation
10208 // definition and an explicit instantiation declaration. An explicit
10209 // instantiation declaration begins with the extern keyword. [...]
10210 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10211 ? TSK_ExplicitInstantiationDefinition
10212 : TSK_ExplicitInstantiationDeclaration;
10213
10214 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10215 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10216 // Check for dllexport class template instantiation declarations,
10217 // except for MinGW mode.
10218 for (const ParsedAttr &AL : Attr) {
10219 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10220 Diag(Loc: ExternLoc,
10221 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10222 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10223 break;
10224 }
10225 }
10226
10227 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10228 Diag(Loc: ExternLoc,
10229 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10230 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10231 }
10232 }
10233
10234 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10235 // instantiation declarations for most purposes.
10236 bool DLLImportExplicitInstantiationDef = false;
10237 if (TSK == TSK_ExplicitInstantiationDefinition &&
10238 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10239 // Check for dllimport class template instantiation definitions.
10240 bool DLLImport =
10241 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10242 for (const ParsedAttr &AL : Attr) {
10243 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10244 DLLImport = true;
10245 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10246 // dllexport trumps dllimport here.
10247 DLLImport = false;
10248 break;
10249 }
10250 }
10251 if (DLLImport) {
10252 TSK = TSK_ExplicitInstantiationDeclaration;
10253 DLLImportExplicitInstantiationDef = true;
10254 }
10255 }
10256
10257 // Translate the parser's template argument list in our AST format.
10258 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10259 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10260
10261 // Check that the template argument list is well-formed for this
10262 // template.
10263 CheckTemplateArgumentInfo CTAI;
10264 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10265 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10266 /*UpdateArgsWithConversions=*/true,
10267 /*ConstraintsNotSatisfied=*/nullptr))
10268 return true;
10269
10270 // Find the class template specialization declaration that
10271 // corresponds to these arguments.
10272 void *InsertPos = nullptr;
10273 ClassTemplateSpecializationDecl *PrevDecl =
10274 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10275
10276 TemplateSpecializationKind PrevDecl_TSK
10277 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10278
10279 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10280 Context.getTargetInfo().getTriple().isOSCygMing()) {
10281 // Check for dllexport class template instantiation definitions in MinGW
10282 // mode, if a previous declaration of the instantiation was seen.
10283 for (const ParsedAttr &AL : Attr) {
10284 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10285 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10286 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10287 } else {
10288 Diag(Loc: AL.getLoc(),
10289 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10290 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10291 }
10292 break;
10293 }
10294 }
10295 }
10296
10297 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10298 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10299 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10300 return AL.getKind() == ParsedAttr::AT_DLLExport;
10301 })) {
10302 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10303 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10304 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10305 }
10306 }
10307
10308 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10309 WasQualifiedName: SS.isSet(), TSK))
10310 return true;
10311
10312 ClassTemplateSpecializationDecl *Specialization = nullptr;
10313
10314 bool HasNoEffect = false;
10315 if (PrevDecl) {
10316 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10317 PrevDecl, PrevTSK: PrevDecl_TSK,
10318 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10319 HasNoEffect))
10320 return PrevDecl;
10321
10322 // Even though HasNoEffect == true means that this explicit instantiation
10323 // has no effect on semantics, we go on to put its syntax in the AST.
10324
10325 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10326 PrevDecl_TSK == TSK_Undeclared) {
10327 // Since the only prior class template specialization with these
10328 // arguments was referenced but not declared, reuse that
10329 // declaration node as our own, updating the source location
10330 // for the template name to reflect our new declaration.
10331 // (Other source locations will be updated later.)
10332 Specialization = PrevDecl;
10333 Specialization->setLocation(TemplateNameLoc);
10334 PrevDecl = nullptr;
10335 }
10336
10337 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10338 DLLImportExplicitInstantiationDef) {
10339 // The new specialization might add a dllimport attribute.
10340 HasNoEffect = false;
10341 }
10342 }
10343
10344 if (!Specialization) {
10345 // Create a new class template specialization declaration node for
10346 // this explicit specialization.
10347 Specialization = ClassTemplateSpecializationDecl::Create(
10348 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10349 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10350 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10351
10352 // A MSInheritanceAttr attached to the previous declaration must be
10353 // propagated to the new node prior to instantiation.
10354 if (PrevDecl) {
10355 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10356 auto *Clone = A->clone(C&: getASTContext());
10357 Clone->setInherited(true);
10358 Specialization->addAttr(A: Clone);
10359 Consumer.AssignInheritanceModel(RD: Specialization);
10360 }
10361 }
10362
10363 if (!HasNoEffect && !PrevDecl) {
10364 // Insert the new specialization.
10365 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10366 }
10367 }
10368
10369 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10370
10371 // Set source locations for keywords.
10372 Specialization->setExternKeywordLoc(ExternLoc);
10373 Specialization->setTemplateKeywordLoc(TemplateLoc);
10374 Specialization->setBraceRange(SourceRange());
10375
10376 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10377 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10378 ProcessAPINotes(D: Specialization);
10379
10380 // Add the explicit instantiation into its lexical context. However,
10381 // since explicit instantiations are never found by name lookup, we
10382 // just put it into the declaration context directly.
10383 Specialization->setLexicalDeclContext(CurContext);
10384 CurContext->addDecl(D: Specialization);
10385
10386 // Syntax is now OK, so return if it has no other effect on semantics.
10387 if (HasNoEffect) {
10388 // Set the template specialization kind.
10389 Specialization->setTemplateSpecializationKind(TSK);
10390 return Specialization;
10391 }
10392
10393 // C++ [temp.explicit]p3:
10394 // A definition of a class template or class member template
10395 // shall be in scope at the point of the explicit instantiation of
10396 // the class template or class member template.
10397 //
10398 // This check comes when we actually try to perform the
10399 // instantiation.
10400 ClassTemplateSpecializationDecl *Def
10401 = cast_or_null<ClassTemplateSpecializationDecl>(
10402 Val: Specialization->getDefinition());
10403 if (!Def)
10404 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10405 /*Complain=*/true,
10406 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10407 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10408 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10409 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10410 }
10411
10412 // Instantiate the members of this class template specialization.
10413 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10414 Val: Specialization->getDefinition());
10415 if (Def) {
10416 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10417 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10418 // TSK_ExplicitInstantiationDefinition
10419 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10420 (TSK == TSK_ExplicitInstantiationDefinition ||
10421 DLLImportExplicitInstantiationDef)) {
10422 // FIXME: Need to notify the ASTMutationListener that we did this.
10423 Def->setTemplateSpecializationKind(TSK);
10424
10425 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10426 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10427 // An explicit instantiation definition can add a dll attribute to a
10428 // template with a previous instantiation declaration. MinGW doesn't
10429 // allow this.
10430 auto *A = cast<InheritableAttr>(
10431 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10432 A->setInherited(true);
10433 Def->addAttr(A);
10434 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10435 }
10436 }
10437
10438 // Fix a TSK_ImplicitInstantiation followed by a
10439 // TSK_ExplicitInstantiationDefinition
10440 bool NewlyDLLExported =
10441 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10442 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10443 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10444 // An explicit instantiation definition can add a dll attribute to a
10445 // template with a previous implicit instantiation. MinGW doesn't allow
10446 // this. We limit clang to only adding dllexport, to avoid potentially
10447 // strange codegen behavior. For example, if we extend this conditional
10448 // to dllimport, and we have a source file calling a method on an
10449 // implicitly instantiated template class instance and then declaring a
10450 // dllimport explicit instantiation definition for the same template
10451 // class, the codegen for the method call will not respect the dllimport,
10452 // while it will with cl. The Def will already have the DLL attribute,
10453 // since the Def and Specialization will be the same in the case of
10454 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10455 // attribute to the Specialization; we just need to make it take effect.
10456 assert(Def == Specialization &&
10457 "Def and Specialization should match for implicit instantiation");
10458 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10459 }
10460
10461 // In MinGW mode, export the template instantiation if the declaration
10462 // was marked dllexport.
10463 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10464 Context.getTargetInfo().getTriple().isOSCygMing() &&
10465 PrevDecl->hasAttr<DLLExportAttr>()) {
10466 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10467 }
10468
10469 // Set the template specialization kind. Make sure it is set before
10470 // instantiating the members which will trigger ASTConsumer callbacks.
10471 Specialization->setTemplateSpecializationKind(TSK);
10472 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10473 } else {
10474
10475 // Set the template specialization kind.
10476 Specialization->setTemplateSpecializationKind(TSK);
10477 }
10478
10479 return Specialization;
10480}
10481
10482DeclResult
10483Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10484 SourceLocation TemplateLoc, unsigned TagSpec,
10485 SourceLocation KWLoc, CXXScopeSpec &SS,
10486 IdentifierInfo *Name, SourceLocation NameLoc,
10487 const ParsedAttributesView &Attr) {
10488
10489 bool Owned = false;
10490 bool IsDependent = false;
10491 Decl *TagD =
10492 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10493 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10494 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10495 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10496 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10497 .get();
10498 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10499
10500 if (!TagD)
10501 return true;
10502
10503 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10504 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10505
10506 if (Tag->isInvalidDecl())
10507 return true;
10508
10509 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10510 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10511 if (!Pattern) {
10512 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10513 << Context.getCanonicalTagType(TD: Record);
10514 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10515 return true;
10516 }
10517
10518 // C++0x [temp.explicit]p2:
10519 // If the explicit instantiation is for a class or member class, the
10520 // elaborated-type-specifier in the declaration shall include a
10521 // simple-template-id.
10522 //
10523 // C++98 has the same restriction, just worded differently.
10524 if (!ScopeSpecifierHasTemplateId(SS))
10525 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10526 << Record << SS.getRange();
10527
10528 // C++0x [temp.explicit]p2:
10529 // There are two forms of explicit instantiation: an explicit instantiation
10530 // definition and an explicit instantiation declaration. An explicit
10531 // instantiation declaration begins with the extern keyword. [...]
10532 TemplateSpecializationKind TSK
10533 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10534 : TSK_ExplicitInstantiationDeclaration;
10535
10536 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10537
10538 // Verify that it is okay to explicitly instantiate here.
10539 CXXRecordDecl *PrevDecl
10540 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10541 if (!PrevDecl && Record->getDefinition())
10542 PrevDecl = Record;
10543 if (PrevDecl) {
10544 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10545 bool HasNoEffect = false;
10546 assert(MSInfo && "No member specialization information?");
10547 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10548 PrevDecl,
10549 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10550 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10551 HasNoEffect))
10552 return true;
10553 if (HasNoEffect)
10554 return TagD;
10555 }
10556
10557 CXXRecordDecl *RecordDef
10558 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10559 if (!RecordDef) {
10560 // C++ [temp.explicit]p3:
10561 // A definition of a member class of a class template shall be in scope
10562 // at the point of an explicit instantiation of the member class.
10563 CXXRecordDecl *Def
10564 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10565 if (!Def) {
10566 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10567 << 0 << Record->getDeclName() << Record->getDeclContext();
10568 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10569 << Pattern;
10570 return true;
10571 } else {
10572 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10573 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10574 TSK))
10575 return true;
10576
10577 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10578 if (!RecordDef)
10579 return true;
10580 }
10581 }
10582
10583 // Instantiate all of the members of the class.
10584 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10585 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10586
10587 if (TSK == TSK_ExplicitInstantiationDefinition)
10588 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10589
10590 // FIXME: We don't have any representation for explicit instantiations of
10591 // member classes. Such a representation is not needed for compilation, but it
10592 // should be available for clients that want to see all of the declarations in
10593 // the source code.
10594 return TagD;
10595}
10596
10597DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10598 SourceLocation ExternLoc,
10599 SourceLocation TemplateLoc,
10600 Declarator &D) {
10601 // Explicit instantiations always require a name.
10602 // TODO: check if/when DNInfo should replace Name.
10603 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10604 DeclarationName Name = NameInfo.getName();
10605 if (!Name) {
10606 if (!D.isInvalidType())
10607 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10608 DiagID: diag::err_explicit_instantiation_requires_name)
10609 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10610
10611 return true;
10612 }
10613
10614 // Get the innermost enclosing declaration scope.
10615 S = S->getDeclParent();
10616
10617 // Determine the type of the declaration.
10618 TypeSourceInfo *T = GetTypeForDeclarator(D);
10619 QualType R = T->getType();
10620 if (R.isNull())
10621 return true;
10622
10623 // C++ [dcl.stc]p1:
10624 // A storage-class-specifier shall not be specified in [...] an explicit
10625 // instantiation (14.7.2) directive.
10626 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10627 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10628 << Name;
10629 return true;
10630 } else if (D.getDeclSpec().getStorageClassSpec()
10631 != DeclSpec::SCS_unspecified) {
10632 // Complain about then remove the storage class specifier.
10633 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10634 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10635
10636 D.getMutableDeclSpec().ClearStorageClassSpecs();
10637 }
10638
10639 // C++0x [temp.explicit]p1:
10640 // [...] An explicit instantiation of a function template shall not use the
10641 // inline or constexpr specifiers.
10642 // Presumably, this also applies to member functions of class templates as
10643 // well.
10644 if (D.getDeclSpec().isInlineSpecified())
10645 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10646 DiagID: getLangOpts().CPlusPlus11 ?
10647 diag::err_explicit_instantiation_inline :
10648 diag::warn_explicit_instantiation_inline_0x)
10649 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10650 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10651 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10652 // not already specified.
10653 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10654 DiagID: diag::err_explicit_instantiation_constexpr);
10655
10656 // A deduction guide is not on the list of entities that can be explicitly
10657 // instantiated.
10658 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10659 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10660 << /*explicit instantiation*/ 0;
10661 return true;
10662 }
10663
10664 // C++0x [temp.explicit]p2:
10665 // There are two forms of explicit instantiation: an explicit instantiation
10666 // definition and an explicit instantiation declaration. An explicit
10667 // instantiation declaration begins with the extern keyword. [...]
10668 TemplateSpecializationKind TSK
10669 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10670 : TSK_ExplicitInstantiationDeclaration;
10671
10672 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10673 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10674 /*ObjectType=*/QualType());
10675
10676 if (!R->isFunctionType()) {
10677 // C++ [temp.explicit]p1:
10678 // A [...] static data member of a class template can be explicitly
10679 // instantiated from the member definition associated with its class
10680 // template.
10681 // C++1y [temp.explicit]p1:
10682 // A [...] variable [...] template specialization can be explicitly
10683 // instantiated from its template.
10684 if (Previous.isAmbiguous())
10685 return true;
10686
10687 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10688 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10689
10690 if (!PrevTemplate) {
10691 if (!Prev || !Prev->isStaticDataMember()) {
10692 // We expect to see a static data member here.
10693 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10694 << Name;
10695 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10696 P != PEnd; ++P)
10697 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10698 return true;
10699 }
10700
10701 if (!Prev->getInstantiatedFromStaticDataMember()) {
10702 // FIXME: Check for explicit specialization?
10703 Diag(Loc: D.getIdentifierLoc(),
10704 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10705 << Prev;
10706 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10707 // FIXME: Can we provide a note showing where this was declared?
10708 return true;
10709 }
10710 } else {
10711 // Explicitly instantiate a variable template.
10712
10713 // C++1y [dcl.spec.auto]p6:
10714 // ... A program that uses auto or decltype(auto) in a context not
10715 // explicitly allowed in this section is ill-formed.
10716 //
10717 // This includes auto-typed variable template instantiations.
10718 if (R->isUndeducedType()) {
10719 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10720 DiagID: diag::err_auto_not_allowed_var_inst);
10721 return true;
10722 }
10723
10724 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10725 // C++1y [temp.explicit]p3:
10726 // If the explicit instantiation is for a variable, the unqualified-id
10727 // in the declaration shall be a template-id.
10728 Diag(Loc: D.getIdentifierLoc(),
10729 DiagID: diag::err_explicit_instantiation_without_template_id)
10730 << PrevTemplate;
10731 Diag(Loc: PrevTemplate->getLocation(),
10732 DiagID: diag::note_explicit_instantiation_here);
10733 return true;
10734 }
10735
10736 // Translate the parser's template argument list into our AST format.
10737 TemplateArgumentListInfo TemplateArgs =
10738 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10739
10740 DeclResult Res =
10741 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10742 TemplateArgs, /*SetWrittenArgs=*/true);
10743 if (Res.isInvalid())
10744 return true;
10745
10746 if (!Res.isUsable()) {
10747 // We somehow specified dependent template arguments in an explicit
10748 // instantiation. This should probably only happen during error
10749 // recovery.
10750 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10751 return true;
10752 }
10753
10754 // Ignore access control bits, we don't need them for redeclaration
10755 // checking.
10756 Prev = cast<VarDecl>(Val: Res.get());
10757 }
10758
10759 // C++0x [temp.explicit]p2:
10760 // If the explicit instantiation is for a member function, a member class
10761 // or a static data member of a class template specialization, the name of
10762 // the class template specialization in the qualified-id for the member
10763 // name shall be a simple-template-id.
10764 //
10765 // C++98 has the same restriction, just worded differently.
10766 //
10767 // This does not apply to variable template specializations, where the
10768 // template-id is in the unqualified-id instead.
10769 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10770 Diag(Loc: D.getIdentifierLoc(),
10771 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10772 << Prev << D.getCXXScopeSpec().getRange();
10773
10774 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10775
10776 // Verify that it is okay to explicitly instantiate here.
10777 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10778 SourceLocation POI = Prev->getPointOfInstantiation();
10779 bool HasNoEffect = false;
10780 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10781 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10782 return true;
10783
10784 if (!HasNoEffect) {
10785 // Instantiate static data member or variable template.
10786 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10787 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10788 VTSD->setExternKeywordLoc(ExternLoc);
10789 VTSD->setTemplateKeywordLoc(TemplateLoc);
10790 }
10791
10792 // Merge attributes.
10793 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10794 if (PrevTemplate)
10795 ProcessAPINotes(D: Prev);
10796
10797 if (TSK == TSK_ExplicitInstantiationDefinition)
10798 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10799 }
10800
10801 // Check the new variable specialization against the parsed input.
10802 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10803 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10804 DiagID: diag::err_invalid_var_template_spec_type)
10805 << 0 << PrevTemplate << R << Prev->getType();
10806 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10807 << 2 << PrevTemplate->getDeclName();
10808 return true;
10809 }
10810
10811 // FIXME: Create an ExplicitInstantiation node?
10812 return (Decl*) nullptr;
10813 }
10814
10815 // If the declarator is a template-id, translate the parser's template
10816 // argument list into our AST format.
10817 bool HasExplicitTemplateArgs = false;
10818 TemplateArgumentListInfo TemplateArgs;
10819 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10820 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10821 HasExplicitTemplateArgs = true;
10822 }
10823
10824 // C++ [temp.explicit]p1:
10825 // A [...] function [...] can be explicitly instantiated from its template.
10826 // A member function [...] of a class template can be explicitly
10827 // instantiated from the member definition associated with its class
10828 // template.
10829 UnresolvedSet<8> TemplateMatches;
10830 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10831 OverloadCandidateSet::CSK_Normal);
10832 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10833 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10834 P != PEnd; ++P) {
10835 NamedDecl *Prev = *P;
10836 if (!HasExplicitTemplateArgs) {
10837 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10838 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10839 /*AdjustExceptionSpec*/true);
10840 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10841 if (Method->getPrimaryTemplate()) {
10842 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10843 } else {
10844 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10845 C.FoundDecl = P.getPair();
10846 C.Function = Method;
10847 C.Viable = true;
10848 ConstraintSatisfaction S;
10849 if (Method->getTrailingRequiresClause() &&
10850 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10851 /*ForOverloadResolution=*/true) ||
10852 !S.IsSatisfied)) {
10853 C.Viable = false;
10854 C.FailureKind = ovl_fail_constraints_not_satisfied;
10855 }
10856 }
10857 }
10858 }
10859 }
10860
10861 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10862 if (!FunTmpl)
10863 continue;
10864
10865 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10866 FunctionDecl *Specialization = nullptr;
10867 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10868 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10869 Specialization, Info);
10870 TDK != TemplateDeductionResult::Success) {
10871 // Keep track of almost-matches.
10872 FailedTemplateCandidates.addCandidate().set(
10873 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10874 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10875 (void)TDK;
10876 continue;
10877 }
10878
10879 // Target attributes are part of the cuda function signature, so
10880 // the cuda target of the instantiated function must match that of its
10881 // template. Given that C++ template deduction does not take
10882 // target attributes into account, we reject candidates here that
10883 // have a different target.
10884 if (LangOpts.CUDA &&
10885 CUDA().IdentifyTarget(D: Specialization,
10886 /* IgnoreImplicitHDAttr = */ true) !=
10887 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10888 FailedTemplateCandidates.addCandidate().set(
10889 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10890 Info: MakeDeductionFailureInfo(
10891 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10892 continue;
10893 }
10894
10895 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10896 }
10897
10898 FunctionDecl *Specialization = nullptr;
10899 if (!NonTemplateMatches.empty()) {
10900 unsigned Msg = 0;
10901 OverloadCandidateDisplayKind DisplayKind;
10902 OverloadCandidateSet::iterator Best;
10903 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10904 Best)) {
10905 case OR_Success:
10906 case OR_Deleted:
10907 Specialization = cast<FunctionDecl>(Val: Best->Function);
10908 break;
10909 case OR_Ambiguous:
10910 Msg = diag::err_explicit_instantiation_ambiguous;
10911 DisplayKind = OCD_AmbiguousCandidates;
10912 break;
10913 case OR_No_Viable_Function:
10914 Msg = diag::err_explicit_instantiation_no_candidate;
10915 DisplayKind = OCD_AllCandidates;
10916 break;
10917 }
10918 if (Msg) {
10919 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
10920 NonTemplateMatches.NoteCandidates(
10921 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10922 Args: {});
10923 return true;
10924 }
10925 }
10926
10927 if (!Specialization) {
10928 // Find the most specialized function template specialization.
10929 UnresolvedSetIterator Result = getMostSpecialized(
10930 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
10931 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
10932 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
10933 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
10934 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
10935
10936 if (Result == TemplateMatches.end())
10937 return true;
10938
10939 // Ignore access control bits, we don't need them for redeclaration checking.
10940 Specialization = cast<FunctionDecl>(Val: *Result);
10941 }
10942
10943 // C++11 [except.spec]p4
10944 // In an explicit instantiation an exception-specification may be specified,
10945 // but is not required.
10946 // If an exception-specification is specified in an explicit instantiation
10947 // directive, it shall be compatible with the exception-specifications of
10948 // other declarations of that function.
10949 if (auto *FPT = R->getAs<FunctionProtoType>())
10950 if (FPT->hasExceptionSpec()) {
10951 unsigned DiagID =
10952 diag::err_mismatched_exception_spec_explicit_instantiation;
10953 if (getLangOpts().MicrosoftExt)
10954 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10955 bool Result = CheckEquivalentExceptionSpec(
10956 DiagID: PDiag(DiagID) << Specialization->getType(),
10957 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
10958 Old: Specialization->getType()->getAs<FunctionProtoType>(),
10959 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
10960 // In Microsoft mode, mismatching exception specifications just cause a
10961 // warning.
10962 if (!getLangOpts().MicrosoftExt && Result)
10963 return true;
10964 }
10965
10966 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10967 Diag(Loc: D.getIdentifierLoc(),
10968 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
10969 << Specialization
10970 << (Specialization->getTemplateSpecializationKind() ==
10971 TSK_ExplicitSpecialization);
10972 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10973 return true;
10974 }
10975
10976 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10977 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10978 PrevDecl = Specialization;
10979
10980 if (PrevDecl) {
10981 bool HasNoEffect = false;
10982 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
10983 PrevDecl,
10984 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
10985 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10986 HasNoEffect))
10987 return true;
10988
10989 // FIXME: We may still want to build some representation of this
10990 // explicit specialization.
10991 if (HasNoEffect)
10992 return (Decl*) nullptr;
10993 }
10994
10995 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10996 // functions
10997 // valarray<size_t>::valarray(size_t) and
10998 // valarray<size_t>::~valarray()
10999 // that it declared to have internal linkage with the internal_linkage
11000 // attribute. Ignore the explicit instantiation declaration in this case.
11001 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11002 TSK == TSK_ExplicitInstantiationDeclaration) {
11003 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11004 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11005 RD->isInStdNamespace())
11006 return (Decl*) nullptr;
11007 }
11008
11009 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11010 ProcessAPINotes(D: Specialization);
11011
11012 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11013 // instantiation declarations.
11014 if (TSK == TSK_ExplicitInstantiationDefinition &&
11015 Specialization->hasAttr<DLLImportAttr>() &&
11016 Context.getTargetInfo().getCXXABI().isMicrosoft())
11017 TSK = TSK_ExplicitInstantiationDeclaration;
11018
11019 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11020
11021 if (Specialization->isDefined()) {
11022 // Let the ASTConsumer know that this function has been explicitly
11023 // instantiated now, and its linkage might have changed.
11024 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11025 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11026 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11027
11028 // C++0x [temp.explicit]p2:
11029 // If the explicit instantiation is for a member function, a member class
11030 // or a static data member of a class template specialization, the name of
11031 // the class template specialization in the qualified-id for the member
11032 // name shall be a simple-template-id.
11033 //
11034 // C++98 has the same restriction, just worded differently.
11035 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11036 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11037 D.getCXXScopeSpec().isSet() &&
11038 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11039 Diag(Loc: D.getIdentifierLoc(),
11040 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11041 << Specialization << D.getCXXScopeSpec().getRange();
11042
11043 CheckExplicitInstantiation(
11044 S&: *this,
11045 D: FunTmpl ? (NamedDecl *)FunTmpl
11046 : Specialization->getInstantiatedFromMemberFunction(),
11047 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11048
11049 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11050 return (Decl*) nullptr;
11051}
11052
11053TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11054 const CXXScopeSpec &SS,
11055 const IdentifierInfo *Name,
11056 SourceLocation TagLoc,
11057 SourceLocation NameLoc) {
11058 // This has to hold, because SS is expected to be defined.
11059 assert(Name && "Expected a name in a dependent tag");
11060
11061 NestedNameSpecifier NNS = SS.getScopeRep();
11062 if (!NNS)
11063 return true;
11064
11065 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11066
11067 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11068 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11069 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11070 return true;
11071 }
11072
11073 // Create the resulting type.
11074 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11075 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11076
11077 // Create type-source location information for this type.
11078 TypeLocBuilder TLB;
11079 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11080 TL.setElaboratedKeywordLoc(TagLoc);
11081 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11082 TL.setNameLoc(NameLoc);
11083 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11084}
11085
11086TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11087 const CXXScopeSpec &SS,
11088 const IdentifierInfo &II,
11089 SourceLocation IdLoc,
11090 ImplicitTypenameContext IsImplicitTypename) {
11091 if (SS.isInvalid())
11092 return true;
11093
11094 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11095 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11096 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11097
11098 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11099 TypeSourceInfo *TSI = nullptr;
11100 QualType T =
11101 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11102 : ElaboratedTypeKeyword::None,
11103 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11104 /*DeducedTSTContext=*/true);
11105 if (T.isNull())
11106 return true;
11107 return CreateParsedType(T, TInfo: TSI);
11108}
11109
11110TypeResult
11111Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11112 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11113 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11114 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11115 ASTTemplateArgsPtr TemplateArgsIn,
11116 SourceLocation RAngleLoc) {
11117 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11118 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11119 ? diag::compat_cxx11_typename_outside_of_template
11120 : diag::compat_pre_cxx11_typename_outside_of_template)
11121 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11122
11123 // Strangely, non-type results are not ignored by this lookup, so the
11124 // program is ill-formed if it finds an injected-class-name.
11125 if (TypenameLoc.isValid()) {
11126 auto *LookupRD =
11127 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11128 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11129 Diag(Loc: TemplateIILoc,
11130 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11131 << TemplateII << 0 /*injected-class-name used as template name*/
11132 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11133 }
11134 }
11135
11136 // Translate the parser's template argument list in our AST format.
11137 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11138 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11139
11140 QualType T = CheckTemplateIdType(
11141 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11142 : ElaboratedTypeKeyword::None,
11143 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11144 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11145 if (T.isNull())
11146 return true;
11147
11148 // Provide source-location information for the template specialization type.
11149 TypeLocBuilder Builder;
11150 TemplateSpecializationTypeLoc SpecTL
11151 = Builder.push<TemplateSpecializationTypeLoc>(T);
11152 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11153 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11154 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11155 return CreateParsedType(T, TInfo: TSI);
11156}
11157
11158/// Determine whether this failed name lookup should be treated as being
11159/// disabled by a usage of std::enable_if.
11160static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11161 SourceRange &CondRange, Expr *&Cond) {
11162 // We must be looking for a ::type...
11163 if (!II.isStr(Str: "type"))
11164 return false;
11165
11166 // ... within an explicitly-written template specialization...
11167 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11168 return false;
11169
11170 // FIXME: Look through sugar.
11171 auto EnableIfTSTLoc =
11172 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11173 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11174 return false;
11175 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11176
11177 // ... which names a complete class template declaration...
11178 const TemplateDecl *EnableIfDecl =
11179 EnableIfTST->getTemplateName().getAsTemplateDecl();
11180 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11181 return false;
11182
11183 // ... called "enable_if".
11184 const IdentifierInfo *EnableIfII =
11185 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11186 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11187 return false;
11188
11189 // Assume the first template argument is the condition.
11190 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11191
11192 // Dig out the condition.
11193 Cond = nullptr;
11194 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11195 != TemplateArgument::Expression)
11196 return true;
11197
11198 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11199
11200 // Ignore Boolean literals; they add no value.
11201 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11202 Cond = nullptr;
11203
11204 return true;
11205}
11206
11207QualType
11208Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11209 SourceLocation KeywordLoc,
11210 NestedNameSpecifierLoc QualifierLoc,
11211 const IdentifierInfo &II,
11212 SourceLocation IILoc,
11213 TypeSourceInfo **TSI,
11214 bool DeducedTSTContext) {
11215 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11216 DeducedTSTContext);
11217 if (T.isNull())
11218 return QualType();
11219
11220 TypeLocBuilder TLB;
11221 if (isa<DependentNameType>(Val: T)) {
11222 auto TL = TLB.push<DependentNameTypeLoc>(T);
11223 TL.setElaboratedKeywordLoc(KeywordLoc);
11224 TL.setQualifierLoc(QualifierLoc);
11225 TL.setNameLoc(IILoc);
11226 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11227 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11228 TL.setElaboratedKeywordLoc(KeywordLoc);
11229 TL.setQualifierLoc(QualifierLoc);
11230 TL.setNameLoc(IILoc);
11231 } else if (isa<TemplateTypeParmType>(Val: T)) {
11232 // FIXME: There might be a 'typename' keyword here, but we just drop it
11233 // as it can't be represented.
11234 assert(!QualifierLoc);
11235 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11236 } else if (isa<TagType>(Val: T)) {
11237 auto TL = TLB.push<TagTypeLoc>(T);
11238 TL.setElaboratedKeywordLoc(KeywordLoc);
11239 TL.setQualifierLoc(QualifierLoc);
11240 TL.setNameLoc(IILoc);
11241 } else if (isa<TypedefType>(Val: T)) {
11242 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11243 } else {
11244 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11245 }
11246 *TSI = TLB.getTypeSourceInfo(Context, T);
11247 return T;
11248}
11249
11250/// Build the type that describes a C++ typename specifier,
11251/// e.g., "typename T::type".
11252QualType
11253Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11254 SourceLocation KeywordLoc,
11255 NestedNameSpecifierLoc QualifierLoc,
11256 const IdentifierInfo &II,
11257 SourceLocation IILoc, bool DeducedTSTContext) {
11258 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11259
11260 CXXScopeSpec SS;
11261 SS.Adopt(Other: QualifierLoc);
11262
11263 DeclContext *Ctx = nullptr;
11264 if (QualifierLoc) {
11265 Ctx = computeDeclContext(SS);
11266 if (!Ctx) {
11267 // If the nested-name-specifier is dependent and couldn't be
11268 // resolved to a type, build a typename type.
11269 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11270 return Context.getDependentNameType(Keyword,
11271 NNS: QualifierLoc.getNestedNameSpecifier(),
11272 Name: &II);
11273 }
11274
11275 // If the nested-name-specifier refers to the current instantiation,
11276 // the "typename" keyword itself is superfluous. In C++03, the
11277 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11278 // allows such extraneous "typename" keywords, and we retroactively
11279 // apply this DR to C++03 code with only a warning. In any case we continue.
11280
11281 if (RequireCompleteDeclContext(SS, DC: Ctx))
11282 return QualType();
11283 }
11284
11285 DeclarationName Name(&II);
11286 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11287 if (Ctx)
11288 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11289 else
11290 LookupName(R&: Result, S: CurScope);
11291 unsigned DiagID = 0;
11292 Decl *Referenced = nullptr;
11293 switch (Result.getResultKind()) {
11294 case LookupResultKind::NotFound: {
11295 // If we're looking up 'type' within a template named 'enable_if', produce
11296 // a more specific diagnostic.
11297 SourceRange CondRange;
11298 Expr *Cond = nullptr;
11299 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11300 // If we have a condition, narrow it down to the specific failed
11301 // condition.
11302 if (Cond) {
11303 Expr *FailedCond;
11304 std::string FailedDescription;
11305 std::tie(args&: FailedCond, args&: FailedDescription) =
11306 findFailedBooleanCondition(Cond);
11307
11308 Diag(Loc: FailedCond->getExprLoc(),
11309 DiagID: diag::err_typename_nested_not_found_requirement)
11310 << FailedDescription
11311 << FailedCond->getSourceRange();
11312 return QualType();
11313 }
11314
11315 Diag(Loc: CondRange.getBegin(),
11316 DiagID: diag::err_typename_nested_not_found_enable_if)
11317 << Ctx << CondRange;
11318 return QualType();
11319 }
11320
11321 DiagID = Ctx ? diag::err_typename_nested_not_found
11322 : diag::err_unknown_typename;
11323 break;
11324 }
11325
11326 case LookupResultKind::FoundUnresolvedValue: {
11327 // We found a using declaration that is a value. Most likely, the using
11328 // declaration itself is meant to have the 'typename' keyword.
11329 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11330 IILoc);
11331 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11332 << Name << Ctx << FullRange;
11333 if (UnresolvedUsingValueDecl *Using
11334 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11335 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11336 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11337 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11338 }
11339 }
11340 // Fall through to create a dependent typename type, from which we can
11341 // recover better.
11342 [[fallthrough]];
11343
11344 case LookupResultKind::NotFoundInCurrentInstantiation:
11345 // Okay, it's a member of an unknown instantiation.
11346 return Context.getDependentNameType(Keyword,
11347 NNS: QualifierLoc.getNestedNameSpecifier(),
11348 Name: &II);
11349
11350 case LookupResultKind::Found:
11351 // FXIME: Missing support for UsingShadowDecl on this path?
11352 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11353 // C++ [class.qual]p2:
11354 // In a lookup in which function names are not ignored and the
11355 // nested-name-specifier nominates a class C, if the name specified
11356 // after the nested-name-specifier, when looked up in C, is the
11357 // injected-class-name of C [...] then the name is instead considered
11358 // to name the constructor of class C.
11359 //
11360 // Unlike in an elaborated-type-specifier, function names are not ignored
11361 // in typename-specifier lookup. However, they are ignored in all the
11362 // contexts where we form a typename type with no keyword (that is, in
11363 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11364 //
11365 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11366 // ignore functions, but that appears to be an oversight.
11367 checkTypeDeclType(LookupCtx: Ctx,
11368 DCK: Keyword == ElaboratedTypeKeyword::Typename
11369 ? DiagCtorKind::Typename
11370 : DiagCtorKind::None,
11371 TD: Type, NameLoc: IILoc);
11372 // FIXME: This appears to be the only case where a template type parameter
11373 // can have an elaborated keyword. We should preserve it somehow.
11374 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11375 assert(Keyword == ElaboratedTypeKeyword::Typename);
11376 assert(!QualifierLoc);
11377 Keyword = ElaboratedTypeKeyword::None;
11378 }
11379 return Context.getTypeDeclType(
11380 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11381 }
11382
11383 // C++ [dcl.type.simple]p2:
11384 // A type-specifier of the form
11385 // typename[opt] nested-name-specifier[opt] template-name
11386 // is a placeholder for a deduced class type [...].
11387 if (getLangOpts().CPlusPlus17) {
11388 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11389 if (!DeducedTSTContext) {
11390 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11391 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11392 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11393 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11394 << QualType(Qualifier.getAsType(), 0);
11395 else
11396 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11397 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11398 NoteTemplateLocation(Decl: *TD);
11399 return QualType();
11400 }
11401 TemplateName Name = Context.getQualifiedTemplateName(
11402 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11403 Template: TemplateName(TD));
11404 return Context.getDeducedTemplateSpecializationType(
11405 Keyword, Template: Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);
11406 }
11407 }
11408
11409 DiagID = Ctx ? diag::err_typename_nested_not_type
11410 : diag::err_typename_not_type;
11411 Referenced = Result.getFoundDecl();
11412 break;
11413
11414 case LookupResultKind::FoundOverloaded:
11415 DiagID = Ctx ? diag::err_typename_nested_not_type
11416 : diag::err_typename_not_type;
11417 Referenced = *Result.begin();
11418 break;
11419
11420 case LookupResultKind::Ambiguous:
11421 return QualType();
11422 }
11423
11424 // If we get here, it's because name lookup did not find a
11425 // type. Emit an appropriate diagnostic and return an error.
11426 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11427 IILoc);
11428 if (Ctx)
11429 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11430 else
11431 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11432 if (Referenced)
11433 Diag(Loc: Referenced->getLocation(),
11434 DiagID: Ctx ? diag::note_typename_member_refers_here
11435 : diag::note_typename_refers_here)
11436 << Name;
11437 return QualType();
11438}
11439
11440namespace {
11441 // See Sema::RebuildTypeInCurrentInstantiation
11442 class CurrentInstantiationRebuilder
11443 : public TreeTransform<CurrentInstantiationRebuilder> {
11444 SourceLocation Loc;
11445 DeclarationName Entity;
11446
11447 public:
11448 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11449
11450 CurrentInstantiationRebuilder(Sema &SemaRef,
11451 SourceLocation Loc,
11452 DeclarationName Entity)
11453 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11454 Loc(Loc), Entity(Entity) { }
11455
11456 /// Determine whether the given type \p T has already been
11457 /// transformed.
11458 ///
11459 /// For the purposes of type reconstruction, a type has already been
11460 /// transformed if it is NULL or if it is not dependent.
11461 bool AlreadyTransformed(QualType T) {
11462 return T.isNull() || !T->isInstantiationDependentType();
11463 }
11464
11465 /// Returns the location of the entity whose type is being
11466 /// rebuilt.
11467 SourceLocation getBaseLocation() { return Loc; }
11468
11469 /// Returns the name of the entity whose type is being rebuilt.
11470 DeclarationName getBaseEntity() { return Entity; }
11471
11472 /// Sets the "base" location and entity when that
11473 /// information is known based on another transformation.
11474 void setBase(SourceLocation Loc, DeclarationName Entity) {
11475 this->Loc = Loc;
11476 this->Entity = Entity;
11477 }
11478
11479 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11480 // Lambdas never need to be transformed.
11481 return E;
11482 }
11483 };
11484} // end anonymous namespace
11485
11486TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11487 SourceLocation Loc,
11488 DeclarationName Name) {
11489 if (!T || !T->getType()->isInstantiationDependentType())
11490 return T;
11491
11492 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11493 return Rebuilder.TransformType(TSI: T);
11494}
11495
11496ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11497 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11498 DeclarationName());
11499 return Rebuilder.TransformExpr(E);
11500}
11501
11502bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11503 if (SS.isInvalid())
11504 return true;
11505
11506 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11507 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11508 DeclarationName());
11509 NestedNameSpecifierLoc Rebuilt
11510 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11511 if (!Rebuilt)
11512 return true;
11513
11514 SS.Adopt(Other: Rebuilt);
11515 return false;
11516}
11517
11518bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11519 TemplateParameterList *Params) {
11520 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11521 Decl *Param = Params->getParam(Idx: I);
11522
11523 // There is nothing to rebuild in a type parameter.
11524 if (isa<TemplateTypeParmDecl>(Val: Param))
11525 continue;
11526
11527 // Rebuild the template parameter list of a template template parameter.
11528 if (TemplateTemplateParmDecl *TTP
11529 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11530 if (RebuildTemplateParamsInCurrentInstantiation(
11531 Params: TTP->getTemplateParameters()))
11532 return true;
11533
11534 continue;
11535 }
11536
11537 // Rebuild the type of a non-type template parameter.
11538 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11539 TypeSourceInfo *NewTSI
11540 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11541 Loc: NTTP->getLocation(),
11542 Name: NTTP->getDeclName());
11543 if (!NewTSI)
11544 return true;
11545
11546 if (NewTSI->getType()->isUndeducedType()) {
11547 // C++17 [temp.dep.expr]p3:
11548 // An id-expression is type-dependent if it contains
11549 // - an identifier associated by name lookup with a non-type
11550 // template-parameter declared with a type that contains a
11551 // placeholder type (7.1.7.4),
11552 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11553 }
11554
11555 if (NewTSI != NTTP->getTypeSourceInfo()) {
11556 NTTP->setTypeSourceInfo(NewTSI);
11557 NTTP->setType(NewTSI->getType());
11558 }
11559 }
11560
11561 return false;
11562}
11563
11564std::string
11565Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11566 const TemplateArgumentList &Args) {
11567 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11568}
11569
11570std::string
11571Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11572 const TemplateArgument *Args,
11573 unsigned NumArgs) {
11574 SmallString<128> Str;
11575 llvm::raw_svector_ostream Out(Str);
11576
11577 if (!Params || Params->size() == 0 || NumArgs == 0)
11578 return std::string();
11579
11580 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11581 if (I >= NumArgs)
11582 break;
11583
11584 if (I == 0)
11585 Out << "[with ";
11586 else
11587 Out << ", ";
11588
11589 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11590 Out << Id->getName();
11591 } else {
11592 Out << '$' << I;
11593 }
11594
11595 Out << " = ";
11596 Args[I].print(Policy: getPrintingPolicy(), Out,
11597 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11598 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11599 }
11600
11601 Out << ']';
11602 return std::string(Out.str());
11603}
11604
11605void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11606 CachedTokens &Toks) {
11607 if (!FD)
11608 return;
11609
11610 auto LPT = std::make_unique<LateParsedTemplate>();
11611
11612 // Take tokens to avoid allocations
11613 LPT->Toks.swap(RHS&: Toks);
11614 LPT->D = FnD;
11615 LPT->FPO = getCurFPFeatures();
11616 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11617
11618 FD->setLateTemplateParsed(true);
11619}
11620
11621void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11622 if (!FD)
11623 return;
11624 FD->setLateTemplateParsed(false);
11625}
11626
11627bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11628 DeclContext *DC = CurContext;
11629
11630 while (DC) {
11631 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11632 const FunctionDecl *FD = RD->isLocalClass();
11633 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11634 } else if (DC->isTranslationUnit() || DC->isNamespace())
11635 return false;
11636
11637 DC = DC->getParent();
11638 }
11639 return false;
11640}
11641
11642namespace {
11643/// Walk the path from which a declaration was instantiated, and check
11644/// that every explicit specialization along that path is visible. This enforces
11645/// C++ [temp.expl.spec]/6:
11646///
11647/// If a template, a member template or a member of a class template is
11648/// explicitly specialized then that specialization shall be declared before
11649/// the first use of that specialization that would cause an implicit
11650/// instantiation to take place, in every translation unit in which such a
11651/// use occurs; no diagnostic is required.
11652///
11653/// and also C++ [temp.class.spec]/1:
11654///
11655/// A partial specialization shall be declared before the first use of a
11656/// class template specialization that would make use of the partial
11657/// specialization as the result of an implicit or explicit instantiation
11658/// in every translation unit in which such a use occurs; no diagnostic is
11659/// required.
11660class ExplicitSpecializationVisibilityChecker {
11661 Sema &S;
11662 SourceLocation Loc;
11663 llvm::SmallVector<Module *, 8> Modules;
11664 Sema::AcceptableKind Kind;
11665
11666public:
11667 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11668 Sema::AcceptableKind Kind)
11669 : S(S), Loc(Loc), Kind(Kind) {}
11670
11671 void check(NamedDecl *ND) {
11672 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11673 return checkImpl(Spec: FD);
11674 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11675 return checkImpl(Spec: RD);
11676 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11677 return checkImpl(Spec: VD);
11678 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11679 return checkImpl(Spec: ED);
11680 }
11681
11682private:
11683 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11684 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11685 : Sema::MissingImportKind::ExplicitSpecialization;
11686 const bool Recover = true;
11687
11688 // If we got a custom set of modules (because only a subset of the
11689 // declarations are interesting), use them, otherwise let
11690 // diagnoseMissingImport intelligently pick some.
11691 if (Modules.empty())
11692 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11693 else
11694 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11695 }
11696
11697 bool CheckMemberSpecialization(const NamedDecl *D) {
11698 return Kind == Sema::AcceptableKind::Visible
11699 ? S.hasVisibleMemberSpecialization(D)
11700 : S.hasReachableMemberSpecialization(D);
11701 }
11702
11703 bool CheckExplicitSpecialization(const NamedDecl *D) {
11704 return Kind == Sema::AcceptableKind::Visible
11705 ? S.hasVisibleExplicitSpecialization(D)
11706 : S.hasReachableExplicitSpecialization(D);
11707 }
11708
11709 bool CheckDeclaration(const NamedDecl *D) {
11710 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11711 : S.hasReachableDeclaration(D);
11712 }
11713
11714 // Check a specific declaration. There are three problematic cases:
11715 //
11716 // 1) The declaration is an explicit specialization of a template
11717 // specialization.
11718 // 2) The declaration is an explicit specialization of a member of an
11719 // templated class.
11720 // 3) The declaration is an instantiation of a template, and that template
11721 // is an explicit specialization of a member of a templated class.
11722 //
11723 // We don't need to go any deeper than that, as the instantiation of the
11724 // surrounding class / etc is not triggered by whatever triggered this
11725 // instantiation, and thus should be checked elsewhere.
11726 template<typename SpecDecl>
11727 void checkImpl(SpecDecl *Spec) {
11728 bool IsHiddenExplicitSpecialization = false;
11729 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11730 // Some invalid friend declarations are written as specializations but are
11731 // instantiated implicitly.
11732 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11733 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11734 if (SpecKind == TSK_ExplicitSpecialization) {
11735 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11736 ? !CheckMemberSpecialization(D: Spec)
11737 : !CheckExplicitSpecialization(D: Spec);
11738 } else {
11739 checkInstantiated(Spec);
11740 }
11741
11742 if (IsHiddenExplicitSpecialization)
11743 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11744 }
11745
11746 void checkInstantiated(FunctionDecl *FD) {
11747 if (auto *TD = FD->getPrimaryTemplate())
11748 checkTemplate(TD);
11749 }
11750
11751 void checkInstantiated(CXXRecordDecl *RD) {
11752 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11753 if (!SD)
11754 return;
11755
11756 auto From = SD->getSpecializedTemplateOrPartial();
11757 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11758 checkTemplate(TD);
11759 else if (auto *TD =
11760 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11761 if (!CheckDeclaration(D: TD))
11762 diagnose(D: TD, IsPartialSpec: true);
11763 checkTemplate(TD);
11764 }
11765 }
11766
11767 void checkInstantiated(VarDecl *RD) {
11768 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11769 if (!SD)
11770 return;
11771
11772 auto From = SD->getSpecializedTemplateOrPartial();
11773 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11774 checkTemplate(TD);
11775 else if (auto *TD =
11776 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11777 if (!CheckDeclaration(D: TD))
11778 diagnose(D: TD, IsPartialSpec: true);
11779 checkTemplate(TD);
11780 }
11781 }
11782
11783 void checkInstantiated(EnumDecl *FD) {}
11784
11785 template<typename TemplDecl>
11786 void checkTemplate(TemplDecl *TD) {
11787 if (TD->isMemberSpecialization()) {
11788 if (!CheckMemberSpecialization(D: TD))
11789 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11790 }
11791 }
11792};
11793} // end anonymous namespace
11794
11795void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11796 if (!getLangOpts().Modules)
11797 return;
11798
11799 ExplicitSpecializationVisibilityChecker(*this, Loc,
11800 Sema::AcceptableKind::Visible)
11801 .check(ND: Spec);
11802}
11803
11804void Sema::checkSpecializationReachability(SourceLocation Loc,
11805 NamedDecl *Spec) {
11806 if (!getLangOpts().CPlusPlusModules)
11807 return checkSpecializationVisibility(Loc, Spec);
11808
11809 ExplicitSpecializationVisibilityChecker(*this, Loc,
11810 Sema::AcceptableKind::Reachable)
11811 .check(ND: Spec);
11812}
11813
11814SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11815 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11816 return N->getLocation();
11817 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11818 if (!FD->isFunctionTemplateSpecialization())
11819 return FD->getLocation();
11820 } else if (!isa<ClassTemplateSpecializationDecl,
11821 VarTemplateSpecializationDecl>(Val: N)) {
11822 return N->getLocation();
11823 }
11824 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11825 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11826 continue;
11827 return CSC.PointOfInstantiation;
11828 }
11829 return N->getLocation();
11830}
11831